From d5357e074438bc99fdaef201d70f3b780dbcd52e Mon Sep 17 00:00:00 2001 From: troyeguo <13820674+troyeguo@users.noreply.github.com> Date: Thu, 17 Jul 2025 18:02:40 +0800 Subject: [PATCH] fix bug --- src/assets/lib/kookit-extra-browser.min.js | 2 +- src/assets/lib/kookit-extra.min.mjs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/assets/lib/kookit-extra-browser.min.js b/src/assets/lib/kookit-extra-browser.min.js index 799a511f..453a036f 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{SSE as o}from"sse.js";import{isElectron as s}from"react-device-detect";function a(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 c=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,u=["books","notes","bookmarks","plugins","words"],d=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 f{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.hasFailedTasks=!1,this.downloadedSize=0,this.maxConcurrency=e}addTask(e){return a(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{const n=()=>a(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:u,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:d,arrayBufferToBase64:l,generateSHA256Hash:function(e){return a(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):h(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 g={publicUrl:"https://api.960960.xyz",cloudUrl:"https://cloud.960960.xyz",cloudCNUrl:"https://cloud.koodoreader.cn",devUrl:"http://192.168.28.159:8000"},m={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"},y={google:{clientId:m.googleClientId,scopes:["openid email profile"],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{prompt:"consent",scope:"openid email profile"}},microsoft:{clientId:m.microsoftClientId,scopes:["openid","profile","User.Read","offline_access"],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{scope:"openid profile User.Read offline_access"}},facebook:{clientId:m.facebookClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{scope:""}},github:{clientId:m.githubClientId,scopes:["user:email"],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{scope:"user:email"}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{scope:""}}};var v={CloudConfig:g,ThirdpartyConfig:m,LoginAuthRequest:y,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:m.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{token_access_type:"offline"}},boxnet:{clientId:m.boxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}},pcloud:{clientId:m.pcloudClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{grant_type:"authorization_code"}},adrive:{clientId:m.adriveClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}},microsoft:{clientId:m.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{scope:"files.readwrite.appfolder offline_access"}},google:{clientId:m.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive.file",access_type:"offline"}},microsoft_exp:{clientId:m.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{scope:"files.readwrite.all offline_access"}},google_exp:{clientId:m.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:m.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive",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"},microsoft_exp:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google_exp:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"}}};class b{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new f(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=5){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(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 a(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(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(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 console.log("All items:",o),[...new Set(o.map((e=>({name:e.name,size:e.size,type:e.type,modified:e.updated_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(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 a(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 a(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=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:m.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:m.adriveClientId,redirect_uri:m.callbackUrl,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class w extends b{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return new Promise(((n,i)=>a(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)=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});r(a.data)}catch(e){console.error("Error downloading file:",e),r(!1)}}))))}}class k{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new f(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(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(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(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);console.log(i,"folderId");let 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}`}});console.log("Response data:",t.data);const n=t.data.entries||[];o=o.concat(n),s+=n.length,a=n.length===c&&t.data.total_count>s}return console.log("All items:",o),[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:e.type,modified:e.content_modified_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(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 a(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=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:m.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:m.boxClientId,redirect_uri:m.callbackUrl,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class S extends k{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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;console.log(c,"file");const u=yield e({url:`https://api.box.com/2.0/files/${c.id}/content`,method:"get",headers:{Authorization:`Bearer ${r}`},responseType:"arraybuffer",onDownloadProgress:e=>{console.log(e,"progressEvent"),this.taskQueue.setDownloadedSize(e.loaded)}});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 E{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new f(3)}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(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 console.log("Total items fetched:",n),[...new Set(n.map((e=>({name:e.name,size:e.size||0,type:e[".tag"],modified:e.client_modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(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 a(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=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:m.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${m.dropboxClientId}&redirect_uri=${m.callbackUrl}`}}class x extends E{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});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 A{constructor(e,t){this.isExp=!1,this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new f(3),this.isExp=this.config.isExp||!1,void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(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&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 a(this,void 0,void 0,(function*(){t=this.baseFolder+"/"+t;const r=yield this.refreshToken();if(""===t)return"root";const n=t.split("/").filter((e=>""!==e.trim()));let i="root";for(const t of n){let n=yield this.getFolderId(t,i);if(!n){const o={name:t,mimeType:"application/vnd.google-apps.folder",parents:[i]};try{n=(yield e.post("https://www.googleapis.com/drive/v3/files",o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error(`Error occurred during folder creation for ${t}:`,e),e}}i=n}return i}))}getFolderId(t,r){return a(this,void 0,void 0,(function*(){const n=yield this.refreshToken(),i=`https://www.googleapis.com/drive/v3/files?q=name='${t=encodeURIComponent(t)}'+and+mimeType='application/vnd.google-apps.folder'+and+'${r}'+in+parents&fields=files(id,name)`;try{const t=(yield e.get(i,{headers:{Authorization:`Bearer ${n}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(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&fields=nextPageToken,files(id,name,size,mimeType)&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 console.log("Total items fetched:",i),[...new Set(i.map((e=>({name:e.name,size:e.size||0,type:"application/vnd.google-apps.folder"===e.mimeType?"folder":"file",modified:e.modifiedTime}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return a(this,void 0,void 0,(function*(){const r=t.split("/")[1],n=yield this.checkFolder(t),i=yield this.refreshToken(),o=yield this.getFileId(r,n);if(""===o)return console.error("File not found:",r),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${o}`,{headers:{Authorization:`Bearer ${i}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return a(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=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:m.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${m.callbackUrl}&prompt=consent&response_type=code&client_id=${m.googleClientId}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class T extends A{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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(),a=c(s||""),u=r.split("/")[0],d=yield this.checkFolder(u),l=yield this.getFileId(i||"",d);const h={mimeType:a,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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});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 a(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 C{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new f(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(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 a(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 a(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const n=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return a(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=>({name:e.name,size:e.size||0,type:e.directory?"folder":"file",modified:e.timestamp?new Date(1e3*e.timestamp).toISOString():""})));return r}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return a(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 R extends C{constructor(e){super(e)}uploadFile(e,t){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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;const o=yield i.downloadBuffer();return this.taskQueue.setDownloadedSize(o.size),o.buffer}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class O{constructor(e,t){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new f(3),this.isExp=this.config.isExp||!1,this.baseUrl=this.isExp?"https://graph.microsoft.com/v1.0/me/drive/root":"https://graph.microsoft.com/v1.0/me/drive/special/approot",void 0===this.config.baseFolder?this.baseFolder=this.isExp?"KoodoReader":"":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let n,i=[];if(""===t)n=`${this.baseUrl}/children`;else{const e=encodeURIComponent(t);n=`${this.baseUrl}:/${e}:/children`}for(;n;){const t=yield e.get(n,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(t.status>=300)break;const o=t.data.value||[];i=i.concat(o),n=t.data["@odata.nextLink"]||""}return console.log("All items fetched:",i),[...new Set(i.map((e=>({name:e.name,size:e.size||0,type:e.folder?"folder":"file",modified:e.lastModifiedDateTime}))))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const n=yield e.delete(`${this.baseUrl}:/${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 a(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=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:m.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${m.microsoftClientId}&scope=${this.isExp?"files.readwrite.all":"files.readwrite.appfolder"} offline_access&response_type=code&redirect_uri=${m.callbackUrl}`}}class P extends O{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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});for(r=this.baseFolder+"/"+r;r.startsWith("/");)r=r.substring(1);const s=this.baseUrl+":/"+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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const n=`${this.baseUrl}:/${t}:/content`,i=yield e.get(n,{responseType:"arraybuffer",headers:{Authorization:"Bearer "+r},maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});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 _{downloadFile(e,t){return a(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return a(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return a(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return a(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class I{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new f(3)}retryOperation(e,t=5){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(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 a(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(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(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=>({name:e.name,size:e.size||0,type:e.isfolder?"folder":"file",modified:e.modified})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(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 a(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:m.callbackUrl,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${m.pcloudClientId}&response_type=code&redirect_uri=${m.callbackUrl}`}}class M extends I{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});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 N=e=>{let t=e.httpHandler;return{setHttpHandler(e){t=e},httpHandler:()=>t,updateHttpClientConfig(e,r){t.updateHttpClientConfig(e,r)},httpHandlerConfigs:()=>t.httpHandlerConfigs()}};var F,$,U,L,B;!function(e){e.HEADER="header",e.QUERY="query"}(F||(F={})),function(e){e.HEADER="header",e.QUERY="query"}($||($={})),function(e){e.HTTP="http",e.HTTPS="https"}(U||(U={})),function(e){e.MD5="md5",e.CRC32="crc32",e.CRC32C="crc32c",e.SHA1="sha1",e.SHA256="sha256"}(L||(L={})),function(e){e[e.HEADER=0]="HEADER",e[e.TRAILER=1]="TRAILER"}(B||(B={}));const D="__smithy_context";var z,j;!function(e){e.PROFILE="profile",e.SSO_SESSION="sso-session",e.SERVICES="services"}(z||(z={})),function(e){e.HTTP_0_9="http/0.9",e.HTTP_1_0="http/1.0",e.TDS_8_0="tds/8.0"}(j||(j={}));class q{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 q({...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 q.clone(this)}}class H{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 W={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0},K=e=>({applyToStack:t=>{t.add(function(e){return t=>async r=>{const{request:n}=r;return q.isInstance(n)&&n.body&&"node"===e.runtime&&"FetchHttpHandler"!==e.requestHandler?.constructor?.name&&(n.headers={...n.headers,Expect:"100-continue"}),t({...r,request:n})}}(e),W)}}),V="WHEN_SUPPORTED",Q=V,G=V;var J,X;!function(e){e.MD5="MD5",e.CRC32="CRC32",e.CRC32C="CRC32C",e.SHA1="SHA1",e.SHA256="SHA256"}(J||(J={})),function(e){e.HEADER="header",e.TRAILER="trailer"}(X||(X={}));const Z=J.MD5,Y=J.CRC32;var ee;function te(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"}(ee||(ee={}));const re=e=>H.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,ne=e=>new Date(Date.now()+e),ie=(e,t)=>{const r=Date.parse(e);return((e,t)=>Math.abs(ne(t).getTime()-e)>=3e5)(r,t)?r-Date.now():t},oe=(e,t)=>{if(!t)throw new Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},se=async e=>{const t=oe("context",e.context),r=oe("config",e.config),n=t.endpointV2?.properties?.authSchemes?.[0],i=oe("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 ae{async sign(e,t,r){if(!q.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const n=await se(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:ne(i.systemClockOffset),signingRegion:s,signingService:a})}errorHandler(e){return t=>{const r=t.ServerTime??re(t.$response);if(r){const n=oe("config",e.config),i=n.systemClockOffset;n.systemClockOffset=ie(r,n.systemClockOffset);n.systemClockOffset!==i&&t.$metadata&&(t.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const r=re(e);if(r){const e=oe("config",t.config);e.systemClockOffset=ie(r,e.systemClockOffset)}}}class ce extends ae{async sign(e,t,r){if(!q.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 se(r),c=(await(n.sigv4aSigningRegionSet?.())??s??[o]).join(",");return await i.sign(e,{signingDate:ne(n.systemClockOffset),signingRegion:c,signingService:a})}}const ue=e=>e[D]||(e[D]={}),de=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t};const le=(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=ue(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)},he={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},fe={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},pe={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function ge(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),fe),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),pe)}}}const me=e=>e=>{throw e},ye=(e,t)=>{},ve={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},be=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{if(!q.isInstance(r.request))return e(r);const n=ue(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||me)(i));return(s.successHandler||ye)(a.response,i),a}),ve)}}),we=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t},ke={},Se=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);ke[r]=e,Se[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;ke[r]=n,Se[n]=r}for(let e=0;e<10;e++){ke[e.toString(10)]=e+52;const t=e.toString(10),r=e+52;ke[t]=r,Se[r]=t}ke["+"]=62,Se[62]="+",ke["/"]=63,Se[63]="/";const Ee=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)},xe=e=>(new TextEncoder).encode(e),Ae=e=>"string"==typeof e?xe(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e),Te=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 Ce(e){let t;t="string"==typeof e?xe(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 Re extends Uint8Array{static fromString(e,t="utf-8"){if("string"==typeof e)return function(e,t){return"base64"===t?Re.mutate(Ee(e)):Re.mutate(xe(e))}(e,t);throw new Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,Re.prototype),e}transformToString(e="utf-8"){return function(e,t="utf-8"){return"base64"===t?Ce(e):Te(e)}(this,e)}}const Oe=(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`)}})},Pe=e=>encodeURIComponent(e).replace(/[!'()*]/g,_e),_e=e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`;function Ie(e,t){return new Request(e,t)}function Me(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 Ne={supported:void 0};class Fe{static create(e){return"function"==typeof e?.handle?e:new Fe(e)}constructor(e){"function"==typeof e?this.configProvider=e().then((e=>e||{})):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),void 0===Ne.supported&&(Ne.supported=Boolean("undefined"!=typeof Request&&"keepalive"in Ie("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=Pe(r),Array.isArray(n))for(let e=0,i=n.length;e{};const p=Ie(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 H({headers:r,reason:e.statusText,statusCode:e.status,body:e.body})}:e.blob().then((t=>({response:new H({headers:r,reason:e.statusText,statusCode:e.status,body:t})})))})),Me(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 $e=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 Ue={},Le={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();1===t.length&&(t=`0${t}`),Ue[e]=t,Le[t]=e}function Be(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),je="The stream has already been transformed.",qe=e=>{if(!He(e)&&!ze(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(je);return t=!0,await $e(e)};return Object.assign(e,{transformToByteArray:r,transformToString:async e=>{const t=await r();if("base64"===e)return Ce(t);if("hex"===e)return De(t);if(void 0===e||"utf8"===e||"utf-8"===e)return Te(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(je);if(t=!0,He(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(ze(e))return e;throw new Error(`Cannot transform payload to web stream, got ${e}`)}})},He=e=>"function"==typeof Blob&&e instanceof Blob;const We="function"==typeof ReadableStream?ReadableStream:function(){};class Ke extends We{}const Ve=({expectedChecksum:e,checksum:t,source:r,checksumSourceLocation:n,base64Encoder:i})=>{if(!ze(r))throw new Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);const o=i??Ce;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,Ke.prototype),a},Qe=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return Re.mutate(e);if(!e)return Re.mutate(new Uint8Array);const r=t.streamCollector(e);return Re.mutate(await r)};function Ge(e){return encodeURIComponent(e).replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function Je(e,t){return new Xe(e,t)}class Xe{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 q({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=>Ge(e))).join("/"):Ge(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 Ze{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 Ye=(et=3e5,e=>tt(e)&&e.expiration.getTime()-Date.now()void 0!==e.expiration,rt="X-Amz-Date",nt="X-Amz-Signature",it="X-Amz-Security-Token",ot="authorization",st=rt.toLowerCase(),at=[ot,st,"date"],ct=nt.toLowerCase(),ut="x-amz-content-sha256",dt=it.toLowerCase(),lt={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},ht=/^proxy-/,ft=/^sec-/,pt="AWS4-HMAC-SHA256",gt="AWS4-HMAC-SHA256-PAYLOAD",mt="aws4_request",yt={},vt=[],bt=(e,t,r)=>`${e}/${t}/${r}/${mt}`,wt=(e,t,r)=>{const n=new e(t);return n.update(Ae(r)),n.digest()},kt=({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 lt||t?.has(o)||ht.test(o)||ft.test(o))&&(!r||r&&!r.has(o))||(n[o]=e[i].trim().replace(/\s+/g," "))}return n},St=e=>"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(e),Et=async({headers:e,body:t},r)=>{for(const t of Object.keys(e))if(t.toLowerCase()===ut)return e[t];if(null==t)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if("string"==typeof t||ArrayBuffer.isView(t)||St(t)){const e=new r;return e.update(Ae(t)),De(await e.digest())}return"UNSIGNED-PAYLOAD"};class xt{format(e){const t=[];for(const r of Object.keys(e)){const n=xe(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=xe(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(Ct.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!Tt.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(Be(e.value.replace(/\-/g,"")),1),d}}}var At;!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"}(At||(At={}));const Tt=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Ct{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&&Rt(t),new Ct(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&Rt(e),parseInt(De(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function Rt(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}const Ot=e=>{e=q.clone(e);for(const t of Object.keys(e.headers))at.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e},Pt=e=>"number"==typeof e?new Date(1e3*e):"string"==typeof e?Number(e)?new Date(1e3*Number(e)):new Date(e):e;class _t{constructor({applyChecksum:e,credentials:t,region:r,service:n,sha256:i,uriEscapePath:o=!0}){this.headerFormatter=new xt,this.service=n,this.sha256=i,this.uriEscapePath=o,this.applyChecksum="boolean"!=typeof e||e,this.regionProvider=de(r),this.credentialProvider=de(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}=It(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=bt(f,l,u??this.service),g=((e,t={})=>{const{headers:r,query:n={}}=q.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}})(Ot(e),{unhoistableHeaders:o,hoistableHeaders:a});d.sessionToken&&(g.query[it]=d.sessionToken),g.query["X-Amz-Algorithm"]=pt,g.query["X-Amz-Credential"]=`${d.accessKeyId}/${p}`,g.query[rt]=h,g.query["X-Amz-Expires"]=n.toString(10);const m=kt(g,i,s);return g.query["X-Amz-SignedHeaders"]=Mt(m),g.query[nt]=await this.getSignature(h,p,this.getSigningKey(d,l,f,u),this.createCanonicalRequest(g,m,await Et(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}=It(r),u=bt(a,s,o??this.service),d=await Et({headers:{},body:t},this.sha256),l=new this.sha256;l.update(e);const h=De(await l.digest()),f=[gt,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}=It(t),a=new this.sha256(await this.getSigningKey(i,o,s,n));return a.update(Ae(e)),De(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=Ot(e),{longDate:u,shortDate:d}=It(t),l=bt(d,a,o??this.service);c.headers[st]=u,s.sessionToken&&(c.headers[dt]=s.sessionToken);const h=await Et(c,this.sha256);!((e,t)=>{e=e.toLowerCase();for(const r of Object.keys(t))if(e===r.toLowerCase())return!0;return!1})(ut,c.headers)&&this.applyChecksum&&(c.headers[ut]=h);const f=kt(c,n,r),p=await this.getSignature(u,l,this.getSigningKey(s,a,d,o),this.createCanonicalRequest(c,f,h));return c.headers[ot]=`${pt} Credential=${s.accessKeyId}/${l}, SignedHeaders=${Mt(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()===ct)continue;const i=Pe(n);t.push(i);const o=e[n];"string"==typeof o?r[i]=`${i}=${Pe(o)}`:Array.isArray(o)&&(r[i]=o.slice(0).reduce(((e,t)=>e.concat([`${i}=${Pe(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(Ae(r));const i=await n.digest();return`${pt}\n${e}\n${t}\n${De(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 Pe(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(Ae(i)),De(await o.digest())}getSigningKey(e,t,r,n){return(async(e,t,r,n,i)=>{const o=`${r}:${n}:${i}:${De(await wt(e,t.secretAccessKey,t.accessKeyId))}:${t.sessionToken}`;if(o in yt)return yt[o];for(vt.push(o);vt.length>50;)delete yt[vt.shift()];let s=`AWS4${t.secretAccessKey}`;for(const t of[r,n,i,mt])s=await wt(e,s,t);return yt[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 It=e=>{const t=(r=e,Pt(r).toISOString().replace(/\.\d{3}Z$/,"Z")).replace(/[\-:]/g,"");var r;return{longDate:t,shortDate:t.slice(0,8)}},Mt=e=>Object.keys(e).sort().join(";"),Nt=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,Ye,tt)),t||(t=e.credentialDefaultProvider?we(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?we(e.signer):e.regionInfoProvider?()=>we(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||_t)(c)})):async r=>{const i=(r=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await we(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||_t)(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}},Ft=(e,t)=>{const r=[];if(e&&r.push(e),t)for(const e of t)r.push(e);return r},$t=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,Ut=()=>{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 Ft(t.name,t.aliases))s[e]=t;n.push(t)})),t.forEach((e=>{const t={...e,before:[],after:[]};for(const e of Ft(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 ${$t(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)=>Lt[t.step]-Lt[e.step]||Bt[t.priority||"normal"]-Bt[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=Ft(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${$t(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(`"${$t(n.name,n.aliases)}" middleware with ${n.priority} priority in ${n.step} step cannot be overridden by "${$t(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=Ft(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${$t(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(`"${$t(n.name,n.aliases)}" middleware ${n.relation} "${n.toMiddleware}" middleware cannot be overridden by "${$t(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(Ut()),use:e=>{e.applyToStack(a)},remove:r=>"string"==typeof r?(r=>{let i=!1;const o=e=>{const t=Ft(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 Ft(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=Ft(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(Ut());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 $t(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},Lt={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},Bt={high:3,normal:2,low:1};class Dt{constructor(e){this.config=e,this.middlewareStack=Ut()}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 zt{constructor(){this.middlewareStack=Ut()}static classBuilder(){return new jt}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,[D]:{commandInstance:this,...c},...u},{requestHandler:p}=t;return l.resolve((e=>p.handle(e.request,r||{})),f)}}class jt{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 zt{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 qt="***SensitiveInformation***",Ht=e=>{switch(e){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${e}"`)}},Wt=Math.ceil(2**127*(2-2**-23)),Kt=e=>{const t=(e=>{if(null!=e){if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&cr.warn(ar(`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)>Wt)throw new TypeError(`Expected 32-bit float, got ${e}`);return t},Vt=e=>{if(null!=e){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw new TypeError(`Expected integer, got ${typeof e}: ${e}`)}},Qt=e=>Xt(e,32),Gt=e=>Xt(e,16),Jt=e=>Xt(e,8),Xt=(e,t)=>{const r=Vt(e);if(void 0!==r&&Zt(r,t)!==r)throw new TypeError(`Expected ${t}-bit integer, got ${e}`);return r},Zt=(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]}},Yt=(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},er=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}`)},tr=e=>{if(null!=e){if("string"==typeof e)return e;if(["boolean","number","bigint"].includes(typeof e))return cr.warn(ar(`Expected string, got ${typeof e}: ${e}`)),String(e);throw new TypeError(`Expected string, got ${typeof e}: ${e}`)}},rr=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,nr=e=>{const t=e.match(rr);if(null===t||t[0].length!==e.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(e)},ir=e=>Vt("string"==typeof e?nr(e):e),or=e=>Qt("string"==typeof e?nr(e):e),sr=e=>Gt("string"==typeof e?nr(e):e),ar=e=>String(new TypeError(e).stack||e).split("\n").slice(0,5).filter((e=>!e.includes("stackTraceWarning"))).join("\n"),cr={warn:console.warn},ur=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function lr(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`${ur[n]}, ${i<10?`0${i}`:`${i}`} ${dr[r]} ${t} ${c}:${u}:${d} GMT`}const hr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),fr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-3339 date-times must be expressed as strings");const t=hr.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=sr(Rr(n)),h=Ar(i,"month",1,12),f=Ar(o,"day",1,31),p=vr(l,h,f,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u});return"Z"!=d.toUpperCase()&&p.setTime(p.getTime()-Cr(d)),p},pr=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$/),gr=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$/),mr=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})$/),yr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-7231 date-times must be expressed as strings");let t=pr.exec(e);if(t){const[e,r,n,i,o,s,a,c]=t;return vr(sr(Rr(i)),kr(n),Ar(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c})}if(t=gr.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return wr(vr(br(i),kr(n),Ar(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c}))}if(t=mr.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return vr(sr(Rr(c)),kr(r),Ar(n.trimLeft(),"day",1,31),{hours:i,minutes:o,seconds:s,fractionalMilliseconds:a})}throw new TypeError("Invalid RFC-7231 date-time value")},vr=(e,t,r,n)=>{const i=t-1;return Er(e,i,r),new Date(Date.UTC(e,i,r,Ar(n.hours,"hour",0,23),Ar(n.minutes,"minute",0,59),Ar(n.seconds,"seconds",0,60),Tr(n.fractionalMilliseconds)))},br=e=>{const t=(new Date).getUTCFullYear(),r=100*Math.floor(t/100)+sr(Rr(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,kr=e=>{const t=dr.indexOf(e);if(t<0)throw new TypeError(`Invalid month: ${e}`);return t+1},Sr=[31,28,31,30,31,30,31,31,30,31,30,31],Er=(e,t,r)=>{let n=Sr[t];if(1===t&&xr(e)&&(n=29),r>n)throw new TypeError(`Invalid day for ${dr[t]} in ${e}: ${r}`)},xr=e=>e%4==0&&(e%100!=0||e%400==0),Ar=(e,t,r,n)=>{const i=(e=>Jt("string"==typeof e?nr(e):e))(Rr(e));if(in)throw new TypeError(`${t} must be between ${r} and ${n}, inclusive`);return i},Tr=e=>null==e?0:1e3*(e=>Kt("string"==typeof e?nr(e):e))("0."+e),Cr=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},Rr=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},_r=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"]}),Ir=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{}}},Mr=e=>{const t=[];for(const r in L){const n=L[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}}},Nr=e=>{const t={};return e.checksumAlgorithms().forEach((e=>{t[e.algorithmId()]=e.checksumConstructor()})),t},Fr=e=>{let t=e.retryStrategy;return{setRetryStrategy(e){t=e},retryStrategy:()=>t}},$r=e=>{const t={};return t.retryStrategy=e.retryStrategy(),t},Ur=e=>({...Mr(e),...Fr(e)}),Lr=e=>({...Nr(e),...$r(e)}),Br=e=>Array.isArray(e)?e:[e],Dr=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]=Dr(e[r]));return e},zr=e=>null!=e,jr=function(){const e=Object.getPrototypeOf(this).constructor,t=new(Function.bind.apply(String,[null,...arguments]));return Object.setPrototypeOf(t,e.prototype),t};jr.prototype=Object.create(String.prototype,{constructor:{value:jr,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(jr,String);class qr{trace(){}debug(){}info(){}warn(){}error(){}}function Hr(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,Wr(n,i,o);o=t}for(const e of Object.keys(o))Array.isArray(o[e])?Kr(n,null,o,e):n[e]=o[e];return n}const Wr=(e,t,r)=>Hr(e,Object.entries(r).reduce(((e,[r,n])=>(Array.isArray(n)?e[r]=n:e[r]="function"==typeof n?[t,n()]:[t,n],e)),{})),Kr=(e,t,r,n)=>{if(null!==t){let i=r[n];"function"==typeof i&&(i=[,i]);const[o=Vr,s=Qr,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)}},Vr=e=>null!=e,Qr=e=>e;function Gr(e){return(e.includes(",")||e.includes('"'))&&(e=`"${e.replace(/"/g,'\\"')}"`),e}function Jr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Xr={},Zr={};!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 ln("InvalidXml","XML declaration allowed only at the start of the document.",fn(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}}return t}function nn(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}Xr.validate=function(e,t){t=Object.assign({},en,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,!Yr.isName(o)){let t;return t=0===u.trim().length?"Invalid space after '<'.":"Tag '"+u+"' is an invalid name.",ln("InvalidTag",t,fn(e,s))}const d=an(e,s);if(!1===d)return ln("InvalidAttr","Attributes for '"+u+"' have open quote.",fn(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=un(l,t);if(!0!==i)return ln(i.err.code,i.err.msg,fn(e,r+i.err.line));n=!0}else if(c){if(!d.tagClosed)return ln("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",fn(e,s));if(l.trim().length>0)return ln("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",fn(e,a));if(0===r.length)return ln("InvalidTag","Closing tag '"+u+"' has not been opened.",fn(e,a));{const t=r.pop();if(u!==t.tagName){let r=fn(e,t.tagStartPos);return ln("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+u+"'.",fn(e,a))}0==r.length&&(i=!0)}}else{const o=un(l,t);if(!0!==o)return ln(o.err.code,o.err.msg,fn(e,s-l.length+o.err.line));if(!0===i)return ln("InvalidXml","Multiple possible root nodes found.",fn(e,s));-1!==t.unpairedTags.indexOf(u)||r.push({tagName:u,tagStartPos:a}),n=!0}for(s++;s0)||ln("InvalidXml","Invalid '"+JSON.stringify(r.map((e=>e.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):ln("InvalidXml","Start tag expected.",1)};const on='"',sn="'";function an(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 cn=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function un(e,t){const r=Yr.getAllMatches(e,cn),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}};gn.buildOptions=function(e){return Object.assign({},mn,e)},gn.defaultOptions=mn;var yn=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 vn=Zr;function bn(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&&kn(e,t))t+=7,[entityName,val,t]=bn(e,t+1),-1===val.indexOf("&")&&(r[An(entityName)]={regx:RegExp(`&${entityName};`,"g"),val:val});else if(i&&Sn(e,t))t+=8;else if(i&&En(e,t))t+=8;else if(i&&xn(e,t))t+=9;else{if(!wn)throw new Error("Invalid DOCTYPE");o=!0}n++,s=""}if(0!==n)throw new Error("Unclosed DOCTYPE")}return{entities:r,i:t}};const Cn=/^[-+]?0x[a-fA-F0-9]+$/,Rn=/^([\-\+])?(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 On={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};const Pn=Zr,_n=yn,In=Tn,Mn=function(e,t={}){if(t=Object.assign({},On,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&&Cn.test(r))return Number.parseInt(r,16);{const n=Rn.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 Nn(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 Vn(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?Vn(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function $n(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 Un=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function Ln(e,t,r){if(!this.options.ignoreAttributes&&"string"==typeof e){const r=Pn.getAllMatches(e,Un),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=Wn(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 _n(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=Hn(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=In(e,o);this.docTypeEntities=t.entities,o=t.i}else if("!["===e.substr(o+1,2)){const t=Hn(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=Wn(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 _n(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 _n(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 _n(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 Dn(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 zn=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 jn(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 qn(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 Hn(e,t,r,n){const i=e.indexOf(t,r);if(-1===i)throw new Error(n);return i+t.length-1}function Wn(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=Hn(e,"?>",r+1,"StopNode is not closed.")}else if("!--"===e.substr(r+1,3)){r=Hn(e,"--\x3e",r+3,"StopNode is not closed.")}else if("!["===e.substr(r+1,2)){r=Hn(e,"]]>",r,"StopNode is not closed.")-2}else{const n=Wn(e,r,">");if(n){(n&&n.tagName)===t&&"/"!==n.tagExp[n.tagExp.length-1]&&i++,r=n.closeIndex}}}function Vn(e,t,r){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&Mn(e,r)}return Pn.isExist(e)?e:""}var Qn=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=Nn,this.parseXml=Bn,this.parseTextData=Fn,this.resolveNameSpace=$n,this.buildAttributesMap=Ln,this.isItStopNode=qn,this.replaceEntitiesValue=zn,this.readStopNodeData=Kn,this.saveTextToParentTag=jn,this.addChild=Dn}},Gn={};function Jn(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 Xn(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=ai(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}${ai(a[":@"],t)}`,h=oi(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 si(e){const t=Object.keys(e);for(let r=0;r0&&t.processEntities)for(let r=0;r0&&(r="\n"),oi(e,t,"",r)},li={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 hi(e){this.options=Object.assign({},li,e),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=gi),this.processTextOrObjNode=fi,this.options.format?(this.indentate=pi,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function fi(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 pi(e){return this.options.indentBy.repeat(e)}function gi(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}hi.prototype.build=function(e){return this.options.preserveOrder?di(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0).val)},hi.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}},hi.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)=>Qe(e,t).then((e=>t.utf8Encoder(e))))(e,t).then((e=>{if(e.length){const t=new mi.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]),Dr(o)}return{}})),vi=async(e,t)=>{const r=await yi(e,t);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r},bi=[J.CRC32,J.CRC32C,J.SHA1,J.SHA256],wi=[J.SHA256,J.SHA1,J.CRC32,J.CRC32C],ki=e=>e===J.MD5?"content-md5":`x-amz-checksum-${e.toLowerCase()}`,Si=e=>void 0!==e&&"string"!=typeof e&&!ArrayBuffer.isView(e)&&!St(e);function Ei(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 xi(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 Ti(e){return e instanceof Uint8Array?e:"string"==typeof e?Ai(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}function Ci(e){return"string"==typeof e?0===e.length:0===e.byteLength}function Ri(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}function Oi(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^Ii[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}(),Ii=Oi([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 Mi(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 Ni(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^Ui[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}(),Ui=Oi([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 Li=(e,t)=>({[J.MD5]:t.md5,[J.CRC32]:Fi,[J.CRC32C]:Pi,[J.SHA1]:t.sha1,[J.SHA256]:t.sha256}[e]),Bi=(e,t)=>{const r=new e;return r.update(Ae(t||"")),r.digest()},Di={name:"flexibleChecksumsMiddleware",step:"build",tags:["BODY_CHECKSUM"],override:!0},zi=(e,t)=>(r,n)=>async i=>{if(!q.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?Y:Z;if(!r||!e[r])return t?i:void 0;const o=e[r];if(!bi.includes(o))throw new Error(`The checksum algorithm "${o}" is not supported by the client. Select one of ${bi}.`);return o})(s,{requestChecksumRequired:l,requestAlgorithmMember:h},!!n.isS3ExpressBucket);let p=a,g=c;if(f){switch(f){case J.CRC32:te(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32","U");break;case J.CRC32C:te(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32C","V");break;case J.SHA1:te(n,"FLEXIBLE_CHECKSUMS_REQ_SHA1","X");break;case J.SHA256:te(n,"FLEXIBLE_CHECKSUMS_REQ_SHA256","Y")}const t=ki(f),r=Li(f,e);if(Si(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 Bi(r,a);g={...c,[t]:u(e)}}}return await r({...i,request:{...o,headers:g,body:p}})},ji=(e=[])=>{const t=[];for(const r of wi)e.includes(r)&&bi.includes(r)&&t.push(r);return t};function qi(e){return new Blob([e]).stream()}const Hi=async(e,{checksumAlgorithmFn:t,base64Encoder:r})=>r(await Bi(t,e)),Wi={name:"flexibleChecksumsResponseMiddleware",toMiddleware:"deserializerMiddleware",relation:"after",tags:["BODY_CHECKSUM"],override:!0},Ki=(e,t)=>(r,n)=>async i=>{if(!q.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&&ji(d).every((e=>{const t=ki(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=Si(a.body);i&&(c=await e.streamCollector(a.body),a.body=qi(c)),await(async(e,{config:t,responseAlgorithms:r})=>{const n=ji(r),{body:i,headers:o}=e;for(const r of n){const n=ki(r),s=o[n];if(s){const o=Li(r,t),{base64Encoder:a}=t;if(Si(i))return void(e.body=Ve({expectedChecksum:s,checksumSourceLocation:n,checksum:new o,source:i,base64Encoder:a}));const c=await Hi(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=qi(c))}return s},Vi=(e,t)=>({applyToStack:r=>{r.add(zi(e,t),Di),r.addRelativeTo(Ki(e,t),Wi)}});const Qi={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},Gi=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{if(!q.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),Qi)}}),Ji={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},Xi="X-Amzn-Trace-Id",Zi={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},Yi=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{const{request:n}=r;if(!q.isInstance(n)||"node"!==e.runtime||n.headers.hasOwnProperty(Xi))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[Xi]=o),t({...r,request:n})})(e),Zi)}});const eo={step:"finalizeRequest",tags:["CHECK_CONTENT_LENGTH_HEADER"],name:"getCheckContentLengthHeaderPlugin",override:!0},to=e=>({applyToStack:e=>{e.add(((e,t)=>async r=>{const{request:n}=r;if(q.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 qr?console.warn(e):t.logger.warn(e)}return e({...r})}),eo)}}),ro={tags:["REGION_REDIRECT","S3"],name:"regionRedirectEndpointMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};const no={step:"initialize",tags:["REGION_REDIRECT","S3"],name:"regionRedirectMiddleware",override:!0},io=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),no),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),ro)}}),oo={tags:["S3"],name:"s3ExpiresMiddleware",override:!0,relation:"after",toMiddleware:"deserializerMiddleware"},so=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{const n=await e(r),{response:i}=n;if(H.isInstance(i)&&i.headers.expires){i.headers.expiresstring=i.headers.expires;try{yr(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}),oo)}});class ao{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+ao.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 co(Promise.resolve(e)))}))),e})):n.set(r,new co(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 lo;uo.REFRESH_WINDOW_MS=6e4,function(e){e.ENV="env",e.CONFIG="shared config entry"}(lo||(lo={}));const ho="X-Amz-S3session-Token",fo=ho.toLowerCase();class po extends _t{async signWithCredentials(e,t,r){const n=go(t);e.headers[fo]=t.sessionToken;return mo(this,n),this.signRequest(e,r??{})}async presignWithCredentials(e,t,r){const n=go(t);delete e.headers[fo],e.headers[ho]=t.sessionToken,e.query=e.query??{},e.query[ho]=t.sessionToken;return mo(this,n),this.presign(e,r)}}function go(e){return{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,expiration:e.expiration}}function mo(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 yo={name:"s3ExpressMiddleware",step:"build",tags:["S3","S3_EXPRESS"],override:!0},vo=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)&&(te(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,q.isInstance(n.request)&&i.sessionToken&&(n.request.headers[fo]=i.sessionToken)}}}return t(n)})(e),yo)}}),bo=e=>e=>{throw e},wo=(e,t)=>{},ko=e=>(t,r)=>async n=>{if(!q.isInstance(n.request))return t(n);const i=ue(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||bo)(o));return(a.successHandler||wo)(u.response,o),u},So={CopyObjectCommand:!0,UploadPartCopyCommand:!0,CompleteMultipartUploadCommand:!0},Eo=e=>(t,r)=>async n=>{const i=await t(n),{response:o}=i;if(!H.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 xo(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&&So[r.commandName]){const e=new Error("S3 aborted request");throw e.name="InternalError",e}return l&&l.endsWith("")&&(o.statusCode=400),i},xo=(e=new Uint8Array,t)=>e instanceof Uint8Array?Promise.resolve(e):t.streamCollector(e)||Promise.resolve(new Uint8Array),Ao={relation:"after",toMiddleware:"deserializerMiddleware",tags:["THROW_200_EXCEPTIONS","S3"],name:"throw200ExceptionsMiddleware",override:!0},To=e=>({applyToStack:t=>{t.addRelativeTo(Eo(e),Ao)}});const Co={name:"bucketEndpointMiddleware",override:!0,relation:"after",toMiddleware:"endpointV2Middleware"};const Ro={step:"initialize",tags:["VALIDATE_BUCKET_NAME"],name:"validateBucketNameMiddleware",override:!0},Oo=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),Ro),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),Co)}});const Po=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}$"),_o=e=>Po.test(e)||e.startsWith("[")&&e.endsWith("]"),Io=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),Mo=(e,t=!1)=>{if(!t)return Io.test(e);const r=e.split(".");for(const e of r)if(!Mo(e))return!1;return!0},No={},Fo="endpoints";function $o(e){return"object"!=typeof e||null==e?e:"ref"in e?`$${$o(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map($o).join(", ")})`:JSON.stringify(e,null,2)}class Uo extends Error{constructor(e){super(e),this.name="EndpointError"}}const Lo=(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 Uo(`Path: '${e}' does not end with ']'`);const i=n.slice(t+1,-1);if(Number.isNaN(parseInt(i)))throw new Uo(`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 Uo(`Index '${n}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(r)?r[parseInt(n)]:r[n]}),e),Bo={[U.HTTP]:80,[U.HTTPS]:443},Do={booleanEquals:(e,t)=>e===t,getAttr:Lo,isSet:e=>null!=e,isValidHostLabel:Mo,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(U).includes(c))return null;const u=_o(i);return{scheme:c,authority:`${n}${r.includes(`${n}:${Bo[c]}`)||"string"==typeof e&&e.includes(`${n}:${Bo[c]}`)?`:${Bo[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()}`))},zo=(e,t)=>{const r=[],n={...t.endpointParams,...t.referenceRecord};let i=0;for(;i{if("string"==typeof e)return zo(e,r);if(e.fn)return qo(e,r);if(e.ref)return(({ref:e},t)=>({...t.endpointParams,...t.referenceRecord}[e]))(e,r);throw new Uo(`'${t}': ${String(e)} is not a string, function or reference.`)},qo=({fn:e,argv:t},r)=>{const n=t.map((e=>["boolean","number"].includes(typeof e)?e:jo(e,"arg",r))),i=e.split(".");return i[0]in No&&null!=i[1]?No[i[0]][i[1]](...n):Do[e](...n)},Ho=({assign:e,...t},r)=>{if(e&&e in r.referenceRecord)throw new Uo(`'${e}' is already defined in Reference Record.`);const n=qo(t,r);return r.logger?.debug?.(`${Fo} evaluateCondition: ${$o(t)} = ${$o(n)}`),{result:""===n||!!n,...null!=e&&{toAssign:{name:e,value:n}}}},Wo=(e=[],t)=>{const r={};for(const n of e){const{result:e,toAssign:i}=Ho(n,{...t,referenceRecord:{...t.referenceRecord,...r}});if(!e)return{result:e};i&&(r[i.name]=i.value,t.logger?.debug?.(`${Fo} assign: ${i.name} := ${$o(i.value)}`))}return{result:!0,referenceRecord:r}},Ko=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:n.map((e=>{const n=jo(e,"Header value entry",t);if("string"!=typeof n)throw new Uo(`Header '${r}' value '${n}' is not a string`);return n}))})),{}),Vo=(e,t)=>{if(Array.isArray(e))return e.map((e=>Vo(e,t)));switch(typeof e){case"string":return zo(e,t);case"object":if(null===e)throw new Uo(`Unexpected endpoint property: ${e}`);return Qo(e,t);case"boolean":return e;default:throw new Uo("Unexpected endpoint property type: "+typeof e)}},Qo=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:Vo(n,t)})),{}),Go=(e,t)=>{const r=jo(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 Uo("Endpoint URL must be a string, got "+typeof r)},Jo=(e,t)=>{const{conditions:r,endpoint:n}=e,{result:i,referenceRecord:o}=Wo(r,t);if(!i)return;const s={...t,referenceRecord:{...t.referenceRecord,...o}},{url:a,properties:c,headers:u}=n;return t.logger?.debug?.(`${Fo} Resolving endpoint from template: ${$o(n)}`),{...null!=u&&{headers:Ko(u,s)},...null!=c&&{properties:Qo(c,s)},url:Go(a,s)}},Xo=(e,t)=>{const{conditions:r,error:n}=e,{result:i,referenceRecord:o}=Wo(r,t);if(i)throw new Uo(jo(n,"Error",{...t,referenceRecord:{...t.referenceRecord,...o}}))},Zo=(e,t)=>{const{conditions:r,rules:n}=e,{result:i,referenceRecord:o}=Wo(r,t);if(i)return Yo(n,{...t,referenceRecord:{...t.referenceRecord,...o}})},Yo=(e,t)=>{for(const r of e)if("endpoint"===r.type){const e=Jo(r,t);if(e)return e}else if("error"===r.type)Xo(r,t);else{if("tree"!==r.type)throw new Uo(`Unknown endpoint rule: ${r}`);{const e=Zo(r,t);if(e)return e}}throw new Uo("Rules evaluation failed")},es=(e,t=!1)=>{if(t){for(const t of e.split("."))if(!es(t))return!1;return!0}return!!Mo(e)&&(!(e.length<3||e.length>63)&&(e===e.toLowerCase()&&!_o(e)))};let ts={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 rs={isVirtualHostableS3Bucket:es,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}=ts;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}}};No.aws=rs;const ns=/\d{12}\.ddb/;const is="user-agent",os="x-amz-user-agent",ss=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g,as=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;const cs=e=>(t,r)=>async n=>{const{request:i}=n;if(!q.isInstance(i))return t(n);const{headers:o}=i,s=r?.userAgent?.map(us)||[],a=(await e.defaultUserAgentProvider()).map(us);await async function(e,t,r){const n=r.request;if("rpc-v2-cbor"===n?.headers?.["smithy-protocol"]&&te(e,"PROTOCOL_RPC_V2_CBOR","M"),"function"==typeof t.retryStrategy){const r=await t.retryStrategy();"function"==typeof r.acquireInitialRetryToken?r.constructor?.name?.includes("Adaptive")?te(e,"RETRY_MODE_ADAPTIVE","F"):te(e,"RETRY_MODE_STANDARD","E"):te(e,"RETRY_MODE_LEGACY","D")}if("function"==typeof t.accountIdEndpointMode){const r=e.endpointV2;switch(String(r?.url?.hostname).match(ns)&&te(e,"ACCOUNT_ID_ENDPOINT","O"),await(t.accountIdEndpointMode?.())){case"disabled":te(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":te(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":te(e,"ACCOUNT_ID_MODE_REQUIRED","R")}}const i=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const t=i;t.accountId&&te(e,"RESOLVED_ACCOUNT_ID","T");for(const[r,n]of Object.entries(t.$source??{}))te(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(us)||[],d=await e.userAgentAppId();d&&a.push(us([`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[os]=o[os]?`${o[is]} ${h}`:h),o[is]=l):o[os]=l,t({...n,request:i})},us=e=>{const t=e[0].split("/").map((e=>e.replace(ss,"-"))).join("/"),r=e[1]?.replace(as,"-"),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}`}}),"")},ds={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},ls=e=>"string"==typeof e&&(e.startsWith("fips-")||e.endsWith("-fips")),hs=e=>ls(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,fs="content-length";const ps={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},gs=e=>({applyToStack:t=>{var r;t.add((r=e.bodyLengthChecker,e=>async t=>{const n=t.request;if(q.isInstance(n)){const{body:e,headers:t}=n;if(e&&-1===Object.keys(t).map((e=>e.toLowerCase())).indexOf(fs))try{const t=r(e);n.headers={...n.headers,[fs]:String(t)}}catch(e){}}return e({...t,request:n})}),ps)}}),ms=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,ys=/(\d+\.){3}\d+/,vs=/\.\./,bs=e=>ms.test(e)&&!ys.test(e)&&!vs.test(e),ws=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},ks=(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},Ss=async e=>{};const Es=e=>{if("string"==typeof e)return Es(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}},xs=e=>"object"==typeof e?"url"in e?Es(e.url):e:Es(e),As=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 ks(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("?"))),ws(t)){if(!0===e.ForcePathStyle)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!bs(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},Ts=({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 Ss(r.serviceId),e&&(r.endpoint=()=>Promise.resolve(xs(e)))}const i=await As(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=ue(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})},Cs={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:pe.name},Rs=(e,t)=>({applyToStack:r=>{r.addRelativeTo(Ts({config:e,instructions:t}),Cs)}});var Os;!function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"}(Os||(Os={}));const Ps=Os.STANDARD,_s=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Is=["TimeoutError","RequestTimeout","RequestTimeoutException"],Ms=[500,502,503,504],Ns=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],Fs=e=>429===e.$metadata?.httpStatusCode||_s.includes(e.name)||1==e.$retryable?.throttling,$s=e=>(e=>e.$metadata?.clockSkewCorrected)(e)||Is.includes(e.name)||Ns.includes(e?.code||"")||Ms.includes(e.$metadata?.httpStatusCode||0);class Us{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=>Us.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(),Fs(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))}}Us.setTimeoutFn=setTimeout;const Ls=({retryDelay:e,retryCount:t,retryCost:r})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(2e4,e),getRetryCost:()=>r});class Bs{constructor(e){this.maxAttempts=e,this.mode=Os.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 Ls({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,Ls({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 Ds{constructor(e,t){this.maxAttemptsProvider=e,this.mode=Os.ADAPTIVE;const{rateLimiter:r}=t??{};this.rateLimiter=r??new Us,this.standardRetryStrategy=new Bs(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 zs;const js=new Uint8Array(16);function qs(){if(!zs&&(zs="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!zs))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return zs(js)}const Hs=[];for(let e=0;e<256;++e)Hs.push((e+256).toString(16).slice(1));var Ws={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Ks(e,t,r){if(Ws.randomUUID&&!t&&!e)return Ws.randomUUID();const n=(e=e||{}).random||(e.rng||qs)();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 Hs[e[t+0]]+Hs[e[t+1]]+Hs[e[t+2]]+Hs[e[t+3]]+"-"+Hs[e[t+4]]+Hs[e[t+5]]+"-"+Hs[e[t+6]]+Hs[e[t+7]]+"-"+Hs[e[t+8]]+Hs[e[t+9]]+"-"+Hs[e[t+10]]+Hs[e[t+11]]+Hs[e[t+12]]+Hs[e[t+13]]+Hs[e[t+14]]+Hs[e[t+15]]}(n)}const Vs=e=>e?.body instanceof ReadableStream,Qs=e=>void 0!==e.acquireInitialRetryToken&&void 0!==e.refreshRetryTokenForRetry&&void 0!==e.recordSuccess,Gs=e=>{const t={error:e,errorType:Js(e)},r=Ys(e.$response);return r&&(t.retryAfterHint=r),t},Js=e=>Fs(e)?"THROTTLING":$s(e)?"TRANSIENT":(e=>{if(void 0!==e.$metadata?.httpStatusCode){const t=e.$metadata.httpStatusCode;return 500<=t&&t<=599&&!$s(e)}return!1})(e)?"SERVER_ERROR":"CLIENT_ERROR",Xs={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},Zs=e=>({applyToStack:t=>{t.add((e=>(t,r)=>async n=>{let i=await e.retryStrategy();const o=await e.maxAttempts();if(!Qs(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=q.isInstance(d);for(l&&(d.headers["amz-sdk-invocation-id"]=Ks());;)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=Gs(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&&Vs(d))throw(r.logger instanceof qr?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),Xs)}}),Ys=e=>{if(!H.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)},ea=null;class ta{constructor(e){this.sigv4Signer=new po(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=ea,"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 ra="required",na="type",ia="conditions",oa="fn",sa="argv",aa="ref",ca="assign",ua="url",da="properties",la="backend",ha="authSchemes",fa="disableDoubleEncoding",pa="signingName",ga="signingRegion",ma="headers",ya="signingRegionSet",va=!0,ba="isSet",wa="booleanEquals",ka="error",Sa="aws.partition",Ea="stringEquals",xa="getAttr",Aa="name",Ta="substring",Ca="bucketSuffix",Ra="parseURL",Oa="{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",Pa="endpoint",_a="tree",Ia="aws.isVirtualHostableS3Bucket",Ma="{url#scheme}://{Bucket}.{url#authority}{url#path}",Na="not",Fa="{url#scheme}://{url#authority}{url#path}",$a="hardwareType",Ua="regionPrefix",La="bucketAliasSuffix",Ba="outpostId",Da="isValidHostLabel",za="sigv4a",ja="s3-outposts",qa="s3",Ha="{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}",Wa="https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}",Ka="https://{Bucket}.s3.{partitionResult#dnsSuffix}",Va="aws.parseArn",Qa="bucketArn",Ga="arnType",Ja="s3-object-lambda",Xa="accesspoint",Za="accessPointName",Ya="{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}",ec="mrapPartition",tc="outpostType",rc="arnPrefix",nc="{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}",ic="https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",oc="https://s3.{partitionResult#dnsSuffix}",sc={[ra]:!1,[na]:"String"},ac={[ra]:!0,default:!1,[na]:"Boolean"},cc={[ra]:!1,[na]:"Boolean"},uc={[oa]:wa,[sa]:[{[aa]:"Accelerate"},!0]},dc={[oa]:wa,[sa]:[{[aa]:"UseFIPS"},!0]},lc={[oa]:wa,[sa]:[{[aa]:"UseDualStack"},!0]},hc={[oa]:ba,[sa]:[{[aa]:"Endpoint"}]},fc={[oa]:Sa,[sa]:[{[aa]:"Region"}],[ca]:"partitionResult"},pc={[oa]:Ea,[sa]:[{[oa]:xa,[sa]:[{[aa]:"partitionResult"},Aa]},"aws-cn"]},gc={[oa]:ba,[sa]:[{[aa]:"Bucket"}]},mc={[aa]:"Bucket"},yc={[oa]:Ra,[sa]:[{[aa]:"Endpoint"}],[ca]:"url"},vc={[oa]:wa,[sa]:[{[oa]:xa,[sa]:[{[aa]:"url"},"isIp"]},!0]},bc={[aa]:"url"},wc={[oa]:"uriEncode",[sa]:[mc],[ca]:"uri_encoded_bucket"},kc={[la]:"S3Express",[ha]:[{[fa]:!0,[Aa]:"sigv4",[pa]:"s3express",[ga]:"{Region}"}]},Sc={},Ec={[oa]:Ia,[sa]:[mc,!1]},xc={[ka]:"S3Express bucket name is not a valid virtual hostable name.",[na]:ka},Ac={[la]:"S3Express",[ha]:[{[fa]:!0,[Aa]:"sigv4-s3express",[pa]:"s3express",[ga]:"{Region}"}]},Tc={[oa]:ba,[sa]:[{[aa]:"UseS3ExpressControlEndpoint"}]},Cc={[oa]:wa,[sa]:[{[aa]:"UseS3ExpressControlEndpoint"},!0]},Rc={[oa]:Na,[sa]:[hc]},Oc={[ka]:"Unrecognized S3Express bucket name format.",[na]:ka},Pc={[oa]:Na,[sa]:[gc]},_c={[aa]:$a},Ic={[ia]:[Rc],[ka]:"Expected a endpoint to be specified but no endpoint was found",[na]:ka},Mc={[ha]:[{[fa]:!0,[Aa]:za,[pa]:ja,[ya]:["*"]},{[fa]:!0,[Aa]:"sigv4",[pa]:ja,[ga]:"{Region}"}]},Nc={[oa]:wa,[sa]:[{[aa]:"ForcePathStyle"},!1]},Fc={[aa]:"ForcePathStyle"},$c={[oa]:wa,[sa]:[{[aa]:"Accelerate"},!1]},Uc={[oa]:Ea,[sa]:[{[aa]:"Region"},"aws-global"]},Lc={[ha]:[{[fa]:!0,[Aa]:"sigv4",[pa]:qa,[ga]:"us-east-1"}]},Bc={[oa]:Na,[sa]:[Uc]},Dc={[oa]:wa,[sa]:[{[aa]:"UseGlobalEndpoint"},!0]},zc={[ua]:"https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[da]:{[ha]:[{[fa]:!0,[Aa]:"sigv4",[pa]:qa,[ga]:"{Region}"}]},[ma]:{}},jc={[ha]:[{[fa]:!0,[Aa]:"sigv4",[pa]:qa,[ga]:"{Region}"}]},qc={[oa]:wa,[sa]:[{[aa]:"UseGlobalEndpoint"},!1]},Hc={[oa]:wa,[sa]:[{[aa]:"UseDualStack"},!1]},Wc={[ua]:"https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",[da]:jc,[ma]:{}},Kc={[oa]:wa,[sa]:[{[aa]:"UseFIPS"},!1]},Vc={[ua]:"https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",[da]:jc,[ma]:{}},Qc={[ua]:"https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[da]:jc,[ma]:{}},Gc={[oa]:wa,[sa]:[{[oa]:xa,[sa]:[bc,"isIp"]},!1]},Jc={[ua]:Ha,[da]:jc,[ma]:{}},Xc={[ua]:Ma,[da]:jc,[ma]:{}},Zc={[Pa]:Xc,[na]:Pa},Yc={[ua]:Wa,[da]:jc,[ma]:{}},eu={[ua]:"https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",[da]:jc,[ma]:{}},tu={[ka]:"Invalid region: region was not a valid DNS name.",[na]:ka},ru={[aa]:Qa},nu={[aa]:Ga},iu={[oa]:xa,[sa]:[ru,"service"]},ou={[aa]:Za},su={[ia]:[lc],[ka]:"S3 Object Lambda does not support Dual-stack",[na]:ka},au={[ia]:[uc],[ka]:"S3 Object Lambda does not support S3 Accelerate",[na]:ka},cu={[ia]:[{[oa]:ba,[sa]:[{[aa]:"DisableAccessPoints"}]},{[oa]:wa,[sa]:[{[aa]:"DisableAccessPoints"},!0]}],[ka]:"Access points are not supported for this operation",[na]:ka},uu={[ia]:[{[oa]:ba,[sa]:[{[aa]:"UseArnRegion"}]},{[oa]:wa,[sa]:[{[aa]:"UseArnRegion"},!1]},{[oa]:Na,[sa]:[{[oa]:Ea,[sa]:[{[oa]:xa,[sa]:[ru,"region"]},"{Region}"]}]}],[ka]:"Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",[na]:ka},du={[oa]:xa,[sa]:[{[aa]:"bucketPartition"},Aa]},lu={[oa]:xa,[sa]:[ru,"accountId"]},hu={[ha]:[{[fa]:!0,[Aa]:"sigv4",[pa]:Ja,[ga]:"{bucketArn#region}"}]},fu={[ka]:"Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",[na]:ka},pu={[ka]:"Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",[na]:ka},gu={[ka]:"Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",[na]:ka},mu={[ka]:"Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",[na]:ka},yu={[ka]:"Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",[na]:ka},vu={[ka]:"Invalid ARN: Expected a resource of the format `accesspoint:` but no name was provided",[na]:ka},bu={[ha]:[{[fa]:!0,[Aa]:"sigv4",[pa]:qa,[ga]:"{bucketArn#region}"}]},wu={[ha]:[{[fa]:!0,[Aa]:za,[pa]:ja,[ya]:["*"]},{[fa]:!0,[Aa]:"sigv4",[pa]:ja,[ga]:"{bucketArn#region}"}]},ku={[oa]:Va,[sa]:[mc]},Su={[ua]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[da]:jc,[ma]:{}},Eu={[ua]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[da]:jc,[ma]:{}},xu={[ua]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[da]:jc,[ma]:{}},Au={[ua]:nc,[da]:jc,[ma]:{}},Tu={[ua]:"https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[da]:jc,[ma]:{}},Cu={[aa]:"UseObjectLambdaEndpoint"},Ru={[ha]:[{[fa]:!0,[Aa]:"sigv4",[pa]:Ja,[ga]:"{Region}"}]},Ou={[ua]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[da]:jc,[ma]:{}},Pu={[ua]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}",[da]:jc,[ma]:{}},_u={[ua]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[da]:jc,[ma]:{}},Iu={[ua]:Fa,[da]:jc,[ma]:{}},Mu={[ua]:"https://s3.{Region}.{partitionResult#dnsSuffix}",[da]:jc,[ma]:{}},Nu=[{[aa]:"Region"}],Fu=[{[aa]:"Endpoint"}],$u=[mc],Uu=[lc],Lu=[uc],Bu=[hc,yc],Du=[{[oa]:ba,[sa]:[{[aa]:"DisableS3ExpressSessionAuth"}]},{[oa]:wa,[sa]:[{[aa]:"DisableS3ExpressSessionAuth"},!0]}],zu=[vc],ju=[wc],qu=[Ec],Hu=[dc],Wu=[{[oa]:Ta,[sa]:[mc,6,14,!0],[ca]:"s3expressAvailabilityZoneId"},{[oa]:Ta,[sa]:[mc,14,16,!0],[ca]:"s3expressAvailabilityZoneDelim"},{[oa]:Ea,[sa]:[{[aa]:"s3expressAvailabilityZoneDelim"},"--"]}],Ku=[{[ia]:[dc],[Pa]:{[ua]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[da]:kc,[ma]:{}},[na]:Pa},{[Pa]:{[ua]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[da]:kc,[ma]:{}},[na]:Pa}],Vu=[{[oa]:Ta,[sa]:[mc,6,15,!0],[ca]:"s3expressAvailabilityZoneId"},{[oa]:Ta,[sa]:[mc,15,17,!0],[ca]:"s3expressAvailabilityZoneDelim"},{[oa]:Ea,[sa]:[{[aa]:"s3expressAvailabilityZoneDelim"},"--"]}],Qu=[{[ia]:[dc],[Pa]:{[ua]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[da]:Ac,[ma]:{}},[na]:Pa},{[Pa]:{[ua]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[da]:Ac,[ma]:{}},[na]:Pa}],Gu=[gc],Ju=[{[oa]:Da,[sa]:[{[aa]:Ba},!1]}],Xu=[{[oa]:Ea,[sa]:[{[aa]:Ua},"beta"]}],Zu=[fc],Yu=[{[oa]:Da,[sa]:[{[aa]:"Region"},!1]}],ed=[{[oa]:Ea,[sa]:[{[aa]:"Region"},"us-east-1"]}],td=[{[oa]:Ea,[sa]:[nu,Xa]}],rd=[{[oa]:xa,[sa]:[ru,"resourceId[1]"],[ca]:Za},{[oa]:Na,[sa]:[{[oa]:Ea,[sa]:[ou,""]}]}],nd=[ru,"resourceId[1]"],id=[{[oa]:Na,[sa]:[{[oa]:Ea,[sa]:[{[oa]:xa,[sa]:[ru,"region"]},""]}]}],od=[{[oa]:Na,[sa]:[{[oa]:ba,[sa]:[{[oa]:xa,[sa]:[ru,"resourceId[2]"]}]}]}],sd=[ru,"resourceId[2]"],ad=[{[oa]:Sa,[sa]:[{[oa]:xa,[sa]:[ru,"region"]}],[ca]:"bucketPartition"}],cd=[{[oa]:Ea,[sa]:[du,{[oa]:xa,[sa]:[{[aa]:"partitionResult"},Aa]}]}],ud=[{[oa]:Da,[sa]:[{[oa]:xa,[sa]:[ru,"region"]},!0]}],dd=[{[oa]:Da,[sa]:[lu,!1]}],ld=[{[oa]:Da,[sa]:[ou,!1]}],hd=[{[oa]:Da,[sa]:[{[aa]:"Region"},!0]}],fd={version:"1.0",parameters:{Bucket:sc,Region:sc,UseFIPS:ac,UseDualStack:ac,Endpoint:sc,ForcePathStyle:ac,Accelerate:ac,UseGlobalEndpoint:ac,UseObjectLambdaEndpoint:cc,Key:sc,Prefix:sc,CopySource:sc,DisableAccessPoints:cc,DisableMultiRegionAccessPoints:ac,UseArnRegion:cc,UseS3ExpressControlEndpoint:cc,DisableS3ExpressSessionAuth:cc},rules:[{[ia]:[{[oa]:ba,[sa]:Nu}],rules:[{[ia]:[uc,dc],error:"Accelerate cannot be used with FIPS",[na]:ka},{[ia]:[lc,hc],error:"Cannot set dual-stack in combination with a custom endpoint.",[na]:ka},{[ia]:[hc,dc],error:"A custom endpoint cannot be combined with FIPS",[na]:ka},{[ia]:[hc,uc],error:"A custom endpoint cannot be combined with S3 Accelerate",[na]:ka},{[ia]:[dc,fc,pc],error:"Partition does not support FIPS",[na]:ka},{[ia]:[gc,{[oa]:Ta,[sa]:[mc,0,6,va],[ca]:Ca},{[oa]:Ea,[sa]:[{[aa]:Ca},"--x-s3"]}],rules:[{[ia]:Uu,error:"S3Express does not support Dual-stack.",[na]:ka},{[ia]:Lu,error:"S3Express does not support S3 Accelerate.",[na]:ka},{[ia]:Bu,rules:[{[ia]:Du,rules:[{[ia]:zu,rules:[{[ia]:ju,rules:[{endpoint:{[ua]:Oa,[da]:kc,[ma]:Sc},[na]:Pa}],[na]:_a}],[na]:_a},{[ia]:qu,rules:[{endpoint:{[ua]:Ma,[da]:kc,[ma]:Sc},[na]:Pa}],[na]:_a},xc],[na]:_a},{[ia]:zu,rules:[{[ia]:ju,rules:[{endpoint:{[ua]:Oa,[da]:Ac,[ma]:Sc},[na]:Pa}],[na]:_a}],[na]:_a},{[ia]:qu,rules:[{endpoint:{[ua]:Ma,[da]:Ac,[ma]:Sc},[na]:Pa}],[na]:_a},xc],[na]:_a},{[ia]:[Tc,Cc],rules:[{[ia]:[wc,Rc],rules:[{[ia]:Hu,endpoint:{[ua]:"https://s3express-control-fips.{Region}.amazonaws.com/{uri_encoded_bucket}",[da]:kc,[ma]:Sc},[na]:Pa},{endpoint:{[ua]:"https://s3express-control.{Region}.amazonaws.com/{uri_encoded_bucket}",[da]:kc,[ma]:Sc},[na]:Pa}],[na]:_a}],[na]:_a},{[ia]:qu,rules:[{[ia]:Du,rules:[{[ia]:Wu,rules:Ku,[na]:_a},{[ia]:Vu,rules:Ku,[na]:_a},Oc],[na]:_a},{[ia]:Wu,rules:Qu,[na]:_a},{[ia]:Vu,rules:Qu,[na]:_a},Oc],[na]:_a},xc],[na]:_a},{[ia]:[Pc,Tc,Cc],rules:[{[ia]:Bu,endpoint:{[ua]:Fa,[da]:kc,[ma]:Sc},[na]:Pa},{[ia]:Hu,endpoint:{[ua]:"https://s3express-control-fips.{Region}.amazonaws.com",[da]:kc,[ma]:Sc},[na]:Pa},{endpoint:{[ua]:"https://s3express-control.{Region}.amazonaws.com",[da]:kc,[ma]:Sc},[na]:Pa}],[na]:_a},{[ia]:[gc,{[oa]:Ta,[sa]:[mc,49,50,va],[ca]:$a},{[oa]:Ta,[sa]:[mc,8,12,va],[ca]:Ua},{[oa]:Ta,[sa]:[mc,0,7,va],[ca]:La},{[oa]:Ta,[sa]:[mc,32,49,va],[ca]:Ba},{[oa]:Sa,[sa]:Nu,[ca]:"regionPartition"},{[oa]:Ea,[sa]:[{[aa]:La},"--op-s3"]}],rules:[{[ia]:Ju,rules:[{[ia]:[{[oa]:Ea,[sa]:[_c,"e"]}],rules:[{[ia]:Xu,rules:[Ic,{[ia]:Bu,endpoint:{[ua]:"https://{Bucket}.ec2.{url#authority}",[da]:Mc,[ma]:Sc},[na]:Pa}],[na]:_a},{endpoint:{[ua]:"https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[da]:Mc,[ma]:Sc},[na]:Pa}],[na]:_a},{[ia]:[{[oa]:Ea,[sa]:[_c,"o"]}],rules:[{[ia]:Xu,rules:[Ic,{[ia]:Bu,endpoint:{[ua]:"https://{Bucket}.op-{outpostId}.{url#authority}",[da]:Mc,[ma]:Sc},[na]:Pa}],[na]:_a},{endpoint:{[ua]:"https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[da]:Mc,[ma]:Sc},[na]:Pa}],[na]:_a},{error:'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',[na]:ka}],[na]:_a},{error:"Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",[na]:ka}],[na]:_a},{[ia]:Gu,rules:[{[ia]:[hc,{[oa]:Na,[sa]:[{[oa]:ba,[sa]:[{[oa]:Ra,[sa]:Fu}]}]}],error:"Custom endpoint `{Endpoint}` was not a valid URI",[na]:ka},{[ia]:[Nc,Ec],rules:[{[ia]:Zu,rules:[{[ia]:Yu,rules:[{[ia]:[uc,pc],error:"S3 Accelerate cannot be used in this region",[na]:ka},{[ia]:[lc,dc,$c,Rc,Uc],endpoint:{[ua]:"https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[lc,dc,$c,Rc,Bc,Dc],rules:[{endpoint:zc,[na]:Pa}],[na]:_a},{[ia]:[lc,dc,$c,Rc,Bc,qc],endpoint:zc,[na]:Pa},{[ia]:[Hc,dc,$c,Rc,Uc],endpoint:{[ua]:"https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[Hc,dc,$c,Rc,Bc,Dc],rules:[{endpoint:Wc,[na]:Pa}],[na]:_a},{[ia]:[Hc,dc,$c,Rc,Bc,qc],endpoint:Wc,[na]:Pa},{[ia]:[lc,Kc,uc,Rc,Uc],endpoint:{[ua]:"https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[lc,Kc,uc,Rc,Bc,Dc],rules:[{endpoint:Vc,[na]:Pa}],[na]:_a},{[ia]:[lc,Kc,uc,Rc,Bc,qc],endpoint:Vc,[na]:Pa},{[ia]:[lc,Kc,$c,Rc,Uc],endpoint:{[ua]:"https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[lc,Kc,$c,Rc,Bc,Dc],rules:[{endpoint:Qc,[na]:Pa}],[na]:_a},{[ia]:[lc,Kc,$c,Rc,Bc,qc],endpoint:Qc,[na]:Pa},{[ia]:[Hc,Kc,$c,hc,yc,vc,Uc],endpoint:{[ua]:Ha,[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[Hc,Kc,$c,hc,yc,Gc,Uc],endpoint:{[ua]:Ma,[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[Hc,Kc,$c,hc,yc,vc,Bc,Dc],rules:[{[ia]:ed,endpoint:Jc,[na]:Pa},{endpoint:Jc,[na]:Pa}],[na]:_a},{[ia]:[Hc,Kc,$c,hc,yc,Gc,Bc,Dc],rules:[{[ia]:ed,endpoint:Xc,[na]:Pa},Zc],[na]:_a},{[ia]:[Hc,Kc,$c,hc,yc,vc,Bc,qc],endpoint:Jc,[na]:Pa},{[ia]:[Hc,Kc,$c,hc,yc,Gc,Bc,qc],endpoint:Xc,[na]:Pa},{[ia]:[Hc,Kc,uc,Rc,Uc],endpoint:{[ua]:Wa,[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[Hc,Kc,uc,Rc,Bc,Dc],rules:[{[ia]:ed,endpoint:Yc,[na]:Pa},{endpoint:Yc,[na]:Pa}],[na]:_a},{[ia]:[Hc,Kc,uc,Rc,Bc,qc],endpoint:Yc,[na]:Pa},{[ia]:[Hc,Kc,$c,Rc,Uc],endpoint:{[ua]:Ka,[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[Hc,Kc,$c,Rc,Bc,Dc],rules:[{[ia]:ed,endpoint:{[ua]:Ka,[da]:jc,[ma]:Sc},[na]:Pa},{endpoint:eu,[na]:Pa}],[na]:_a},{[ia]:[Hc,Kc,$c,Rc,Bc,qc],endpoint:eu,[na]:Pa}],[na]:_a},tu],[na]:_a}],[na]:_a},{[ia]:[hc,yc,{[oa]:Ea,[sa]:[{[oa]:xa,[sa]:[bc,"scheme"]},"http"]},{[oa]:Ia,[sa]:[mc,va]},Nc,Kc,Hc,$c],rules:[{[ia]:Zu,rules:[{[ia]:Yu,rules:[Zc],[na]:_a},tu],[na]:_a}],[na]:_a},{[ia]:[Nc,{[oa]:Va,[sa]:$u,[ca]:Qa}],rules:[{[ia]:[{[oa]:xa,[sa]:[ru,"resourceId[0]"],[ca]:Ga},{[oa]:Na,[sa]:[{[oa]:Ea,[sa]:[nu,""]}]}],rules:[{[ia]:[{[oa]:Ea,[sa]:[iu,Ja]}],rules:[{[ia]:td,rules:[{[ia]:rd,rules:[su,au,{[ia]:id,rules:[cu,{[ia]:od,rules:[uu,{[ia]:ad,rules:[{[ia]:Zu,rules:[{[ia]:cd,rules:[{[ia]:ud,rules:[{[ia]:[{[oa]:Ea,[sa]:[lu,""]}],error:"Invalid ARN: Missing account id",[na]:ka},{[ia]:dd,rules:[{[ia]:ld,rules:[{[ia]:Bu,endpoint:{[ua]:Ya,[da]:hu,[ma]:Sc},[na]:Pa},{[ia]:Hu,endpoint:{[ua]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[da]:hu,[ma]:Sc},[na]:Pa},{endpoint:{[ua]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",[da]:hu,[ma]:Sc},[na]:Pa}],[na]:_a},fu],[na]:_a},pu],[na]:_a},gu],[na]:_a},mu],[na]:_a}],[na]:_a}],[na]:_a},yu],[na]:_a},{error:"Invalid ARN: bucket ARN is missing a region",[na]:ka}],[na]:_a},vu],[na]:_a},{error:"Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",[na]:ka}],[na]:_a},{[ia]:td,rules:[{[ia]:rd,rules:[{[ia]:id,rules:[{[ia]:td,rules:[{[ia]:id,rules:[cu,{[ia]:od,rules:[uu,{[ia]:ad,rules:[{[ia]:Zu,rules:[{[ia]:[{[oa]:Ea,[sa]:[du,"{partitionResult#name}"]}],rules:[{[ia]:ud,rules:[{[ia]:[{[oa]:Ea,[sa]:[iu,qa]}],rules:[{[ia]:dd,rules:[{[ia]:ld,rules:[{[ia]:Lu,error:"Access Points do not support S3 Accelerate",[na]:ka},{[ia]:[dc,lc],endpoint:{[ua]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[da]:bu,[ma]:Sc},[na]:Pa},{[ia]:[dc,Hc],endpoint:{[ua]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[da]:bu,[ma]:Sc},[na]:Pa},{[ia]:[Kc,lc],endpoint:{[ua]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[da]:bu,[ma]:Sc},[na]:Pa},{[ia]:[Kc,Hc,hc,yc],endpoint:{[ua]:Ya,[da]:bu,[ma]:Sc},[na]:Pa},{[ia]:[Kc,Hc],endpoint:{[ua]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",[da]:bu,[ma]:Sc},[na]:Pa}],[na]:_a},fu],[na]:_a},pu],[na]:_a},{error:"Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",[na]:ka}],[na]:_a},gu],[na]:_a},mu],[na]:_a}],[na]:_a}],[na]:_a},yu],[na]:_a}],[na]:_a}],[na]:_a},{[ia]:[{[oa]:Da,[sa]:[ou,va]}],rules:[{[ia]:Uu,error:"S3 MRAP does not support dual-stack",[na]:ka},{[ia]:Hu,error:"S3 MRAP does not support FIPS",[na]:ka},{[ia]:Lu,error:"S3 MRAP does not support S3 Accelerate",[na]:ka},{[ia]:[{[oa]:wa,[sa]:[{[aa]:"DisableMultiRegionAccessPoints"},va]}],error:"Invalid configuration: Multi-Region Access Point ARNs are disabled.",[na]:ka},{[ia]:[{[oa]:Sa,[sa]:Nu,[ca]:ec}],rules:[{[ia]:[{[oa]:Ea,[sa]:[{[oa]:xa,[sa]:[{[aa]:ec},Aa]},{[oa]:xa,[sa]:[ru,"partition"]}]}],rules:[{endpoint:{[ua]:"https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",[da]:{[ha]:[{[fa]:va,name:za,[pa]:qa,[ya]:["*"]}]},[ma]:Sc},[na]:Pa}],[na]:_a},{error:"Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",[na]:ka}],[na]:_a}],[na]:_a},{error:"Invalid Access Point Name",[na]:ka}],[na]:_a},vu],[na]:_a},{[ia]:[{[oa]:Ea,[sa]:[iu,ja]}],rules:[{[ia]:Uu,error:"S3 Outposts does not support Dual-stack",[na]:ka},{[ia]:Hu,error:"S3 Outposts does not support FIPS",[na]:ka},{[ia]:Lu,error:"S3 Outposts does not support S3 Accelerate",[na]:ka},{[ia]:[{[oa]:ba,[sa]:[{[oa]:xa,[sa]:[ru,"resourceId[4]"]}]}],error:"Invalid Arn: Outpost Access Point ARN contains sub resources",[na]:ka},{[ia]:[{[oa]:xa,[sa]:nd,[ca]:Ba}],rules:[{[ia]:Ju,rules:[uu,{[ia]:ad,rules:[{[ia]:Zu,rules:[{[ia]:cd,rules:[{[ia]:ud,rules:[{[ia]:dd,rules:[{[ia]:[{[oa]:xa,[sa]:sd,[ca]:tc}],rules:[{[ia]:[{[oa]:xa,[sa]:[ru,"resourceId[3]"],[ca]:Za}],rules:[{[ia]:[{[oa]:Ea,[sa]:[{[aa]:tc},Xa]}],rules:[{[ia]:Bu,endpoint:{[ua]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",[da]:wu,[ma]:Sc},[na]:Pa},{endpoint:{[ua]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",[da]:wu,[ma]:Sc},[na]:Pa}],[na]:_a},{error:"Expected an outpost type `accesspoint`, found {outpostType}",[na]:ka}],[na]:_a},{error:"Invalid ARN: expected an access point name",[na]:ka}],[na]:_a},{error:"Invalid ARN: Expected a 4-component resource",[na]:ka}],[na]:_a},pu],[na]:_a},gu],[na]:_a},mu],[na]:_a}],[na]:_a}],[na]:_a},{error:"Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",[na]:ka}],[na]:_a},{error:"Invalid ARN: The Outpost Id was not set",[na]:ka}],[na]:_a},{error:"Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",[na]:ka}],[na]:_a},{error:"Invalid ARN: No ARN type specified",[na]:ka}],[na]:_a},{[ia]:[{[oa]:Ta,[sa]:[mc,0,4,!1],[ca]:rc},{[oa]:Ea,[sa]:[{[aa]:rc},"arn:"]},{[oa]:Na,[sa]:[{[oa]:ba,[sa]:[ku]}]}],error:"Invalid ARN: `{Bucket}` was not a valid ARN",[na]:ka},{[ia]:[{[oa]:wa,[sa]:[Fc,va]},ku],error:"Path-style addressing cannot be used with ARN buckets",[na]:ka},{[ia]:ju,rules:[{[ia]:Zu,rules:[{[ia]:[$c],rules:[{[ia]:[lc,Rc,dc,Uc],endpoint:{[ua]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[lc,Rc,dc,Bc,Dc],rules:[{endpoint:Su,[na]:Pa}],[na]:_a},{[ia]:[lc,Rc,dc,Bc,qc],endpoint:Su,[na]:Pa},{[ia]:[Hc,Rc,dc,Uc],endpoint:{[ua]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[Hc,Rc,dc,Bc,Dc],rules:[{endpoint:Eu,[na]:Pa}],[na]:_a},{[ia]:[Hc,Rc,dc,Bc,qc],endpoint:Eu,[na]:Pa},{[ia]:[lc,Rc,Kc,Uc],endpoint:{[ua]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[lc,Rc,Kc,Bc,Dc],rules:[{endpoint:xu,[na]:Pa}],[na]:_a},{[ia]:[lc,Rc,Kc,Bc,qc],endpoint:xu,[na]:Pa},{[ia]:[Hc,hc,yc,Kc,Uc],endpoint:{[ua]:nc,[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[Hc,hc,yc,Kc,Bc,Dc],rules:[{[ia]:ed,endpoint:Au,[na]:Pa},{endpoint:Au,[na]:Pa}],[na]:_a},{[ia]:[Hc,hc,yc,Kc,Bc,qc],endpoint:Au,[na]:Pa},{[ia]:[Hc,Rc,Kc,Uc],endpoint:{[ua]:ic,[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[Hc,Rc,Kc,Bc,Dc],rules:[{[ia]:ed,endpoint:{[ua]:ic,[da]:jc,[ma]:Sc},[na]:Pa},{endpoint:Tu,[na]:Pa}],[na]:_a},{[ia]:[Hc,Rc,Kc,Bc,qc],endpoint:Tu,[na]:Pa}],[na]:_a},{error:"Path-style addressing cannot be used with S3 Accelerate",[na]:ka}],[na]:_a}],[na]:_a}],[na]:_a},{[ia]:[{[oa]:ba,[sa]:[Cu]},{[oa]:wa,[sa]:[Cu,va]}],rules:[{[ia]:Zu,rules:[{[ia]:hd,rules:[su,au,{[ia]:Bu,endpoint:{[ua]:Fa,[da]:Ru,[ma]:Sc},[na]:Pa},{[ia]:Hu,endpoint:{[ua]:"https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",[da]:Ru,[ma]:Sc},[na]:Pa},{endpoint:{[ua]:"https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",[da]:Ru,[ma]:Sc},[na]:Pa}],[na]:_a},tu],[na]:_a}],[na]:_a},{[ia]:[Pc],rules:[{[ia]:Zu,rules:[{[ia]:hd,rules:[{[ia]:[dc,lc,Rc,Uc],endpoint:{[ua]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[dc,lc,Rc,Bc,Dc],rules:[{endpoint:Ou,[na]:Pa}],[na]:_a},{[ia]:[dc,lc,Rc,Bc,qc],endpoint:Ou,[na]:Pa},{[ia]:[dc,Hc,Rc,Uc],endpoint:{[ua]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[dc,Hc,Rc,Bc,Dc],rules:[{endpoint:Pu,[na]:Pa}],[na]:_a},{[ia]:[dc,Hc,Rc,Bc,qc],endpoint:Pu,[na]:Pa},{[ia]:[Kc,lc,Rc,Uc],endpoint:{[ua]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[Kc,lc,Rc,Bc,Dc],rules:[{endpoint:_u,[na]:Pa}],[na]:_a},{[ia]:[Kc,lc,Rc,Bc,qc],endpoint:_u,[na]:Pa},{[ia]:[Kc,Hc,hc,yc,Uc],endpoint:{[ua]:Fa,[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[Kc,Hc,hc,yc,Bc,Dc],rules:[{[ia]:ed,endpoint:Iu,[na]:Pa},{endpoint:Iu,[na]:Pa}],[na]:_a},{[ia]:[Kc,Hc,hc,yc,Bc,qc],endpoint:Iu,[na]:Pa},{[ia]:[Kc,Hc,Rc,Uc],endpoint:{[ua]:oc,[da]:Lc,[ma]:Sc},[na]:Pa},{[ia]:[Kc,Hc,Rc,Bc,Dc],rules:[{[ia]:ed,endpoint:{[ua]:oc,[da]:jc,[ma]:Sc},[na]:Pa},{endpoint:Mu,[na]:Pa}],[na]:_a},{[ia]:[Kc,Hc,Rc,Bc,qc],endpoint:Mu,[na]:Pa}],[na]:_a},tu],[na]:_a}],[na]:_a}],[na]:_a},{error:"A region must be set when sending requests to S3.",[na]:ka}]},pd=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"]}),gd=(e,t={})=>pd.get(e,(()=>((e,t)=>{const{endpointParams:r,logger:n}=t,{parameters:i,rules:o}=e;t.logger?.debug?.(`${Fo} Initial EndpointParams: ${$o(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 Uo(`Missing required parameter: '${e}'`);const c=Yo(o,{endpointParams:r,logger:n,referenceRecord:{}});return t.logger?.debug?.(`${Fo} Resolved endpoint: ${$o(c)}`),c})(fd,{endpointParams:e,logger:t.logger})));No.aws=rs;const md=(yd=async(e,t,r)=>({operation:ue(t).operation,region:await de(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 yd(e,t,r),i=ue(t)?.commandInstance?.constructor?.getEndpointParameterInstructions;if(!i)throw new Error(`getEndpointParameterInstructions() is not defined on \`${t.commandName}\``);const o=await As(r,{getEndpointParameterInstructions:i},e);return Object.assign(n,o)});var yd;function vd(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function bd(e){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}const wd=((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})(gd,(e=>{const t=[];return e.operation,t.push(vd(e)),t.push(bd(e)),t}),{"aws.auth#sigv4":vd,"aws.auth#sigv4a":bd}),kd=e=>{const t=(e=>(e.sigv4aSigningRegionSet=we(e.sigv4aSigningRegionSet),e))(Nt(e));return{...t}},Sd={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 Ed extends Or{constructor(e){super(e),Object.setPrototypeOf(this,Ed.prototype)}}class xd extends Ed{constructor(e){super({name:"NoSuchUpload",$fault:"client",...e}),this.name="NoSuchUpload",this.$fault="client",Object.setPrototypeOf(this,xd.prototype)}}class Ad extends Ed{constructor(e){super({name:"ObjectNotInActiveTierError",$fault:"client",...e}),this.name="ObjectNotInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,Ad.prototype)}}class Td extends Ed{constructor(e){super({name:"BucketAlreadyExists",$fault:"client",...e}),this.name="BucketAlreadyExists",this.$fault="client",Object.setPrototypeOf(this,Td.prototype)}}class Cd extends Ed{constructor(e){super({name:"BucketAlreadyOwnedByYou",$fault:"client",...e}),this.name="BucketAlreadyOwnedByYou",this.$fault="client",Object.setPrototypeOf(this,Cd.prototype)}}class Rd extends Ed{constructor(e){super({name:"NoSuchBucket",$fault:"client",...e}),this.name="NoSuchBucket",this.$fault="client",Object.setPrototypeOf(this,Rd.prototype)}}var Od,Pd;!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])}(Od||(Od={})),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])}(Pd||(Pd={}));class _d extends Ed{constructor(e){super({name:"InvalidObjectState",$fault:"client",...e}),this.name="InvalidObjectState",this.$fault="client",Object.setPrototypeOf(this,_d.prototype),this.StorageClass=e.StorageClass,this.AccessTier=e.AccessTier}}class Id extends Ed{constructor(e){super({name:"NoSuchKey",$fault:"client",...e}),this.name="NoSuchKey",this.$fault="client",Object.setPrototypeOf(this,Id.prototype)}}class Md extends Ed{constructor(e){super({name:"NotFound",$fault:"client",...e}),this.name="NotFound",this.$fault="client",Object.setPrototypeOf(this,Md.prototype)}}const Nd=e=>({...e,...e.SecretAccessKey&&{SecretAccessKey:qt},...e.SessionToken&&{SessionToken:qt}}),Fd=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:qt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:qt},...e.Credentials&&{Credentials:Nd(e.Credentials)}}),$d=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:qt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:qt}}),Ud=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:qt}}),Ld=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:qt}});class Bd extends Ed{constructor(e){super({name:"EncryptionTypeMismatch",$fault:"client",...e}),this.name="EncryptionTypeMismatch",this.$fault="client",Object.setPrototypeOf(this,Bd.prototype)}}class Dd extends Ed{constructor(e){super({name:"InvalidRequest",$fault:"client",...e}),this.name="InvalidRequest",this.$fault="client",Object.setPrototypeOf(this,Dd.prototype)}}class zd extends Ed{constructor(e){super({name:"InvalidWriteOffset",$fault:"client",...e}),this.name="InvalidWriteOffset",this.$fault="client",Object.setPrototypeOf(this,zd.prototype)}}class jd extends Ed{constructor(e){super({name:"TooManyParts",$fault:"client",...e}),this.name="TooManyParts",this.$fault="client",Object.setPrototypeOf(this,jd.prototype)}}class qd extends Ed{constructor(e){super({name:"ObjectAlreadyInActiveTierError",$fault:"client",...e}),this.name="ObjectAlreadyInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,qd.prototype)}}var Hd;!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])}(Hd||(Hd={}));const Wd=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:qt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:qt}}),Kd=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:qt},...e.SSEKMSKeyId&&{SSEKMSKeyId:qt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:qt}}),Vd=async(e,t)=>{const r=Je(e,t),n=Hr({},zr,{[ep]:e[Xh],[xp]:e[Zh],[Ap]:e[nf],[Cp]:e[rf],[Tp]:[()=>zr(e[_l]),()=>e[_l].toString()]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=Hr({[Hf]:[,""]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Qd=async(e,t)=>{const r=Je(e,t),n=Hr({},zr,{[dp]:e[Sh],[wp]:e[Hh],[Qf]:[()=>zr(e[Pl]),()=>e[Pl].toString()],[np]:e[eh],[Rf]:e[lh],[cp]:[()=>zr(e[hh]),()=>lr(e[hh]).toString()],[up]:[()=>zr(e[fh]),()=>e[fh].toString()]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=Hr({[$p]:[,"DeleteObject"],[Kf]:[,e[uf]]});return r.m("DELETE").h(n).q(i).b(undefined),r.build()},Gd=async(e,t)=>{const r=Je(e,t),n=Hr({},zr,{[Rf]:e[lh],[Of]:[()=>zr(e[ph]),()=>lr(e[ph]).toString()],[Pf]:e[gh],[_f]:[()=>zr(e[vh]),()=>lr(e[vh]).toString()],[Uf]:e[Fh],[Rp]:e[Yh],[Op]:e[ef],[Pp]:e[tf],[wp]:e[Hh],[np]:e[eh],[Xf]:e[zl]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=Hr({[$p]:[,"GetObject"],[Lf]:[,e[Uh]],[Bf]:[,e[Lh]],[Df]:[,e[Bh]],[zf]:[,e[Dh]],[jf]:[,e[zh]],[qf]:[()=>void 0!==e.ResponseExpires,()=>lr(e[jh]).toString()],[Kf]:[,e[uf]],[Ff]:[()=>void 0!==e.PartNumber,()=>e[Nh].toString()]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Jd=async(e,t)=>{const r=Je(e,t),n=Hr({},zr,{[wp]:e[Hh],[np]:e[eh],[mp]:[()=>zr(e[_h]),()=>(e[_h]||[]).map(Gr).join(", ")]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=Hr({[Mf]:[,"2"],[Sf]:[,e[Jl]],[xf]:[,e[rh]],[Nf]:[()=>void 0!==e.MaxKeys,()=>e[Eh].toString()],[$f]:[,e[Ih]],[kf]:[,e[Ql]],[Cf]:[()=>void 0!==e.FetchOwner,()=>e[oh].toString()],[Wf]:[,e[Qh]]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Xd=async(e,t)=>{const r=Je(e,t),n=Hr({},zr,{[wf]:e[Vl]||"application/octet-stream",[Vf]:e[Tl],[ff]:e[Nl],[pf]:e[Ul],[gf]:e[Ll],[mf]:e[Bl],[yf]:[()=>zr(e[Dl]),()=>e[Dl].toString()],[vf]:e[jl],[Ep]:e[Ml],[Gf]:e[Fl],[Jf]:e[$l],[Zf]:e[Wl],[Yf]:e[Kl],[Ef]:[()=>zr(e[Yl]),()=>lr(e[Yl]).toString()],[Rf]:e[lh],[Pf]:e[gh],[ip]:e[sh],[op]:e[ah],[sp]:e[ch],[ap]:e[uh],[Np]:[()=>zr(e[df]),()=>e[df].toString()],[xp]:e[Zh],[Sp]:e[Jh],[Fp]:e[lf],[Rp]:e[Yh],[Op]:e[ef],[Pp]:e[tf],[Ap]:e[nf],[Cp]:e[rf],[Tp]:[()=>zr(e[_l]),()=>e[_l].toString()],[wp]:e[Hh],[_p]:e[af],[pp]:e[Oh],[gp]:[()=>zr(e[Ph]),()=>{return(t=e[Ph],t.toISOString().replace(".000Z","Z")).toString();var t}],[fp]:e[Rh],[np]:e[eh],...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=Hr({[$p]:[,"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()},Zd=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return nl(e,t);const r=Hr({$metadata:Al(e),[Zh]:[,e.headers[xp]],[nf]:[,e.headers[Ap]],[rf]:[,e.headers[Cp]],[_l]:[()=>void 0!==e.headers[Tp],()=>Ht(e.headers[Tp])]}),n=Yt(er(await yi(e.body,t)),"body");return null!=n[Il]&&(r[Il]=xl(n[Il])),r},Yd=async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return nl(e,t);const r=Hr({$metadata:Al(e),[Xl]:[()=>void 0!==e.headers[tp],()=>Ht(e.headers[tp])],[uf]:[,e.headers[Mp]],[$h]:[,e.headers[bp]]});return await Qe(e.body,t),r},el=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return nl(e,t);const r=Hr({$metadata:Al(e),[Xl]:[()=>void 0!==e.headers[tp],()=>Ht(e.headers[tp])],[Rl]:[,e.headers[hf]],[ih]:[,e.headers[rp]],[Vh]:[,e.headers[vp]],[kh]:[()=>void 0!==e.headers[If],()=>Yt(yr(e.headers[If]))],[Dl]:[()=>void 0!==e.headers[yf],()=>ir(e.headers[yf])],[nh]:[,e.headers[Af]],[Fl]:[,e.headers[Gf]],[$l]:[,e.headers[Jf]],[Wl]:[,e.headers[Zf]],[Kl]:[,e.headers[Yf]],[xh]:[()=>void 0!==e.headers[lp],()=>or(e.headers[lp])],[uf]:[,e.headers[Mp]],[Nl]:[,e.headers[ff]],[Ul]:[,e.headers[pf]],[Ll]:[,e.headers[gf]],[Bl]:[,e.headers[mf]],[Hl]:[,e.headers[bf]],[Vl]:[,e.headers[wf]],[Yl]:[()=>void 0!==e.headers[Ef],()=>Yt(yr(e.headers[Ef]))],[th]:[,e.headers[Tf]],[lf]:[,e.headers[Fp]],[Zh]:[,e.headers[xp]],[Yh]:[,e.headers[Rp]],[tf]:[,e.headers[Pp]],[nf]:[,e.headers[Ap]],[_l]:[()=>void 0!==e.headers[Tp],()=>Ht(e.headers[Tp])],[Jh]:[,e.headers[Sp]],[$h]:[,e.headers[bp]],[Wh]:[,e.headers[kp]],[Mh]:[()=>void 0!==e.headers[hp],()=>or(e.headers[hp])],[cf]:[()=>void 0!==e.headers[Ip],()=>or(e.headers[Ip])],[Oh]:[,e.headers[pp]],[Ph]:[()=>void 0!==e.headers[gp],()=>Yt(fr(e.headers[gp]))],[Rh]:[,e.headers[fp]],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},tl=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return nl(e,t);const r=Hr({$metadata:Al(e),[$h]:[,e.headers[bp]]}),n=Yt(er(await yi(e.body,t)),"body");return""===n.CommonPrefixes?r[ql]=[]:null!=n[ql]&&(r[ql]=bl(Br(n[ql]))),""===n.Contents?r[Gl]=[]:null!=n[Gl]&&(r[Gl]=kl(Br(n[Gl]))),null!=n[Ql]&&(r[Ql]=tr(n[Ql])),null!=n[Jl]&&(r[Jl]=tr(n[Jl])),null!=n[rh]&&(r[rh]=tr(n[rh])),null!=n[yh]&&(r[yh]=Ht(n[yh])),null!=n[wh]&&(r[wh]=or(n[wh])),null!=n[Eh]&&(r[Eh]=or(n[Eh])),null!=n[Ah]&&(r[Ah]=tr(n[Ah])),null!=n[Th]&&(r[Th]=tr(n[Th])),null!=n[Ih]&&(r[Ih]=tr(n[Ih])),null!=n[Qh]&&(r[Qh]=tr(n[Qh])),r},rl=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return nl(e,t);const r=Hr({$metadata:Al(e),[ih]:[,e.headers[rp]],[nh]:[,e.headers[Af]],[Fl]:[,e.headers[Gf]],[$l]:[,e.headers[Jf]],[Wl]:[,e.headers[Zf]],[Kl]:[,e.headers[Yf]],[Zh]:[,e.headers[xp]],[uf]:[,e.headers[Mp]],[Yh]:[,e.headers[Rp]],[tf]:[,e.headers[Pp]],[nf]:[,e.headers[Ap]],[rf]:[,e.headers[Cp]],[_l]:[()=>void 0!==e.headers[Tp],()=>Ht(e.headers[Tp])],[sf]:[()=>void 0!==e.headers[yp],()=>ir(e.headers[yp])],[$h]:[,e.headers[bp]]});return await Qe(e.body,t),r},nl=async(e,t)=>{const r={...e,body:await vi(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 pl(r,t);case"ObjectNotInActiveTierError":case"com.amazonaws.s3#ObjectNotInActiveTierError":throw await yl(r,t);case"BucketAlreadyExists":case"com.amazonaws.s3#BucketAlreadyExists":throw await sl(r,t);case"BucketAlreadyOwnedByYou":case"com.amazonaws.s3#BucketAlreadyOwnedByYou":throw await al(r,t);case"NoSuchBucket":case"com.amazonaws.s3#NoSuchBucket":throw await hl(r,t);case"InvalidObjectState":case"com.amazonaws.s3#InvalidObjectState":throw await ul(r,t);case"NoSuchKey":case"com.amazonaws.s3#NoSuchKey":throw await fl(r,t);case"NotFound":case"com.amazonaws.s3#NotFound":throw await gl(r,t);case"EncryptionTypeMismatch":case"com.amazonaws.s3#EncryptionTypeMismatch":throw await cl(r,t);case"InvalidRequest":case"com.amazonaws.s3#InvalidRequest":throw await dl(r,t);case"InvalidWriteOffset":case"com.amazonaws.s3#InvalidWriteOffset":throw await ll(r,t);case"TooManyParts":case"com.amazonaws.s3#TooManyParts":throw await vl(r,t);case"ObjectAlreadyInActiveTierError":case"com.amazonaws.s3#ObjectAlreadyInActiveTierError":throw await ml(r,t);default:const i=r.body;return il({output:e,parsedBody:i,errorCode:n})}},il=(ol=Ed,({output:e,parsedBody:t,errorCode:r})=>{(({output:e,parsedBody:t,exceptionCtor:r,errorCode:n})=>{const i=_r(e),o=i.httpStatusCode?i.httpStatusCode+"":void 0,s=new r({name:t?.code||t?.Code||n||o||"UnknownError",$fault:"client",$metadata:i});throw Pr(s,t)})({output:e,parsedBody:t,exceptionCtor:ol,errorCode:r})});var ol;const sl=async(e,t)=>{const r=Hr({});e.body;const n=new Td({$metadata:Al(e),...r});return Pr(n,e.body)},al=async(e,t)=>{const r=Hr({});e.body;const n=new Cd({$metadata:Al(e),...r});return Pr(n,e.body)},cl=async(e,t)=>{const r=Hr({});e.body;const n=new Bd({$metadata:Al(e),...r});return Pr(n,e.body)},ul=async(e,t)=>{const r=Hr({}),n=e.body;null!=n[Ol]&&(r[Ol]=tr(n[Ol])),null!=n[Jh]&&(r[Jh]=tr(n[Jh]));const i=new _d({$metadata:Al(e),...r});return Pr(i,e.body)},dl=async(e,t)=>{const r=Hr({});e.body;const n=new Dd({$metadata:Al(e),...r});return Pr(n,e.body)},ll=async(e,t)=>{const r=Hr({});e.body;const n=new zd({$metadata:Al(e),...r});return Pr(n,e.body)},hl=async(e,t)=>{const r=Hr({});e.body;const n=new Rd({$metadata:Al(e),...r});return Pr(n,e.body)},fl=async(e,t)=>{const r=Hr({});e.body;const n=new Id({$metadata:Al(e),...r});return Pr(n,e.body)},pl=async(e,t)=>{const r=Hr({});e.body;const n=new xd({$metadata:Al(e),...r});return Pr(n,e.body)},gl=async(e,t)=>{const r=Hr({});e.body;const n=new Md({$metadata:Al(e),...r});return Pr(n,e.body)},ml=async(e,t)=>{const r=Hr({});e.body;const n=new qd({$metadata:Al(e),...r});return Pr(n,e.body)},yl=async(e,t)=>{const r=Hr({});e.body;const n=new Ad({$metadata:Al(e),...r});return Pr(n,e.body)},vl=async(e,t)=>{const r=Hr({});e.body;const n=new jd({$metadata:Al(e),...r});return Pr(n,e.body)},bl=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>(e=>{const t={};return null!=e[Ih]&&(t[Ih]=tr(e[Ih])),t})(e))),wl=(e,t)=>{const r={};return null!=e[bh]&&(r[bh]=tr(e[bh])),null!=e[kh]&&(r[kh]=Yt(fr(e[kh]))),null!=e[nh]&&(r[nh]=tr(e[nh])),""===e.ChecksumAlgorithm?r[Ml]=[]:null!=e[Ml]&&(r[Ml]=(e=>(e||[]).filter((e=>null!=e)).map((e=>tr(e))))(Br(e[Ml]))),null!=e[sf]&&(r[sf]=ir(e[sf])),null!=e[Jh]&&(r[Jh]=tr(e[Jh])),null!=e[Ch]&&(r[Ch]=Sl(e[Ch])),null!=e[Kh]&&(r[Kh]=El(e[Kh])),r},kl=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>wl(e))),Sl=(e,t)=>{const r={};return null!=e[Zl]&&(r[Zl]=tr(e[Zl])),null!=e[dh]&&(r[dh]=tr(e[dh])),r},El=(e,t)=>{const r={};return null!=e[mh]&&(r[mh]=Ht(e[mh])),null!=e[qh]&&(r[qh]=Yt(fr(e[qh]))),r},xl=(e,t)=>{const r={};return null!=e[Cl]&&(r[Cl]=tr(e[Cl])),null!=e[Gh]&&(r[Gh]=tr(e[Gh])),null!=e[of]&&(r[of]=tr(e[of])),null!=e[ih]&&(r[ih]=Yt(fr(e[ih]))),r},Al=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"]}),Tl="ACL",Cl="AccessKeyId",Rl="AcceptRanges",Ol="AccessTier",Pl="BypassGovernanceRetention",_l="BucketKeyEnabled",Il="Credentials",Ml="ChecksumAlgorithm",Nl="CacheControl",Fl="ChecksumCRC32",$l="ChecksumCRC32C",Ul="ContentDisposition",Ll="ContentEncoding",Bl="ContentLanguage",Dl="ContentLength",zl="ChecksumMode",jl="ContentMD5",ql="CommonPrefixes",Hl="ContentRange",Wl="ChecksumSHA1",Kl="ChecksumSHA256",Vl="ContentType",Ql="ContinuationToken",Gl="Contents",Jl="Delimiter",Xl="DeleteMarker",Zl="DisplayName",Yl="Expires",eh="ExpectedBucketOwner",th="ExpiresString",rh="EncodingType",nh="ETag",ih="Expiration",oh="FetchOwner",sh="GrantFullControl",ah="GrantRead",ch="GrantReadACP",uh="GrantWriteACP",dh="ID",lh="IfMatch",hh="IfMatchLastModifiedTime",fh="IfMatchSize",ph="IfModifiedSince",gh="IfNoneMatch",mh="IsRestoreInProgress",yh="IsTruncated",vh="IfUnmodifiedSince",bh="Key",wh="KeyCount",kh="LastModified",Sh="MFA",Eh="MaxKeys",xh="MissingMeta",Ah="Name",Th="NextContinuationToken",Ch="Owner",Rh="ObjectLockLegalHoldStatus",Oh="ObjectLockMode",Ph="ObjectLockRetainUntilDate",_h="OptionalObjectAttributes",Ih="Prefix",Mh="PartsCount",Nh="PartNumber",Fh="Range",$h="RequestCharged",Uh="ResponseCacheControl",Lh="ResponseContentDisposition",Bh="ResponseContentEncoding",Dh="ResponseContentLanguage",zh="ResponseContentType",jh="ResponseExpires",qh="RestoreExpiryDate",Hh="RequestPayer",Wh="ReplicationStatus",Kh="RestoreStatus",Vh="Restore",Qh="StartAfter",Gh="SecretAccessKey",Jh="StorageClass",Xh="SessionMode",Zh="ServerSideEncryption",Yh="SSECustomerAlgorithm",ef="SSECustomerKey",tf="SSECustomerKeyMD5",rf="SSEKMSEncryptionContext",nf="SSEKMSKeyId",of="SessionToken",sf="Size",af="Tagging",cf="TagCount",uf="VersionId",df="WriteOffsetBytes",lf="WebsiteRedirectLocation",hf="accept-ranges",ff="cache-control",pf="content-disposition",gf="content-encoding",mf="content-language",yf="content-length",vf="content-md5",bf="content-range",wf="content-type",kf="continuation-token",Sf="delimiter",Ef="expires",xf="encoding-type",Af="etag",Tf="expiresstring",Cf="fetch-owner",Rf="if-match",Of="if-modified-since",Pf="if-none-match",_f="if-unmodified-since",If="last-modified",Mf="list-type",Nf="max-keys",Ff="partNumber",$f="prefix",Uf="range",Lf="response-cache-control",Bf="response-content-disposition",Df="response-content-encoding",zf="response-content-language",jf="response-content-type",qf="response-expires",Hf="session",Wf="start-after",Kf="versionId",Vf="x-amz-acl",Qf="x-amz-bypass-governance-retention",Gf="x-amz-checksum-crc32",Jf="x-amz-checksum-crc32c",Xf="x-amz-checksum-mode",Zf="x-amz-checksum-sha1",Yf="x-amz-checksum-sha256",ep="x-amz-create-session-mode",tp="x-amz-delete-marker",rp="x-amz-expiration",np="x-amz-expected-bucket-owner",ip="x-amz-grant-full-control",op="x-amz-grant-read",sp="x-amz-grant-read-acp",ap="x-amz-grant-write-acp",cp="x-amz-if-match-last-modified-time",up="x-amz-if-match-size",dp="x-amz-mfa",lp="x-amz-missing-meta",hp="x-amz-mp-parts-count",fp="x-amz-object-lock-legal-hold",pp="x-amz-object-lock-mode",gp="x-amz-object-lock-retain-until-date",mp="x-amz-optional-object-attributes",yp="x-amz-object-size",vp="x-amz-restore",bp="x-amz-request-charged",wp="x-amz-request-payer",kp="x-amz-replication-status",Sp="x-amz-storage-class",Ep="x-amz-sdk-checksum-algorithm",xp="x-amz-server-side-encryption",Ap="x-amz-server-side-encryption-aws-kms-key-id",Tp="x-amz-server-side-encryption-bucket-key-enabled",Cp="x-amz-server-side-encryption-context",Rp="x-amz-server-side-encryption-customer-algorithm",Op="x-amz-server-side-encryption-customer-key",Pp="x-amz-server-side-encryption-customer-key-md5",_p="x-amz-tagging",Ip="x-amz-tagging-count",Mp="x-amz-version-id",Np="x-amz-write-offset-bytes",Fp="x-amz-website-redirect-location",$p="x-id";class Up extends(zt.classBuilder().ep({...Sd,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(e,t,r,n){return[ge(r,this.serialize,this.deserialize),Rs(r,e.getEndpointParameterInstructions()),To(r)]})).s("AmazonS3","CreateSession",{}).n("S3Client","CreateSessionCommand").f($d,Fd).ser(Vd).de(Zd).build()){}var Lp="3.701.0";function Bp(e){return"string"==typeof e?0===e.length:0===e.byteLength}var Dp={name:"SHA-1"},zp={name:"HMAC",hash:Dp},jp=new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]);const qp={};function Hp(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:qp}var Wp=function(){function e(e){this.toHash=new Uint8Array(0),void 0!==e&&(this.key=new Promise((function(t,r){Hp().crypto.subtle.importKey("raw",Kp(e),zp,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))}return e.prototype.update=function(e){if(!Bp(e)){var t=Kp(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 Hp().crypto.subtle.sign(zp,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):Bp(this.toHash)?Promise.resolve(jp):Promise.resolve().then((function(){return Hp().crypto.subtle.digest(Dp,e.toHash)})).then((function(e){return Promise.resolve(new Uint8Array(e))}))},e.prototype.reset=function(){this.toHash=new Uint8Array(0)},e}();function Kp(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 Vp=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function Qp(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&&Vp.every((function(t){return"function"==typeof e[t]}))}(e.crypto.subtle)}var Gp=function(){function e(e){if(!Qp(Hp()))throw new Error("SHA1 not supported");this.hash=new Wp(e)}return e.prototype.update=function(e,t){this.hash.update(Ti(e))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e}(),Jp={name:"SHA-256"},Xp={name:"HMAC",hash:Jp},Zp=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]),Yp=function(){function e(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return e.prototype.update=function(e){if(!Ci(e)){var t=Ti(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 Hp().crypto.subtle.sign(Xp,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):Ci(this.toHash)?Promise.resolve(Zp):Promise.resolve().then((function(){return Hp().crypto.subtle.digest(Jp,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){Hp().crypto.subtle.importKey("raw",Ti(e.secret),Xp,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))},e}();function eg(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 tg(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]og)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;r>0;)this.buffer[this.bufferLength++]=e[t++],r--,this.bufferLength===rg&&(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%rg>=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+(ng[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}(),ag=function(){function e(e){this.secret=e,this.hash=new sg,this.reset()}return e.prototype.update=function(e){if(!Ci(e)&&!this.error)try{this.hash.update(Ti(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 eg(this,void 0,void 0,(function(){return tg(this,(function(e){return[2,this.digestSync()]}))}))},e.prototype.reset=function(){if(this.hash=new sg,this.secret){this.outer=new sg;var e=function(e){var t=Ti(e);if(t.byteLength>rg){var r=new sg;r.update(t),t=r.digest()}var n=new Uint8Array(rg);return n.set(t),n}(this.secret),t=new Uint8Array(rg);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 dg=Jr(ug.exports);const lg=({serviceId:e,clientVersion:t})=>async r=>{const n="undefined"!=typeof window&&window?.navigator?.userAgent?dg.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 hg{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&&fg(t),new hg(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&fg(e),parseInt(De(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function fg(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}class pg{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(hg.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!Ag.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(Be(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 $i;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 $i).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 Cg{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 Rg{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 Og{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 Pg{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 _g(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 Ig{constructor({utf8Encoder:e,utf8Decoder:t}){this.eventStreamCodec=new Tg(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 Ng=e=>"function"==typeof ReadableStream&&e instanceof ReadableStream,Fg=e=>new Mg(e);const $g=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()},Ug=64,Lg=[1732584193,4023233417,2562383102,271733878];class Bg{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 xe(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===Ug&&(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%Ug>=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=zg(r,n,i,o,e.getUint32(0,!0),7,3614090360),o=zg(o,r,n,i,e.getUint32(4,!0),12,3905402710),i=zg(i,o,r,n,e.getUint32(8,!0),17,606105819),n=zg(n,i,o,r,e.getUint32(12,!0),22,3250441966),r=zg(r,n,i,o,e.getUint32(16,!0),7,4118548399),o=zg(o,r,n,i,e.getUint32(20,!0),12,1200080426),i=zg(i,o,r,n,e.getUint32(24,!0),17,2821735955),n=zg(n,i,o,r,e.getUint32(28,!0),22,4249261313),r=zg(r,n,i,o,e.getUint32(32,!0),7,1770035416),o=zg(o,r,n,i,e.getUint32(36,!0),12,2336552879),i=zg(i,o,r,n,e.getUint32(40,!0),17,4294925233),n=zg(n,i,o,r,e.getUint32(44,!0),22,2304563134),r=zg(r,n,i,o,e.getUint32(48,!0),7,1804603682),o=zg(o,r,n,i,e.getUint32(52,!0),12,4254626195),i=zg(i,o,r,n,e.getUint32(56,!0),17,2792965006),n=zg(n,i,o,r,e.getUint32(60,!0),22,1236535329),r=jg(r,n,i,o,e.getUint32(4,!0),5,4129170786),o=jg(o,r,n,i,e.getUint32(24,!0),9,3225465664),i=jg(i,o,r,n,e.getUint32(44,!0),14,643717713),n=jg(n,i,o,r,e.getUint32(0,!0),20,3921069994),r=jg(r,n,i,o,e.getUint32(20,!0),5,3593408605),o=jg(o,r,n,i,e.getUint32(40,!0),9,38016083),i=jg(i,o,r,n,e.getUint32(60,!0),14,3634488961),n=jg(n,i,o,r,e.getUint32(16,!0),20,3889429448),r=jg(r,n,i,o,e.getUint32(36,!0),5,568446438),o=jg(o,r,n,i,e.getUint32(56,!0),9,3275163606),i=jg(i,o,r,n,e.getUint32(12,!0),14,4107603335),n=jg(n,i,o,r,e.getUint32(32,!0),20,1163531501),r=jg(r,n,i,o,e.getUint32(52,!0),5,2850285829),o=jg(o,r,n,i,e.getUint32(8,!0),9,4243563512),i=jg(i,o,r,n,e.getUint32(28,!0),14,1735328473),n=jg(n,i,o,r,e.getUint32(48,!0),20,2368359562),r=qg(r,n,i,o,e.getUint32(20,!0),4,4294588738),o=qg(o,r,n,i,e.getUint32(32,!0),11,2272392833),i=qg(i,o,r,n,e.getUint32(44,!0),16,1839030562),n=qg(n,i,o,r,e.getUint32(56,!0),23,4259657740),r=qg(r,n,i,o,e.getUint32(4,!0),4,2763975236),o=qg(o,r,n,i,e.getUint32(16,!0),11,1272893353),i=qg(i,o,r,n,e.getUint32(28,!0),16,4139469664),n=qg(n,i,o,r,e.getUint32(40,!0),23,3200236656),r=qg(r,n,i,o,e.getUint32(52,!0),4,681279174),o=qg(o,r,n,i,e.getUint32(0,!0),11,3936430074),i=qg(i,o,r,n,e.getUint32(12,!0),16,3572445317),n=qg(n,i,o,r,e.getUint32(24,!0),23,76029189),r=qg(r,n,i,o,e.getUint32(36,!0),4,3654602809),o=qg(o,r,n,i,e.getUint32(48,!0),11,3873151461),i=qg(i,o,r,n,e.getUint32(60,!0),16,530742520),n=qg(n,i,o,r,e.getUint32(8,!0),23,3299628645),r=Hg(r,n,i,o,e.getUint32(0,!0),6,4096336452),o=Hg(o,r,n,i,e.getUint32(28,!0),10,1126891415),i=Hg(i,o,r,n,e.getUint32(56,!0),15,2878612391),n=Hg(n,i,o,r,e.getUint32(20,!0),21,4237533241),r=Hg(r,n,i,o,e.getUint32(48,!0),6,1700485571),o=Hg(o,r,n,i,e.getUint32(12,!0),10,2399980690),i=Hg(i,o,r,n,e.getUint32(40,!0),15,4293915773),n=Hg(n,i,o,r,e.getUint32(4,!0),21,2240044497),r=Hg(r,n,i,o,e.getUint32(32,!0),6,1873313359),o=Hg(o,r,n,i,e.getUint32(60,!0),10,4264355552),i=Hg(i,o,r,n,e.getUint32(24,!0),15,2734768916),n=Hg(n,i,o,r,e.getUint32(52,!0),21,1309151649),r=Hg(r,n,i,o,e.getUint32(16,!0),6,4149444226),o=Hg(o,r,n,i,e.getUint32(44,!0),10,3174756917),i=Hg(i,o,r,n,e.getUint32(8,!0),15,718787259),n=Hg(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(Lg),this.buffer=new DataView(new ArrayBuffer(Ug)),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}}function Dg(e,t,r,n,i,o){return((t=(t+e&4294967295)+(n+o&4294967295)&4294967295)<>>32-i)+r&4294967295}function zg(e,t,r,n,i,o,s){return Dg(t&r|~t&n,e,t,i,o,s)}function jg(e,t,r,n,i,o,s){return Dg(t&n|r&~n,e,t,i,o,s)}function qg(e,t,r,n,i,o,s){return Dg(t^r^n,e,t,i,o,s)}function Hg(e,t,r,n,i,o,s){return Dg(r^(t|~n),e,t,i,o,s)}const Wg="function"==typeof TextEncoder?new TextEncoder:null,Kg=e=>{if("string"==typeof e){if(Wg)return Wg.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}`)},Vg=["in-region","cross-region","mobile","standard","legacy"],Qg=()=>{const e="undefined"!=typeof window&&window?.navigator?.userAgent?dg.parse(window.navigator.userAgent):void 0,t=e?.platform?.type;return"tablet"===t||"mobile"===t},Gg=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(Qg()?"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 ${Vg.join(", ")}, got ${t}`)}})))(e),r=()=>t().then(Ir),n=(e=>({apiVersion:"2006-03-01",base64Decoder:e?.base64Decoder??Ee,base64Encoder:e?.base64Encoder??Ce,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??gd,extensions:e?.extensions??[],getAwsChunkedEncodingStream:e?.getAwsChunkedEncodingStream??Oe,httpAuthSchemeProvider:e?.httpAuthSchemeProvider??wd,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new ae},{schemeId:"aws.auth#sigv4a",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4a"),signer:new ce}],logger:e?.logger??new qr,sdkStreamMixin:e?.sdkStreamMixin??qe,serviceId:e?.serviceId??"S3",signerConstructor:e?.signerConstructor??ta,signingEscapePath:e?.signingEscapePath??!1,urlParser:e?.urlParser??Es,useArnRegion:e?.useArnRegion??!1,utf8Decoder:e?.utf8Decoder??xe,utf8Encoder:e?.utf8Encoder??Te}))(e);return{...n,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??Kg,credentialDefaultProvider:e?.credentialDefaultProvider??(e=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??lg({serviceId:n.serviceId,clientVersion:Lp}),eventStreamSerdeProvider:e?.eventStreamSerdeProvider??Fg,maxAttempts:e?.maxAttempts??3,md5:e?.md5??Bg,region:e?.region??(i="Region is missing",()=>Promise.reject(i)),requestHandler:Fe.create(e?.requestHandler??r),retryMode:e?.retryMode??(async()=>(await r()).retryMode||Ps),sha1:e?.sha1??Gp,sha256:e?.sha256??cg,streamCollector:e?.streamCollector??$e,streamHasher:e?.streamHasher??$g,useDualstackEndpoint:e?.useDualstackEndpoint??(()=>Promise.resolve(false)),useFipsEndpoint:e?.useFipsEndpoint??(()=>Promise.resolve(false))};var i},Jg=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}},Xg=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}},Zg=e=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()});class Yg extends Dt{constructor(...[e]){const t=Gg(e||{});var r;const n=function(e){const t=we(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()=>xs(await de(r)()):void 0,i=!!r,o={...e,endpoint:n,tls:t,isCustomEndpoint:i,useDualstackEndpoint:de(e.useDualstackEndpoint??!1),useFipsEndpoint:de(e.useFipsEndpoint??!1)};let s;return o.serviceConfiguredEndpoint=async()=>(e.serviceId&&!s&&(s=Ss(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 hs(t);const e=await t();return hs(e)},useFipsEndpoint:async()=>{const e="string"==typeof t?t:await t();return!!ls(e)||("function"!=typeof r?Promise.resolve(!!r):r())}}})((e=>{const{retryStrategy:t}=e,r=de(e.maxAttempts??3);return{...e,maxAttempts:r,retryStrategy:async()=>t||(await de(e.retryMode)()===Os.ADAPTIVE?new Ds(r):new Bs(r))}})((i=n,{...i,requestChecksumCalculation:de(i.requestChecksumCalculation??Q),responseChecksumValidation:de(i.responseChecksumValidation??G)}))))),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 uo((async e=>r().send(new n({Bucket:e,SessionMode:"ReadWrite"})))),bucketEndpoint:e.bucketEndpoint??!1}})(kd(o),{session:[()=>this,Up]}),a=((e,t)=>{const r={...Jg(e),...Ur(e),...N(e),...Xg(e)};return t.forEach((e=>e.configure(r))),{...e,...(i=r,{region:i.region()}),...Lr(r),...(n=r,{httpHandler:n.httpHandler()}),...Zg(r)};var n,i})(s,e?.extensions||[]);super(a),this.config=a,this.middlewareStack.use((e=>({applyToStack:t=>{t.add(cs(e),ds)}}))(this.config)),this.middlewareStack.use(Zs(this.config)),this.middlewareStack.use(gs(this.config)),this.middlewareStack.use(Gi(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}}),Ji)}})),this.middlewareStack.use(Yi(this.config)),this.middlewareStack.use(((e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(le(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r}),he)}}))(this.config,{httpAuthSchemeParametersProvider:md,identityProviderConfigProvider:async e=>new Ze({"aws.auth#sigv4":e.credentials,"aws.auth#sigv4a":e.credentials})})),this.middlewareStack.use(be(this.config)),this.middlewareStack.use(Oo(this.config)),this.middlewareStack.use(K(this.config)),this.middlewareStack.use(io(this.config)),this.middlewareStack.use(vo(this.config)),this.middlewareStack.use((e=>({applyToStack:t=>{t.addRelativeTo(ko(e),ve)}}))(this.config))}destroy(){super.destroy()}}const em={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0},tm=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?rm(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})}),em)}});function rm(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 nm extends(zt.classBuilder().ep({...Sd,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[ge(r,this.serialize,this.deserialize),Rs(r,e.getEndpointParameterInstructions()),To(r)]})).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").f(void 0,void 0).ser(Qd).de(Yd).build()){}class im extends(zt.classBuilder().ep({...Sd,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[ge(r,this.serialize,this.deserialize),Rs(r,e.getEndpointParameterInstructions()),Vi(r,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC32","CRC32C","SHA256","SHA1"]}),tm(r),so()]})).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").f(Ld,Ud).ser(Gd).de(el).build()){}class om extends(zt.classBuilder().ep({...Sd,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(e,t,r,n){return[ge(r,this.serialize,this.deserialize),Rs(r,e.getEndpointParameterInstructions()),To(r)]})).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").f(void 0,void 0).ser(Jd).de(tl).build()){}class sm extends(zt.classBuilder().ep({...Sd,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[ge(r,this.serialize,this.deserialize),Rs(r,e.getEndpointParameterInstructions()),Vi(r,{requestAlgorithmMember:"ChecksumAlgorithm",requestAlgorithmMemberHttpHeader:"x-amz-sdk-checksum-algorithm",requestChecksumRequired:!1}),to(),To(r),tm(r)]})).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").f(Kd,Wd).ser(Xd).de(rl).build()){}class am{constructor(e){this.config=e,this.taskQueue=new f(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return a(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);""===a||a.endsWith("/")||(a+="/");const c=new Yg({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o}});try{let e,t=[],r=[],i=!0;for(;i;){const o=yield c.send(new om({Bucket:n,Prefix:a,Delimiter:"/",ContinuationToken:e}));o.Contents&&(t=t.concat(o.Contents)),o.CommonPrefixes&&(r=r.concat(o.CommonPrefixes)),e=o.NextContinuationToken,i=!!e}let o=[];return t.forEach((e=>{if(!e.Key.endsWith("/")){const t=e.Key.substring(a.length);t.includes("/")||o.push({name:t,size:e.Size||0,type:"file",modified:e.LastModified?e.LastModified.toISOString():""})}})),r.forEach((e=>{const t=e.Prefix.substring(a.length).replace(/\/$/,"");t&&o.push({name:t,size:0,type:"folder",modified:""})})),console.log("File list:",o),o}catch(e){return console.error(e),[]}}))}deleteFile(e){return a(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 Yg({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 nm({Bucket:n,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class cm extends am{constructor(e){super(e)}uploadFile(e,t){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){let{endpoint:r,region:n,bucketName:i,accessKeyId:o,secretAccessKey:s,dir:a}=this.config;const c=new Yg({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 sm({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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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 Yg({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 im({Bucket:n,Key:c}));if(!e.Body)return console.error("No response body"),!1;const t=yield e.Body.transformToByteArray();return this.taskQueue.setDownloadedSize(t.length),t.buffer}catch(t){return console.error("Error downloading file:",t,e),!1}}))))))}))}}class um{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.url=o,this.dir=s,this.taskQueue=new f(5)}retryOperation(e,t=0){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){if(this.taskQueue.setDownloadedSize(0),-1===t.indexOf("."))return new ArrayBuffer(0);try{const r=btoa(this.username+":"+this.password);let n=this.url.endsWith("/")?this.url:this.url+"/",i=this.dir.startsWith("/")?this.dir.substring(1):this.dir;const o=yield e({url:n+i+"/"+t,method:"get",headers:{Authorization:"Basic "+r},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return o.status>=300?(console.error("Error occurred during file download:",o),!1):o.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return a(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).filter((t=>"."!==t.filename&&".."!==t.filename&&t.filename!==e)).map((e=>({name:e.basename,size:e.size||0,type:"directory"===e.type?"folder":"file",modified:e.lastmod})))}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 a(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 dm{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.refreshTokenPromise=null,this.taskQueue=new f(3)}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(this,void 0,void 0,(function*(){try{return(yield e.get(`${this.url}/list`,{params:{dir:t},auth:{username:this.username,password:this.password}})).data.files.map((e=>({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modifiedTime})))||[]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(this,void 0,void 0,(function*(){try{return(yield e.delete(`${this.url}/delete`,{params:{dir:t.split("/").slice(0,-1).join("/")||"",filename:t.split("/").pop()},auth:{username:this.username,password:this.password}})).data.success}catch(e){return console.error("Error deleting file:",e),!1}}))}}class lm extends dm{constructor(e){super(e)}getAuthHeader(){return`Basic ${btoa(`${this.username}:${this.password}`)}`}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){try{const n=r.split("/").pop()||"",i=r.substring(0,r.lastIndexOf("/"))||"";let o=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const s=new FormData;s.append("file",o);const a=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(i)}`,s,{headers:{Authorization:this.getAuthHeader(),"Content-Type":"multipart/form-data"},maxContentLength:1/0,maxBodyLength:1/0});return!(a.status>=300)||(console.error("Error occurred during file upload:",a),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const r=t.split("/").pop()||"",n=t.substring(0,t.lastIndexOf("/"))||"",i=yield e({url:`${this.url}/download`,method:"GET",params:{dir:n,filename:r},headers:{Authorization:this.getAuthHeader()},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});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}}))))))}))}}const hm=["book","config","cover","font"];class fm{constructor(e,t,r){this.type=e,this.remote="dropbox"===e?new x(t,r):"microsoft"===e?new P(t,r):"google"===e?new T(t,r):"microsoft_exp"===e?new P(Object.assign(Object.assign({},t),{isExp:!0}),r):"google_exp"===e?new T(Object.assign(Object.assign({},t),{isExp:!0}),r):"s3compatible"===e?new cm(t):"webdav"===e?new um(t):"docker"===e?new lm(t):"boxnet"===e?new S(t,r):"mega"===e?new R(t):"adrive"===e?new w(t,r):"pcloud"===e?new M(t,r):new _}downloadFile(e,t){return a(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 a(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r,t+"/"+e)}))}deleteFile(e,t){return a(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 a(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}listFileInfos(e){return a(this,void 0,void 0,(function*(){return yield this.remote.listFileInfos(e)}))}isExist(e,t){return a(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}downloadAllFiles(){return a(this,void 0,void 0,(function*(){for(let e of hm){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,e)}}))}authToken(e){return a(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()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const pm={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 = ?"},gm={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},mm={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function ym(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const vm={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 bm,wm={sqlStatement:{createTableStatement:ym({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:ym({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:ym({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:ym({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:ym({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:ym({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:ym({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:ym(pm),getByBookKeyStatement:ym(gm),getByBookKeysStatement:ym({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:ym(mm)},jsonToSqlite:ym({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:ym(vm)};class km{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 Sm{static generateBook(e,t,r,n,i,o,s){return new Promise(((c,u)=>a(this,void 0,void 0,(function*(){try{let a,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 s.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 s.getMetadata(),m=g.cover;break;case"txt":g=yield s.getMetadata(o),f=g.charset}let y=t.toUpperCase();a=(new Date).getTime()+"",c(new km(a,u,d,h,r,m,y,l,n,p,i,f))}catch(e){console.error(e),u(e)}}))))}}bm=Sm,Sm.getRendition=(e,t,r)=>{let n,i=t.format.toUpperCase();var o,s;return"CACHE"===i?n=new r.CacheRender(e,t):"MOBI"===i||"AZW3"===i||"AZW"===i?n=new r.MobiRender(e,t):"EPUB"===i?n=new r.EpubRender(e,t):"TXT"===i?n=new r.TxtRender(e,t):"MD"===i?n=new r.MdRender(e,t):"PDF"===i?n=new r.PdfRender(e,t):"FB2"===i?n=new r.Fb2Render(e,t):"DOCX"===i?n=new r.DocxRender(e,t):"HTML"===i||"XHTML"===i||"MHTML"===i||"HTM"===i||"XML"===i?n=new r.HtmlRender(e,t):"CBR"!==i&&"CBT"!==i&&"CBZ"!==i&&"CB7"!==i||(n=new r.ComicRender((o=e,s=new ArrayBuffer(o.byteLength),new Uint8Array(s).set(new Uint8Array(o)),s),t)),n},Sm.initMobileBook=(e,t,r,n,i,o,s,c,u,d)=>a(void 0,void 0,void 0,(function*(){try{window.ReactNativeWebView.postMessage(JSON.stringify({event:"user-agent",userAgent:navigator.userAgent}));const a=yield fetch(e);if(!a.ok)throw new Error(`Failed to download book: ${a.status} ${a.statusText}`);const l=yield a.arrayBuffer();window.ReactNativeWebView.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=l;let h=bm.getRendition(l,{format:t,readerMode:r,charset:n,animation:i,convertChinese:o,parserRegex:s,isDarkMode:u,isMobile:"yes",password:d},window.Kookit);window.rendition=h;let f=document.getElementById("page-area");t&&"TXT"===t.toUpperCase()?yield window.rendition.renderTo(f,c):yield window.rendition.renderTo(f),window.rendition.on("rendered",(()=>{let e=window.rendition.getPosition();"PDF"===t&&(e.chapterDocIndex=window.chapterDocIndex),window.ReactNativeWebView.postMessage(JSON.stringify({event:"content-loaded",bookLocation:e})),window.rendition.tranformText()})),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"}))}})),Sm.addMobileBook=(e,t,r,n,i,o,s="")=>a(void 0,void 0,void 0,(function*(){var a;try{if(window.ReactNativeWebView.postMessage(JSON.stringify({event:"user-agent",userAgent:navigator.userAgent})),"PDF"===r.toUpperCase()&&i>314572800){t=t.replace(/\.[^/.]+$/,"");let e=r.toUpperCase(),s=(new Date).getTime()+"",a=new km(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===(a=window.ReactNativeWebView)||void 0===a||a.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=u;let d=bm.getRendition(u,{format:r.toUpperCase(),readerMode:"",charset:"",animation:"",convertChinese:"no",parserRegex:s||"",isDarkMode:"no",isMobile:"yes",password:""},window.Kookit);window.rendition=d,t=t.replace(/\.[^/.]+$/,"");let l=yield Sm.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"}))}})),Sm.precacheMobileBook=(e,t)=>a(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 Em=g.cloudUrl,xm=g.cloudCNUrl;class Am{constructor(e,t){this.TokenService=e,this.ConfigService=t,this.baseUrl="china"===t.getItem("serverRegion")?xm:Em,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return a(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(this.baseUrl+"/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 a(this,void 0,void 0,(function*(){return Am.requestQueue||(Am.requestQueue=[]),new Promise(((t,r)=>{Am.requestQueue.push({config:e,resolve:t,reject:r}),Am.processingQueue||this.processQueue()}))}))}processQueue(){return a(this,void 0,void 0,(function*(){if(!Am.processingQueue){Am.processingQueue=!0;try{for(;Am.requestQueue.length>0;){const e=Am.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{Am.processingQueue=!1}}}))}executeRequest(t){return a(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);if(t.baseURL=this.baseUrl,t.headers)t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r;else{let e=this.ConfigService.getItem("appVersion"),n=this.ConfigService.getItem("appPlatform");t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r,"X-App-Version":e||"1.0.0","X-App-Platform":n||"web"}}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 a(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>a(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,s)=>{let c=this.ConfigService.getItem("appVersion"),u=this.ConfigService.getItem("appPlatform");const d=new r(this.baseUrl+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+n,"X-Request-ID":i,"X-App-Version":c||"1.0.0","X-App-Platform":u||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});d.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),d.addEventListener("message",(e=>a(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(d.close(),o(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),d.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);o(t),d.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return a(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>a(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,s)=>a(this,void 0,void 0,(function*(){let s=this.ConfigService.getItem("appVersion"),c=this.ConfigService.getItem("appPlatform");var u=new o(this.baseUrl+e.url,{headers:{"Content-Type":"text/plain",Authorization:"Bearer "+r,"X-Request-ID":n,"X-App-Version":s||"1.0.0","X-App-Platform":c||"web"},payload:JSON.stringify(e.data),method:"POST"});u.addEventListener("message",(e=>a(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(u.close(),i(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),u.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),u.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const t=JSON.parse(e.data);i(t),u.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}Am.processingQueue=!1,Am.requestQueue=[];class Tm extends Am{constructor(e,t){super(e,t)}getTransStream(e,t,r){return a(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 a(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 a(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 a(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 a(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 a(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 a(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 a(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 a(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 Cm extends Am{constructor(e,t){super(e,t)}encryptToken(e){return a(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 a(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 a(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 a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/refresh_token",data:e};return yield this.requestWithRetry(t)}))}getSyncData(){return a(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_data"})}))}updateSyncData(e){return a(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 Rm extends Am{constructor(e,t){super(e,t)}loginRegister(e){return a(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 a(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/logout"})}))}getLogins(){return a(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/get_logins"})}))}getLoginsV2(){return a(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/get_logins_v2"})}))}addLogin(e){return a(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 a(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 a(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/get_info"})}))}updateUserConfig(e){return a(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 a(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/member/user/get_temp_token"})}))}getTempUuid(){return a(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/member/user/get_temp_uuid"})}))}sendEmailCode(e){return a(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 a(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 a(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 a(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 Om={getAuthUrl:(e,t)=>{let r="";if("github"===e?r=`https://github.com/login/oauth/authorize?client_id=${m.githubClientId}&redirect_uri=${m.callbackUrl}&scope=${y.github.scopes.join(" ")}&response_type=code`:"google"===e?r=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${m.callbackUrl}&prompt=consent&response_type=code&client_id=${m.googleClientId}&scope=${y.google.scopes.join(" ")}&access_type=offline`:"facebook"===e?r=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${m.facebookClientId}&redirect_uri=${m.callbackUrl}&scope=&response_type=code`:"microsoft"===e&&(r=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${m.microsoftClientId}&scope=${y.microsoft.scopes.join(" ")}&response_type=code&redirect_uri=${m.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 Pm{static CompareDatabase(e,t,r){return a(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 a(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:[],save:[],upload:[]},mapConfig:{update:[],delete:[],conflict:[],save:[],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 a(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 a(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 a(this,void 0,void 0,(function*(){let o=[];for(let t of u){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 u)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 a(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 a(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 a(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 _m=(Im=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,t){localStorage.setItem(e,t)}static removeItem(e){localStorage.removeItem(e)}},Mm="browser",class extends Im{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:Mm,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 Im,Mm;class Nm{static saveAllToken(e){return a(this,void 0,void 0,(function*(){if(e)if(s){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 a(this,void 0,void 0,(function*(){if(s){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 a(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 a(this,void 0,void 0,(function*(){return JSON.parse((yield this.getAllToken())||"{}")[e]||null}))}static deleteToken(e){return a(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 a(this,void 0,void 0,(function*(){try{let t=yield this.getFingerprint();const r=yield Um(t),n="undefined"!=typeof crypto&&crypto.subtle?yield function(e,t,r={alg:"HS256",typ:"JWT"}){return a(this,void 0,void 0,(function*(){const n=Fm((new TextEncoder).encode(JSON.stringify(r))),i=Fm((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}.${Fm(yield crypto.subtle.sign("HMAC",s,o))}`}))}(e,r):function(e,t){if(!e||!t)return"";const r=h((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<=ny}}function _y(e){return function(t){return null==t?void 0:t[e]}}var Iy=_y("byteLength"),My=Py(Iy),Ny=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var Fy=Vm?function(e){return Zm?Zm(e)&&!Ey(e):My(e)&&Ny.test(Wm.call(e))}:Oy(!1),$y=_y("length");function Uy(e,t){t=function(e){for(var t={},r=e.length,n=0;n":">",'"':""","'":"'","`":"`"},Cv=Av(Tv),Rv=Av(iv(Tv)),Ov=Dy.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},Pv=/(.)^/,_v={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},Iv=/\\|'|\r|\n|\u2028|\u2029/g;function Mv(e){return"\\"+_v[e]}var Nv=/^\s*(\w|\$)+\s*$/;var Fv=0;function $v(e,t,r,n,i){if(!(n instanceof t))return e.apply(r,i);var o=dv(e.prototype),s=e.apply(o,i);return oy(s)?s:o}var Uv=iy((function(e,t){var r=Uv.placeholder,n=function(){for(var i=0,o=t.length,s=Array(o),a=0;a1)Dv(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 Kv=Uv(Wv,2);function Vv(e,t,r){t=kv(t,r);for(var n,i=Ly(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(Hm.call(n,s,a),Ry))>=0?o+s:-1;for(o=e>0?s:a-1;o>=0&&o=3;return function(t,r,n,i){var o=!Bv(t)&&Ly(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 lb=iy((function(e,t,r){var n,i;return vy(t)?i=t:(t=hv(t),n=t.slice(0,-1),t=t[t.length-1]),nb(e,(function(e){var o=i;if(!o){if(n&&n.length&&(e=fv(e,n)),null==e)return;o=e[t]}return null==o?o:o.apply(e,r)}))}));function hb(e,t){return nb(e,yv(t))}function fb(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=Bv(e)?e:nv(e)).length;ao&&(o=n);else t=kv(t,r),rb(e,(function(e,r,n){((i=t(e,r,n))>s||i===-1/0&&o===-1/0)&&(o=e,s=i)}));return o}var pb=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;function gb(e){return e?xy(e)?Hm.call(e):uy(e)?e.match(pb):Bv(e)?nb(e,gv):nv(e):[]}function mb(e,t,r){if(null==t||r)return Bv(e)||(e=nv(e)),e[Ev(e.length-1)];var n=gb(e),i=$y(n);t=Math.max(Math.min(t,i),0);for(var o=i-1,s=0;s1&&(n=vv(n,t[1])),t=Wy(e)):(n=Sb,t=Dv(t,!1,!1),e=Object(e));for(var i=0,o=t.length;i1&&(r=t[1])):(t=nb(Dv(t,!1,!1),String),n=function(e,r){return!db(t,r)}),Eb(e,n,r)}));function Ab(e,t,r){return Hm.call(e,0,Math.max(0,e.length-(null==t||r?1:t)))}function Tb(e,t,r){return null==e||e.length<1?null==t||r?void 0:[]:null==t||r?e[0]:Ab(e,e.length-t)}function Cb(e,t,r){return Hm.call(e,null==t||r?1:t)}var Rb=iy((function(e,t){return t=Dv(t,!0,!0),ab(e,(function(e){return!db(t,e)}))})),Ob=iy((function(e,t){return Rb(e,t)}));function Pb(e,t,r,n){ay(t)||(n=r,r=t,t=!1),null!=r&&(r=kv(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=xv()-i;t>u?n=setTimeout(c,t-u):(n=null,r||(s=e.apply(a,o)),n||(o=a=null))},u=iy((function(u){return a=this,o=u,i=xv(),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 Uv(t,e)},negate:Hv,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:Wv,once:Kv,findKey:Vv,findIndex:Gv,findLastIndex:Jv,sortedIndex:Xv,indexOf:Yv,lastIndexOf:eb,find:tb,detect:tb,findWhere:function(e,t){return tb(e,mv(t))},each:rb,forEach:rb,map:nb,collect:nb,reduce:ob,foldl:ob,inject:ob,reduceRight:sb,foldr:sb,filter:ab,select:ab,reject:function(e,t,r){return ab(e,Hv(kv(t)),r)},every:cb,all:cb,some:ub,any:ub,contains:db,includes:db,include:db,invoke:lb,pluck:hb,where:function(e,t){return ab(e,mv(t))},max:fb,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=Bv(e)?e:nv(e)).length;an||void 0===r)return 1;if(re.map((e=>e.name)),Bb=e=>e.map((e=>e.key)),Db=(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 zb{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?Db(i,n).reverse():Db(i,n);if(2===t.sort){let r=Lb(e),n=Lb(e).sort();return 1===t.order?Db(n,r).reverse():Db(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=Bb(e);return 1===t.order?Db(Ub.union(n,i),i).reverse():Db(Ub.union(n,i),i)}if(5===t.sort){let r=Bb(e),n=(e=>Ub.sortBy(e.map((e=>({key:e.key,author:e.author}))),"author").map((e=>e.key)))(e);return 1===t.order?Db(n,r).reverse():Db(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=Bb(e);return 1===t.order?Db(n,i).reverse():Db(n,i)}}static sortNotes(e,t,r=[]){if(3===t.sort){let r=Ub.clone(e).reverse(),n=Ub.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:e.chapterIndex}))));n=1===t.order?Ub.sortBy(n,"chapterIndex"):Ub.sortBy(n,"chapterIndex").reverse();let i=Ub.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=Ub.clone(e).reverse(),n=Ub.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=Ub.clone(e).reverse(),i=Ub.uniq(e.map((e=>{let t=Ub.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=Ub.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=Ub.clone(e).reverse(),n=Ub.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:parseInt(JSON.parse(e.cfi).chapterDocIndex)}))));n=1===t.order?Ub.sortBy(n,"chapterIndex"):Ub.sortBy(n,"chapterIndex").reverse();let i=Ub.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 jb{static getDefaultCss(e){return`::selection{background:#f3a6a68c}::-moz-selection{background:#f3a6a68c}.kookit-note:hover{cursor:pointer;}body,html{margin: 0px !important; padding: 0px !important; font-size: 18px;}.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"):""}px !important;line-height: ${e.getReaderConfig("lineHeight")||""} !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":""};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;word-wrap: break-word !important; writing-mode: horizontal-tb !important; `}}class qb{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{Sm as BookHelper,p as CommonTool,_m as ConfigService,v as KookitConfig,Om as LoginHelper,Tm as ReaderRequest,qb as SearchUtil,zb as SortUtil,wm as SqlStatement,jb as StyleHelper,Pm as SyncHelper,fm as SyncUtil,Cm as ThirdpartyRequest,Nm as TokenService,Rm 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{SSE as o}from"sse.js";import{isElectron as s}from"react-device-detect";function a(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 c=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,u=["books","notes","bookmarks","plugins","words"],d=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}const f={_chars:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",encode(e){if("string"!=typeof e)throw new Error("Input must be a string");let t="",r=0;const n=this._stringToUtf8Bytes(e),i=n.length;for(;r>2,c=(3&e)<<4|o>>4,u=(15&o)<<2|s>>6,d=63&s;t+=this._chars.charAt(a),t+=this._chars.charAt(c),t+=r-2>=i?"=":this._chars.charAt(u),t+=r-1>=i?"=":this._chars.charAt(d)}return t},decode(e){if("string"!=typeof e)throw new Error("Input must be a string");if((e=e.replace(/[^A-Za-z0-9+/]/g,"")).length%4!=0)throw new Error("Invalid Base64 string length");const t=[];let r=0;const n=e.length;for(;r>4,c=(15&i)<<4|o>>2,u=(3&o)<<6|s;t.push(a),-1!==o&&t.push(c),-1!==s&&t.push(u)}return this._utf8BytesToString(t)},_stringToUtf8Bytes(e){const t=[];for(let r=0;r>6),t.push(128|63&n);else if(55296==(64512&n)&&r+1>18),t.push(128|e>>12&63),t.push(128|e>>6&63),t.push(128|63&e)}else t.push(239,191,189),r--}else t.push(224|n>>12),t.push(128|n>>6&63),t.push(128|63&n)}return t},_utf8BytesToString(e){let t="",r=0;for(;r65535){const r=e-65536;t+=String.fromCharCode(55296|r>>10),t+=String.fromCharCode(56320|1023&r)}else t+=String.fromCharCode(e)}else t+="�"}else t+="�"}return t},encodeURL(e){return this.encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},decodeURL(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return this.decode(e)}};class p{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.hasFailedTasks=!1,this.downloadedSize=0,this.maxConcurrency=e}addTask(e){return a(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{const n=()=>a(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:u,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:d,arrayBufferToBase64:l,generateSHA256Hash:function(e){return a(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):h(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"],Base64:f};const m={publicUrl:"https://api.960960.xyz",cloudUrl:"https://cloud.960960.xyz",cloudCNUrl:"https://cloud.koodoreader.cn",devUrl:"http://192.168.28.159:8000"},y={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"},v={google:{clientId:y.googleClientId,scopes:["openid email profile"],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{prompt:"consent",scope:"openid email profile"}},microsoft:{clientId:y.microsoftClientId,scopes:["openid","profile","User.Read","offline_access"],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{scope:"openid profile User.Read offline_access"}},facebook:{clientId:y.facebookClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{scope:""}},github:{clientId:y.githubClientId,scopes:["user:email"],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{scope:"user:email"}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{scope:""}}};var b={CloudConfig:m,ThirdpartyConfig:y,LoginAuthRequest:v,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:y.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{token_access_type:"offline"}},boxnet:{clientId:y.boxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}},pcloud:{clientId:y.pcloudClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{grant_type:"authorization_code"}},adrive:{clientId:y.adriveClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}},microsoft:{clientId:y.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{scope:"files.readwrite.appfolder offline_access"}},google:{clientId:y.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive.file",access_type:"offline"}},microsoft_exp:{clientId:y.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{scope:"files.readwrite.all offline_access"}},google_exp:{clientId:y.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive",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"},microsoft_exp:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google_exp:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"}}};class w{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new p(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=5){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(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 a(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(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(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 console.log("All items:",o),[...new Set(o.map((e=>({name:e.name,size:e.size,type:e.type,modified:e.updated_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(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 a(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 a(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=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:y.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:y.adriveClientId,redirect_uri:y.callbackUrl,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class k extends w{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return new Promise(((n,i)=>a(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)=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});r(a.data)}catch(e){console.error("Error downloading file:",e),r(!1)}}))))}}class S{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new p(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(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(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(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);console.log(i,"folderId");let 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}`}});console.log("Response data:",t.data);const n=t.data.entries||[];o=o.concat(n),s+=n.length,a=n.length===c&&t.data.total_count>s}return console.log("All items:",o),[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:e.type,modified:e.content_modified_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(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 a(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=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:y.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:y.boxClientId,redirect_uri:y.callbackUrl,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class E extends S{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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;console.log(c,"file");const u=yield e({url:`https://api.box.com/2.0/files/${c.id}/content`,method:"get",headers:{Authorization:`Bearer ${r}`},responseType:"arraybuffer",onDownloadProgress:e=>{console.log(e,"progressEvent"),this.taskQueue.setDownloadedSize(e.loaded)}});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 x{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new p(3)}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(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 console.log("Total items fetched:",n),[...new Set(n.map((e=>({name:e.name,size:e.size||0,type:e[".tag"],modified:e.client_modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(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 a(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=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:y.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${y.dropboxClientId}&redirect_uri=${y.callbackUrl}`}}class A extends x{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});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 T{constructor(e,t){this.isExp=!1,this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new p(3),this.isExp=this.config.isExp||!1,void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(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&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 a(this,void 0,void 0,(function*(){t=this.baseFolder+"/"+t;const r=yield this.refreshToken();if(""===t)return"root";const n=t.split("/").filter((e=>""!==e.trim()));let i="root";for(const t of n){let n=yield this.getFolderId(t,i);if(!n){const o={name:t,mimeType:"application/vnd.google-apps.folder",parents:[i]};try{n=(yield e.post("https://www.googleapis.com/drive/v3/files",o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error(`Error occurred during folder creation for ${t}:`,e),e}}i=n}return i}))}getFolderId(t,r){return a(this,void 0,void 0,(function*(){const n=yield this.refreshToken(),i=`https://www.googleapis.com/drive/v3/files?q=name='${t=encodeURIComponent(t)}'+and+mimeType='application/vnd.google-apps.folder'+and+'${r}'+in+parents&fields=files(id,name)`;try{const t=(yield e.get(i,{headers:{Authorization:`Bearer ${n}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(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&fields=nextPageToken,files(id,name,size,mimeType)&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 console.log("Total items fetched:",i),[...new Set(i.map((e=>({name:e.name,size:e.size||0,type:"application/vnd.google-apps.folder"===e.mimeType?"folder":"file",modified:e.modifiedTime}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return a(this,void 0,void 0,(function*(){const r=t.split("/")[1],n=yield this.checkFolder(t),i=yield this.refreshToken(),o=yield this.getFileId(r,n);if(""===o)return console.error("File not found:",r),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${o}`,{headers:{Authorization:`Bearer ${i}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return a(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=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:y.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${y.callbackUrl}&prompt=consent&response_type=code&client_id=${y.googleClientId}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class C extends T{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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(),a=c(s||""),u=r.split("/")[0],d=yield this.checkFolder(u),l=yield this.getFileId(i||"",d);const h={mimeType:a,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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});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 a(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 R{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new p(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(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 a(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 a(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const n=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return a(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=>({name:e.name,size:e.size||0,type:e.directory?"folder":"file",modified:e.timestamp?new Date(1e3*e.timestamp).toISOString():""})));return r}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return a(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 O extends R{constructor(e){super(e)}uploadFile(e,t){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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;const o=yield i.downloadBuffer();return this.taskQueue.setDownloadedSize(o.size),o.buffer}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class P{constructor(e,t){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new p(3),this.isExp=this.config.isExp||!1,this.baseUrl=this.isExp?"https://graph.microsoft.com/v1.0/me/drive/root":"https://graph.microsoft.com/v1.0/me/drive/special/approot",void 0===this.config.baseFolder?this.baseFolder=this.isExp?"KoodoReader":"":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let n,i=[];if(""===t)n=`${this.baseUrl}/children`;else{const e=encodeURIComponent(t);n=`${this.baseUrl}:/${e}:/children`}for(;n;){const t=yield e.get(n,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(t.status>=300)break;const o=t.data.value||[];i=i.concat(o),n=t.data["@odata.nextLink"]||""}return console.log("All items fetched:",i),[...new Set(i.map((e=>({name:e.name,size:e.size||0,type:e.folder?"folder":"file",modified:e.lastModifiedDateTime}))))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const n=yield e.delete(`${this.baseUrl}:/${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 a(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=(()=>a(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 a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:y.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${y.microsoftClientId}&scope=${this.isExp?"files.readwrite.all":"files.readwrite.appfolder"} offline_access&response_type=code&redirect_uri=${y.callbackUrl}`}}class _ extends P{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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});for(r=this.baseFolder+"/"+r;r.startsWith("/");)r=r.substring(1);const s=this.baseUrl+":/"+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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const n=`${this.baseUrl}:/${t}:/content`,i=yield e.get(n,{responseType:"arraybuffer",headers:{Authorization:"Bearer "+r},maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});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 I{downloadFile(e,t){return a(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return a(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return a(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return a(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class M{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new p(3)}retryOperation(e,t=5){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(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 a(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(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(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=>({name:e.name,size:e.size||0,type:e.isfolder?"folder":"file",modified:e.modified})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(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 a(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return a(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:y.callbackUrl,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${y.pcloudClientId}&response_type=code&redirect_uri=${y.callbackUrl}`}}class N extends M{constructor(e,t){super(e,t)}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});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 F=e=>{let t=e.httpHandler;return{setHttpHandler(e){t=e},httpHandler:()=>t,updateHttpClientConfig(e,r){t.updateHttpClientConfig(e,r)},httpHandlerConfigs:()=>t.httpHandlerConfigs()}};var $,U,L,B,D;!function(e){e.HEADER="header",e.QUERY="query"}($||($={})),function(e){e.HEADER="header",e.QUERY="query"}(U||(U={})),function(e){e.HTTP="http",e.HTTPS="https"}(L||(L={})),function(e){e.MD5="md5",e.CRC32="crc32",e.CRC32C="crc32c",e.SHA1="sha1",e.SHA256="sha256"}(B||(B={})),function(e){e[e.HEADER=0]="HEADER",e[e.TRAILER=1]="TRAILER"}(D||(D={}));const z="__smithy_context";var j,q;!function(e){e.PROFILE="profile",e.SSO_SESSION="sso-session",e.SERVICES="services"}(j||(j={})),function(e){e.HTTP_0_9="http/0.9",e.HTTP_1_0="http/1.0",e.TDS_8_0="tds/8.0"}(q||(q={}));class H{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 H({...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 H.clone(this)}}class W{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 K={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0},V=e=>({applyToStack:t=>{t.add(function(e){return t=>async r=>{const{request:n}=r;return H.isInstance(n)&&n.body&&"node"===e.runtime&&"FetchHttpHandler"!==e.requestHandler?.constructor?.name&&(n.headers={...n.headers,Expect:"100-continue"}),t({...r,request:n})}}(e),K)}}),Q="WHEN_SUPPORTED",G=Q,J=Q;var X,Z;!function(e){e.MD5="MD5",e.CRC32="CRC32",e.CRC32C="CRC32C",e.SHA1="SHA1",e.SHA256="SHA256"}(X||(X={})),function(e){e.HEADER="header",e.TRAILER="trailer"}(Z||(Z={}));const Y=X.MD5,ee=X.CRC32;var te;function re(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"}(te||(te={}));const ne=e=>W.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,ie=e=>new Date(Date.now()+e),oe=(e,t)=>{const r=Date.parse(e);return((e,t)=>Math.abs(ie(t).getTime()-e)>=3e5)(r,t)?r-Date.now():t},se=(e,t)=>{if(!t)throw new Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},ae=async e=>{const t=se("context",e.context),r=se("config",e.config),n=t.endpointV2?.properties?.authSchemes?.[0],i=se("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 ce{async sign(e,t,r){if(!H.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const n=await ae(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:ie(i.systemClockOffset),signingRegion:s,signingService:a})}errorHandler(e){return t=>{const r=t.ServerTime??ne(t.$response);if(r){const n=se("config",e.config),i=n.systemClockOffset;n.systemClockOffset=oe(r,n.systemClockOffset);n.systemClockOffset!==i&&t.$metadata&&(t.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const r=ne(e);if(r){const e=se("config",t.config);e.systemClockOffset=oe(r,e.systemClockOffset)}}}class ue extends ce{async sign(e,t,r){if(!H.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 ae(r),c=(await(n.sigv4aSigningRegionSet?.())??s??[o]).join(",");return await i.sign(e,{signingDate:ie(n.systemClockOffset),signingRegion:c,signingService:a})}}const de=e=>e[z]||(e[z]={}),le=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t};const he=(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=de(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)},fe={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},pe={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},ge={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function me(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),pe),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),ge)}}}const ye=e=>e=>{throw e},ve=(e,t)=>{},be={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},we=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{if(!H.isInstance(r.request))return e(r);const n=de(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||ye)(i));return(s.successHandler||ve)(a.response,i),a}),be)}}),ke=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t},Se={},Ee=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);Se[r]=e,Ee[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;Se[r]=n,Ee[n]=r}for(let e=0;e<10;e++){Se[e.toString(10)]=e+52;const t=e.toString(10),r=e+52;Se[t]=r,Ee[r]=t}Se["+"]=62,Ee[62]="+",Se["/"]=63,Ee[63]="/";const xe=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)},Ae=e=>(new TextEncoder).encode(e),Te=e=>"string"==typeof e?Ae(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e),Ce=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 Re(e){let t;t="string"==typeof e?Ae(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 Oe extends Uint8Array{static fromString(e,t="utf-8"){if("string"==typeof e)return function(e,t){return"base64"===t?Oe.mutate(xe(e)):Oe.mutate(Ae(e))}(e,t);throw new Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,Oe.prototype),e}transformToString(e="utf-8"){return function(e,t="utf-8"){return"base64"===t?Re(e):Ce(e)}(this,e)}}const Pe=(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`)}})},_e=e=>encodeURIComponent(e).replace(/[!'()*]/g,Ie),Ie=e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`;function Me(e,t){return new Request(e,t)}function Ne(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 Fe={supported:void 0};class $e{static create(e){return"function"==typeof e?.handle?e:new $e(e)}constructor(e){"function"==typeof e?this.configProvider=e().then((e=>e||{})):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),void 0===Fe.supported&&(Fe.supported=Boolean("undefined"!=typeof Request&&"keepalive"in Me("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=_e(r),Array.isArray(n))for(let e=0,i=n.length;e{};const p=Me(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 W({headers:r,reason:e.statusText,statusCode:e.status,body:e.body})}:e.blob().then((t=>({response:new W({headers:r,reason:e.statusText,statusCode:e.status,body:t})})))})),Ne(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 Ue=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 Le={},Be={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();1===t.length&&(t=`0${t}`),Le[e]=t,Be[t]=e}function De(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),qe="The stream has already been transformed.",He=e=>{if(!We(e)&&!je(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(qe);return t=!0,await Ue(e)};return Object.assign(e,{transformToByteArray:r,transformToString:async e=>{const t=await r();if("base64"===e)return Re(t);if("hex"===e)return ze(t);if(void 0===e||"utf8"===e||"utf-8"===e)return Ce(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(qe);if(t=!0,We(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(je(e))return e;throw new Error(`Cannot transform payload to web stream, got ${e}`)}})},We=e=>"function"==typeof Blob&&e instanceof Blob;const Ke="function"==typeof ReadableStream?ReadableStream:function(){};class Ve extends Ke{}const Qe=({expectedChecksum:e,checksum:t,source:r,checksumSourceLocation:n,base64Encoder:i})=>{if(!je(r))throw new Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);const o=i??Re;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,Ve.prototype),a},Ge=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return Oe.mutate(e);if(!e)return Oe.mutate(new Uint8Array);const r=t.streamCollector(e);return Oe.mutate(await r)};function Je(e){return encodeURIComponent(e).replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function Xe(e,t){return new Ze(e,t)}class Ze{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 H({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=>Je(e))).join("/"):Je(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 Ye{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 et=(tt=3e5,e=>rt(e)&&e.expiration.getTime()-Date.now()void 0!==e.expiration,nt="X-Amz-Date",it="X-Amz-Signature",ot="X-Amz-Security-Token",st="authorization",at=nt.toLowerCase(),ct=[st,at,"date"],ut=it.toLowerCase(),dt="x-amz-content-sha256",lt=ot.toLowerCase(),ht={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},ft=/^proxy-/,pt=/^sec-/,gt="AWS4-HMAC-SHA256",mt="AWS4-HMAC-SHA256-PAYLOAD",yt="aws4_request",vt={},bt=[],wt=(e,t,r)=>`${e}/${t}/${r}/${yt}`,kt=(e,t,r)=>{const n=new e(t);return n.update(Te(r)),n.digest()},St=({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 ht||t?.has(o)||ft.test(o)||pt.test(o))&&(!r||r&&!r.has(o))||(n[o]=e[i].trim().replace(/\s+/g," "))}return n},Et=e=>"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(e),xt=async({headers:e,body:t},r)=>{for(const t of Object.keys(e))if(t.toLowerCase()===dt)return e[t];if(null==t)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if("string"==typeof t||ArrayBuffer.isView(t)||Et(t)){const e=new r;return e.update(Te(t)),ze(await e.digest())}return"UNSIGNED-PAYLOAD"};class At{format(e){const t=[];for(const r of Object.keys(e)){const n=Ae(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=Ae(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(Rt.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!Ct.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(De(e.value.replace(/\-/g,"")),1),d}}}var Tt;!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"}(Tt||(Tt={}));const Ct=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Rt{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&&Ot(t),new Rt(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&Ot(e),parseInt(ze(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function Ot(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}const Pt=e=>{e=H.clone(e);for(const t of Object.keys(e.headers))ct.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e},_t=e=>"number"==typeof e?new Date(1e3*e):"string"==typeof e?Number(e)?new Date(1e3*Number(e)):new Date(e):e;class It{constructor({applyChecksum:e,credentials:t,region:r,service:n,sha256:i,uriEscapePath:o=!0}){this.headerFormatter=new At,this.service=n,this.sha256=i,this.uriEscapePath=o,this.applyChecksum="boolean"!=typeof e||e,this.regionProvider=le(r),this.credentialProvider=le(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}=Mt(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=wt(f,l,u??this.service),g=((e,t={})=>{const{headers:r,query:n={}}=H.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}})(Pt(e),{unhoistableHeaders:o,hoistableHeaders:a});d.sessionToken&&(g.query[ot]=d.sessionToken),g.query["X-Amz-Algorithm"]=gt,g.query["X-Amz-Credential"]=`${d.accessKeyId}/${p}`,g.query[nt]=h,g.query["X-Amz-Expires"]=n.toString(10);const m=St(g,i,s);return g.query["X-Amz-SignedHeaders"]=Nt(m),g.query[it]=await this.getSignature(h,p,this.getSigningKey(d,l,f,u),this.createCanonicalRequest(g,m,await xt(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}=Mt(r),u=wt(a,s,o??this.service),d=await xt({headers:{},body:t},this.sha256),l=new this.sha256;l.update(e);const h=ze(await l.digest()),f=[mt,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}=Mt(t),a=new this.sha256(await this.getSigningKey(i,o,s,n));return a.update(Te(e)),ze(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=Pt(e),{longDate:u,shortDate:d}=Mt(t),l=wt(d,a,o??this.service);c.headers[at]=u,s.sessionToken&&(c.headers[lt]=s.sessionToken);const h=await xt(c,this.sha256);!((e,t)=>{e=e.toLowerCase();for(const r of Object.keys(t))if(e===r.toLowerCase())return!0;return!1})(dt,c.headers)&&this.applyChecksum&&(c.headers[dt]=h);const f=St(c,n,r),p=await this.getSignature(u,l,this.getSigningKey(s,a,d,o),this.createCanonicalRequest(c,f,h));return c.headers[st]=`${gt} Credential=${s.accessKeyId}/${l}, SignedHeaders=${Nt(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()===ut)continue;const i=_e(n);t.push(i);const o=e[n];"string"==typeof o?r[i]=`${i}=${_e(o)}`:Array.isArray(o)&&(r[i]=o.slice(0).reduce(((e,t)=>e.concat([`${i}=${_e(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(Te(r));const i=await n.digest();return`${gt}\n${e}\n${t}\n${ze(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 _e(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(Te(i)),ze(await o.digest())}getSigningKey(e,t,r,n){return(async(e,t,r,n,i)=>{const o=`${r}:${n}:${i}:${ze(await kt(e,t.secretAccessKey,t.accessKeyId))}:${t.sessionToken}`;if(o in vt)return vt[o];for(bt.push(o);bt.length>50;)delete vt[bt.shift()];let s=`AWS4${t.secretAccessKey}`;for(const t of[r,n,i,yt])s=await kt(e,s,t);return vt[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 Mt=e=>{const t=(r=e,_t(r).toISOString().replace(/\.\d{3}Z$/,"Z")).replace(/[\-:]/g,"");var r;return{longDate:t,shortDate:t.slice(0,8)}},Nt=e=>Object.keys(e).sort().join(";"),Ft=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,et,rt)),t||(t=e.credentialDefaultProvider?ke(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?ke(e.signer):e.regionInfoProvider?()=>ke(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||It)(c)})):async r=>{const i=(r=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await ke(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||It)(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}},$t=(e,t)=>{const r=[];if(e&&r.push(e),t)for(const e of t)r.push(e);return r},Ut=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,Lt=()=>{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 $t(t.name,t.aliases))s[e]=t;n.push(t)})),t.forEach((e=>{const t={...e,before:[],after:[]};for(const e of $t(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 ${Ut(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)=>Bt[t.step]-Bt[e.step]||Dt[t.priority||"normal"]-Dt[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=$t(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${Ut(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(`"${Ut(n.name,n.aliases)}" middleware with ${n.priority} priority in ${n.step} step cannot be overridden by "${Ut(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=$t(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${Ut(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(`"${Ut(n.name,n.aliases)}" middleware ${n.relation} "${n.toMiddleware}" middleware cannot be overridden by "${Ut(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(Lt()),use:e=>{e.applyToStack(a)},remove:r=>"string"==typeof r?(r=>{let i=!1;const o=e=>{const t=$t(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 $t(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=$t(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(Lt());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 Ut(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},Bt={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},Dt={high:3,normal:2,low:1};class zt{constructor(e){this.config=e,this.middlewareStack=Lt()}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 jt{constructor(){this.middlewareStack=Lt()}static classBuilder(){return new qt}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,[z]:{commandInstance:this,...c},...u},{requestHandler:p}=t;return l.resolve((e=>p.handle(e.request,r||{})),f)}}class qt{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 jt{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 Ht="***SensitiveInformation***",Wt=e=>{switch(e){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${e}"`)}},Kt=Math.ceil(2**127*(2-2**-23)),Vt=e=>{const t=(e=>{if(null!=e){if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&ur.warn(cr(`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)>Kt)throw new TypeError(`Expected 32-bit float, got ${e}`);return t},Qt=e=>{if(null!=e){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw new TypeError(`Expected integer, got ${typeof e}: ${e}`)}},Gt=e=>Zt(e,32),Jt=e=>Zt(e,16),Xt=e=>Zt(e,8),Zt=(e,t)=>{const r=Qt(e);if(void 0!==r&&Yt(r,t)!==r)throw new TypeError(`Expected ${t}-bit integer, got ${e}`);return r},Yt=(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]}},er=(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},tr=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}`)},rr=e=>{if(null!=e){if("string"==typeof e)return e;if(["boolean","number","bigint"].includes(typeof e))return ur.warn(cr(`Expected string, got ${typeof e}: ${e}`)),String(e);throw new TypeError(`Expected string, got ${typeof e}: ${e}`)}},nr=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,ir=e=>{const t=e.match(nr);if(null===t||t[0].length!==e.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(e)},or=e=>Qt("string"==typeof e?ir(e):e),sr=e=>Gt("string"==typeof e?ir(e):e),ar=e=>Jt("string"==typeof e?ir(e):e),cr=e=>String(new TypeError(e).stack||e).split("\n").slice(0,5).filter((e=>!e.includes("stackTraceWarning"))).join("\n"),ur={warn:console.warn},dr=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],lr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function hr(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`${dr[n]}, ${i<10?`0${i}`:`${i}`} ${lr[r]} ${t} ${c}:${u}:${d} GMT`}const fr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),pr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-3339 date-times must be expressed as strings");const t=fr.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=ar(Or(n)),h=Tr(i,"month",1,12),f=Tr(o,"day",1,31),p=br(l,h,f,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u});return"Z"!=d.toUpperCase()&&p.setTime(p.getTime()-Rr(d)),p},gr=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$/),mr=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$/),yr=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})$/),vr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-7231 date-times must be expressed as strings");let t=gr.exec(e);if(t){const[e,r,n,i,o,s,a,c]=t;return br(ar(Or(i)),Sr(n),Tr(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c})}if(t=mr.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return kr(br(wr(i),Sr(n),Tr(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c}))}if(t=yr.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return br(ar(Or(c)),Sr(r),Tr(n.trimLeft(),"day",1,31),{hours:i,minutes:o,seconds:s,fractionalMilliseconds:a})}throw new TypeError("Invalid RFC-7231 date-time value")},br=(e,t,r,n)=>{const i=t-1;return xr(e,i,r),new Date(Date.UTC(e,i,r,Tr(n.hours,"hour",0,23),Tr(n.minutes,"minute",0,59),Tr(n.seconds,"seconds",0,60),Cr(n.fractionalMilliseconds)))},wr=e=>{const t=(new Date).getUTCFullYear(),r=100*Math.floor(t/100)+ar(Or(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,Sr=e=>{const t=lr.indexOf(e);if(t<0)throw new TypeError(`Invalid month: ${e}`);return t+1},Er=[31,28,31,30,31,30,31,31,30,31,30,31],xr=(e,t,r)=>{let n=Er[t];if(1===t&&Ar(e)&&(n=29),r>n)throw new TypeError(`Invalid day for ${lr[t]} in ${e}: ${r}`)},Ar=e=>e%4==0&&(e%100!=0||e%400==0),Tr=(e,t,r,n)=>{const i=(e=>Xt("string"==typeof e?ir(e):e))(Or(e));if(in)throw new TypeError(`${t} must be between ${r} and ${n}, inclusive`);return i},Cr=e=>null==e?0:1e3*(e=>Vt("string"==typeof e?ir(e):e))("0."+e),Rr=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},Or=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},Ir=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"]}),Mr=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{}}},Nr=e=>{const t=[];for(const r in B){const n=B[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}}},Fr=e=>{const t={};return e.checksumAlgorithms().forEach((e=>{t[e.algorithmId()]=e.checksumConstructor()})),t},$r=e=>{let t=e.retryStrategy;return{setRetryStrategy(e){t=e},retryStrategy:()=>t}},Ur=e=>{const t={};return t.retryStrategy=e.retryStrategy(),t},Lr=e=>({...Nr(e),...$r(e)}),Br=e=>({...Fr(e),...Ur(e)}),Dr=e=>Array.isArray(e)?e:[e],zr=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]=zr(e[r]));return e},jr=e=>null!=e,qr=function(){const e=Object.getPrototypeOf(this).constructor,t=new(Function.bind.apply(String,[null,...arguments]));return Object.setPrototypeOf(t,e.prototype),t};qr.prototype=Object.create(String.prototype,{constructor:{value:qr,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(qr,String);class Hr{trace(){}debug(){}info(){}warn(){}error(){}}function Wr(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,Kr(n,i,o);o=t}for(const e of Object.keys(o))Array.isArray(o[e])?Vr(n,null,o,e):n[e]=o[e];return n}const Kr=(e,t,r)=>Wr(e,Object.entries(r).reduce(((e,[r,n])=>(Array.isArray(n)?e[r]=n:e[r]="function"==typeof n?[t,n()]:[t,n],e)),{})),Vr=(e,t,r,n)=>{if(null!==t){let i=r[n];"function"==typeof i&&(i=[,i]);const[o=Qr,s=Gr,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)}},Qr=e=>null!=e,Gr=e=>e;function Jr(e){return(e.includes(",")||e.includes('"'))&&(e=`"${e.replace(/"/g,'\\"')}"`),e}function Xr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Zr={},Yr={};!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 hn("InvalidXml","XML declaration allowed only at the start of the document.",pn(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}}return t}function on(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}Zr.validate=function(e,t){t=Object.assign({},tn,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,!en.isName(o)){let t;return t=0===u.trim().length?"Invalid space after '<'.":"Tag '"+u+"' is an invalid name.",hn("InvalidTag",t,pn(e,s))}const d=cn(e,s);if(!1===d)return hn("InvalidAttr","Attributes for '"+u+"' have open quote.",pn(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=dn(l,t);if(!0!==i)return hn(i.err.code,i.err.msg,pn(e,r+i.err.line));n=!0}else if(c){if(!d.tagClosed)return hn("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",pn(e,s));if(l.trim().length>0)return hn("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",pn(e,a));if(0===r.length)return hn("InvalidTag","Closing tag '"+u+"' has not been opened.",pn(e,a));{const t=r.pop();if(u!==t.tagName){let r=pn(e,t.tagStartPos);return hn("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+u+"'.",pn(e,a))}0==r.length&&(i=!0)}}else{const o=dn(l,t);if(!0!==o)return hn(o.err.code,o.err.msg,pn(e,s-l.length+o.err.line));if(!0===i)return hn("InvalidXml","Multiple possible root nodes found.",pn(e,s));-1!==t.unpairedTags.indexOf(u)||r.push({tagName:u,tagStartPos:a}),n=!0}for(s++;s0)||hn("InvalidXml","Invalid '"+JSON.stringify(r.map((e=>e.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):hn("InvalidXml","Start tag expected.",1)};const sn='"',an="'";function cn(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 un=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function dn(e,t){const r=en.getAllMatches(e,un),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}};mn.buildOptions=function(e){return Object.assign({},yn,e)},mn.defaultOptions=yn;var vn=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 bn=Yr;function wn(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&&Sn(e,t))t+=7,[entityName,val,t]=wn(e,t+1),-1===val.indexOf("&")&&(r[Tn(entityName)]={regx:RegExp(`&${entityName};`,"g"),val:val});else if(i&&En(e,t))t+=8;else if(i&&xn(e,t))t+=8;else if(i&&An(e,t))t+=9;else{if(!kn)throw new Error("Invalid DOCTYPE");o=!0}n++,s=""}if(0!==n)throw new Error("Unclosed DOCTYPE")}return{entities:r,i:t}};const Rn=/^[-+]?0x[a-fA-F0-9]+$/,On=/^([\-\+])?(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 Pn={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};const _n=Yr,In=vn,Mn=Cn,Nn=function(e,t={}){if(t=Object.assign({},Pn,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&&Rn.test(r))return Number.parseInt(r,16);{const n=On.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 Fn(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 Qn(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?Qn(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function Un(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 Ln=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function Bn(e,t,r){if(!this.options.ignoreAttributes&&"string"==typeof e){const r=_n.getAllMatches(e,Ln),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=Kn(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 In(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=Wn(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=Mn(e,o);this.docTypeEntities=t.entities,o=t.i}else if("!["===e.substr(o+1,2)){const t=Wn(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=Kn(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 In(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 In(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 In(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 zn(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 jn=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 qn(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 Hn(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 Wn(e,t,r,n){const i=e.indexOf(t,r);if(-1===i)throw new Error(n);return i+t.length-1}function Kn(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=Wn(e,"?>",r+1,"StopNode is not closed.")}else if("!--"===e.substr(r+1,3)){r=Wn(e,"--\x3e",r+3,"StopNode is not closed.")}else if("!["===e.substr(r+1,2)){r=Wn(e,"]]>",r,"StopNode is not closed.")-2}else{const n=Kn(e,r,">");if(n){(n&&n.tagName)===t&&"/"!==n.tagExp[n.tagExp.length-1]&&i++,r=n.closeIndex}}}function Qn(e,t,r){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&Nn(e,r)}return _n.isExist(e)?e:""}var Gn=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=Fn,this.parseXml=Dn,this.parseTextData=$n,this.resolveNameSpace=Un,this.buildAttributesMap=Bn,this.isItStopNode=Hn,this.replaceEntitiesValue=jn,this.readStopNodeData=Vn,this.saveTextToParentTag=qn,this.addChild=zn}},Jn={};function Xn(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 Zn(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=ci(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}${ci(a[":@"],t)}`,h=si(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 ai(e){const t=Object.keys(e);for(let r=0;r0&&t.processEntities)for(let r=0;r0&&(r="\n"),si(e,t,"",r)},hi={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 fi(e){this.options=Object.assign({},hi,e),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=mi),this.processTextOrObjNode=pi,this.options.format?(this.indentate=gi,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function pi(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 gi(e){return this.options.indentBy.repeat(e)}function mi(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}fi.prototype.build=function(e){return this.options.preserveOrder?li(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0).val)},fi.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}},fi.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)=>Ge(e,t).then((e=>t.utf8Encoder(e))))(e,t).then((e=>{if(e.length){const t=new yi.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]),zr(o)}return{}})),bi=async(e,t)=>{const r=await vi(e,t);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r},wi=[X.CRC32,X.CRC32C,X.SHA1,X.SHA256],ki=[X.SHA256,X.SHA1,X.CRC32,X.CRC32C],Si=e=>e===X.MD5?"content-md5":`x-amz-checksum-${e.toLowerCase()}`,Ei=e=>void 0!==e&&"string"!=typeof e&&!ArrayBuffer.isView(e)&&!Et(e);function xi(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 Ai(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 Ci(e){return e instanceof Uint8Array?e:"string"==typeof e?Ti(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}function Ri(e){return"string"==typeof e?0===e.length:0===e.byteLength}function Oi(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}function Pi(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^Mi[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}(),Mi=Pi([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 Ni(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 Fi(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^Li[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}(),Li=Pi([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 Bi=(e,t)=>({[X.MD5]:t.md5,[X.CRC32]:$i,[X.CRC32C]:_i,[X.SHA1]:t.sha1,[X.SHA256]:t.sha256}[e]),Di=(e,t)=>{const r=new e;return r.update(Te(t||"")),r.digest()},zi={name:"flexibleChecksumsMiddleware",step:"build",tags:["BODY_CHECKSUM"],override:!0},ji=(e,t)=>(r,n)=>async i=>{if(!H.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?ee:Y;if(!r||!e[r])return t?i:void 0;const o=e[r];if(!wi.includes(o))throw new Error(`The checksum algorithm "${o}" is not supported by the client. Select one of ${wi}.`);return o})(s,{requestChecksumRequired:l,requestAlgorithmMember:h},!!n.isS3ExpressBucket);let p=a,g=c;if(f){switch(f){case X.CRC32:re(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32","U");break;case X.CRC32C:re(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32C","V");break;case X.SHA1:re(n,"FLEXIBLE_CHECKSUMS_REQ_SHA1","X");break;case X.SHA256:re(n,"FLEXIBLE_CHECKSUMS_REQ_SHA256","Y")}const t=Si(f),r=Bi(f,e);if(Ei(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 Di(r,a);g={...c,[t]:u(e)}}}return await r({...i,request:{...o,headers:g,body:p}})},qi=(e=[])=>{const t=[];for(const r of ki)e.includes(r)&&wi.includes(r)&&t.push(r);return t};function Hi(e){return new Blob([e]).stream()}const Wi=async(e,{checksumAlgorithmFn:t,base64Encoder:r})=>r(await Di(t,e)),Ki={name:"flexibleChecksumsResponseMiddleware",toMiddleware:"deserializerMiddleware",relation:"after",tags:["BODY_CHECKSUM"],override:!0},Vi=(e,t)=>(r,n)=>async i=>{if(!H.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&&qi(d).every((e=>{const t=Si(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=Ei(a.body);i&&(c=await e.streamCollector(a.body),a.body=Hi(c)),await(async(e,{config:t,responseAlgorithms:r})=>{const n=qi(r),{body:i,headers:o}=e;for(const r of n){const n=Si(r),s=o[n];if(s){const o=Bi(r,t),{base64Encoder:a}=t;if(Ei(i))return void(e.body=Qe({expectedChecksum:s,checksumSourceLocation:n,checksum:new o,source:i,base64Encoder:a}));const c=await Wi(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=Hi(c))}return s},Qi=(e,t)=>({applyToStack:r=>{r.add(ji(e,t),zi),r.addRelativeTo(Vi(e,t),Ki)}});const Gi={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},Ji=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{if(!H.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),Gi)}}),Xi={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},Zi="X-Amzn-Trace-Id",Yi={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},eo=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{const{request:n}=r;if(!H.isInstance(n)||"node"!==e.runtime||n.headers.hasOwnProperty(Zi))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[Zi]=o),t({...r,request:n})})(e),Yi)}});const to={step:"finalizeRequest",tags:["CHECK_CONTENT_LENGTH_HEADER"],name:"getCheckContentLengthHeaderPlugin",override:!0},ro=e=>({applyToStack:e=>{e.add(((e,t)=>async r=>{const{request:n}=r;if(H.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 Hr?console.warn(e):t.logger.warn(e)}return e({...r})}),to)}}),no={tags:["REGION_REDIRECT","S3"],name:"regionRedirectEndpointMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};const io={step:"initialize",tags:["REGION_REDIRECT","S3"],name:"regionRedirectMiddleware",override:!0},oo=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),io),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),no)}}),so={tags:["S3"],name:"s3ExpiresMiddleware",override:!0,relation:"after",toMiddleware:"deserializerMiddleware"},ao=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{const n=await e(r),{response:i}=n;if(W.isInstance(i)&&i.headers.expires){i.headers.expiresstring=i.headers.expires;try{vr(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}),so)}});class co{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+co.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 uo(Promise.resolve(e)))}))),e})):n.set(r,new uo(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 ho;lo.REFRESH_WINDOW_MS=6e4,function(e){e.ENV="env",e.CONFIG="shared config entry"}(ho||(ho={}));const fo="X-Amz-S3session-Token",po=fo.toLowerCase();class go extends It{async signWithCredentials(e,t,r){const n=mo(t);e.headers[po]=t.sessionToken;return yo(this,n),this.signRequest(e,r??{})}async presignWithCredentials(e,t,r){const n=mo(t);delete e.headers[po],e.headers[fo]=t.sessionToken,e.query=e.query??{},e.query[fo]=t.sessionToken;return yo(this,n),this.presign(e,r)}}function mo(e){return{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,expiration:e.expiration}}function yo(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 vo={name:"s3ExpressMiddleware",step:"build",tags:["S3","S3_EXPRESS"],override:!0},bo=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)&&(re(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,H.isInstance(n.request)&&i.sessionToken&&(n.request.headers[po]=i.sessionToken)}}}return t(n)})(e),vo)}}),wo=e=>e=>{throw e},ko=(e,t)=>{},So=e=>(t,r)=>async n=>{if(!H.isInstance(n.request))return t(n);const i=de(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||wo)(o));return(a.successHandler||ko)(u.response,o),u},Eo={CopyObjectCommand:!0,UploadPartCopyCommand:!0,CompleteMultipartUploadCommand:!0},xo=e=>(t,r)=>async n=>{const i=await t(n),{response:o}=i;if(!W.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 Ao(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&&Eo[r.commandName]){const e=new Error("S3 aborted request");throw e.name="InternalError",e}return l&&l.endsWith("")&&(o.statusCode=400),i},Ao=(e=new Uint8Array,t)=>e instanceof Uint8Array?Promise.resolve(e):t.streamCollector(e)||Promise.resolve(new Uint8Array),To={relation:"after",toMiddleware:"deserializerMiddleware",tags:["THROW_200_EXCEPTIONS","S3"],name:"throw200ExceptionsMiddleware",override:!0},Co=e=>({applyToStack:t=>{t.addRelativeTo(xo(e),To)}});const Ro={name:"bucketEndpointMiddleware",override:!0,relation:"after",toMiddleware:"endpointV2Middleware"};const Oo={step:"initialize",tags:["VALIDATE_BUCKET_NAME"],name:"validateBucketNameMiddleware",override:!0},Po=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),Oo),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),Ro)}});const _o=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}$"),Io=e=>_o.test(e)||e.startsWith("[")&&e.endsWith("]"),Mo=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),No=(e,t=!1)=>{if(!t)return Mo.test(e);const r=e.split(".");for(const e of r)if(!No(e))return!1;return!0},Fo={},$o="endpoints";function Uo(e){return"object"!=typeof e||null==e?e:"ref"in e?`$${Uo(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(Uo).join(", ")})`:JSON.stringify(e,null,2)}class Lo extends Error{constructor(e){super(e),this.name="EndpointError"}}const Bo=(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 Lo(`Path: '${e}' does not end with ']'`);const i=n.slice(t+1,-1);if(Number.isNaN(parseInt(i)))throw new Lo(`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 Lo(`Index '${n}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(r)?r[parseInt(n)]:r[n]}),e),Do={[L.HTTP]:80,[L.HTTPS]:443},zo={booleanEquals:(e,t)=>e===t,getAttr:Bo,isSet:e=>null!=e,isValidHostLabel:No,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(L).includes(c))return null;const u=Io(i);return{scheme:c,authority:`${n}${r.includes(`${n}:${Do[c]}`)||"string"==typeof e&&e.includes(`${n}:${Do[c]}`)?`:${Do[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()}`))},jo=(e,t)=>{const r=[],n={...t.endpointParams,...t.referenceRecord};let i=0;for(;i{if("string"==typeof e)return jo(e,r);if(e.fn)return Ho(e,r);if(e.ref)return(({ref:e},t)=>({...t.endpointParams,...t.referenceRecord}[e]))(e,r);throw new Lo(`'${t}': ${String(e)} is not a string, function or reference.`)},Ho=({fn:e,argv:t},r)=>{const n=t.map((e=>["boolean","number"].includes(typeof e)?e:qo(e,"arg",r))),i=e.split(".");return i[0]in Fo&&null!=i[1]?Fo[i[0]][i[1]](...n):zo[e](...n)},Wo=({assign:e,...t},r)=>{if(e&&e in r.referenceRecord)throw new Lo(`'${e}' is already defined in Reference Record.`);const n=Ho(t,r);return r.logger?.debug?.(`${$o} evaluateCondition: ${Uo(t)} = ${Uo(n)}`),{result:""===n||!!n,...null!=e&&{toAssign:{name:e,value:n}}}},Ko=(e=[],t)=>{const r={};for(const n of e){const{result:e,toAssign:i}=Wo(n,{...t,referenceRecord:{...t.referenceRecord,...r}});if(!e)return{result:e};i&&(r[i.name]=i.value,t.logger?.debug?.(`${$o} assign: ${i.name} := ${Uo(i.value)}`))}return{result:!0,referenceRecord:r}},Vo=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:n.map((e=>{const n=qo(e,"Header value entry",t);if("string"!=typeof n)throw new Lo(`Header '${r}' value '${n}' is not a string`);return n}))})),{}),Qo=(e,t)=>{if(Array.isArray(e))return e.map((e=>Qo(e,t)));switch(typeof e){case"string":return jo(e,t);case"object":if(null===e)throw new Lo(`Unexpected endpoint property: ${e}`);return Go(e,t);case"boolean":return e;default:throw new Lo("Unexpected endpoint property type: "+typeof e)}},Go=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:Qo(n,t)})),{}),Jo=(e,t)=>{const r=qo(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 Lo("Endpoint URL must be a string, got "+typeof r)},Xo=(e,t)=>{const{conditions:r,endpoint:n}=e,{result:i,referenceRecord:o}=Ko(r,t);if(!i)return;const s={...t,referenceRecord:{...t.referenceRecord,...o}},{url:a,properties:c,headers:u}=n;return t.logger?.debug?.(`${$o} Resolving endpoint from template: ${Uo(n)}`),{...null!=u&&{headers:Vo(u,s)},...null!=c&&{properties:Go(c,s)},url:Jo(a,s)}},Zo=(e,t)=>{const{conditions:r,error:n}=e,{result:i,referenceRecord:o}=Ko(r,t);if(i)throw new Lo(qo(n,"Error",{...t,referenceRecord:{...t.referenceRecord,...o}}))},Yo=(e,t)=>{const{conditions:r,rules:n}=e,{result:i,referenceRecord:o}=Ko(r,t);if(i)return es(n,{...t,referenceRecord:{...t.referenceRecord,...o}})},es=(e,t)=>{for(const r of e)if("endpoint"===r.type){const e=Xo(r,t);if(e)return e}else if("error"===r.type)Zo(r,t);else{if("tree"!==r.type)throw new Lo(`Unknown endpoint rule: ${r}`);{const e=Yo(r,t);if(e)return e}}throw new Lo("Rules evaluation failed")},ts=(e,t=!1)=>{if(t){for(const t of e.split("."))if(!ts(t))return!1;return!0}return!!No(e)&&(!(e.length<3||e.length>63)&&(e===e.toLowerCase()&&!Io(e)))};let rs={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 ns={isVirtualHostableS3Bucket:ts,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}=rs;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}}};Fo.aws=ns;const is=/\d{12}\.ddb/;const os="user-agent",ss="x-amz-user-agent",as=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g,cs=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;const us=e=>(t,r)=>async n=>{const{request:i}=n;if(!H.isInstance(i))return t(n);const{headers:o}=i,s=r?.userAgent?.map(ds)||[],a=(await e.defaultUserAgentProvider()).map(ds);await async function(e,t,r){const n=r.request;if("rpc-v2-cbor"===n?.headers?.["smithy-protocol"]&&re(e,"PROTOCOL_RPC_V2_CBOR","M"),"function"==typeof t.retryStrategy){const r=await t.retryStrategy();"function"==typeof r.acquireInitialRetryToken?r.constructor?.name?.includes("Adaptive")?re(e,"RETRY_MODE_ADAPTIVE","F"):re(e,"RETRY_MODE_STANDARD","E"):re(e,"RETRY_MODE_LEGACY","D")}if("function"==typeof t.accountIdEndpointMode){const r=e.endpointV2;switch(String(r?.url?.hostname).match(is)&&re(e,"ACCOUNT_ID_ENDPOINT","O"),await(t.accountIdEndpointMode?.())){case"disabled":re(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":re(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":re(e,"ACCOUNT_ID_MODE_REQUIRED","R")}}const i=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const t=i;t.accountId&&re(e,"RESOLVED_ACCOUNT_ID","T");for(const[r,n]of Object.entries(t.$source??{}))re(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(ds)||[],d=await e.userAgentAppId();d&&a.push(ds([`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[ss]=o[ss]?`${o[os]} ${h}`:h),o[os]=l):o[ss]=l,t({...n,request:i})},ds=e=>{const t=e[0].split("/").map((e=>e.replace(as,"-"))).join("/"),r=e[1]?.replace(cs,"-"),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}`}}),"")},ls={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},hs=e=>"string"==typeof e&&(e.startsWith("fips-")||e.endsWith("-fips")),fs=e=>hs(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,ps="content-length";const gs={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},ms=e=>({applyToStack:t=>{var r;t.add((r=e.bodyLengthChecker,e=>async t=>{const n=t.request;if(H.isInstance(n)){const{body:e,headers:t}=n;if(e&&-1===Object.keys(t).map((e=>e.toLowerCase())).indexOf(ps))try{const t=r(e);n.headers={...n.headers,[ps]:String(t)}}catch(e){}}return e({...t,request:n})}),gs)}}),ys=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,vs=/(\d+\.){3}\d+/,bs=/\.\./,ws=e=>ys.test(e)&&!vs.test(e)&&!bs.test(e),ks=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},Ss=(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},Es=async e=>{};const xs=e=>{if("string"==typeof e)return xs(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}},As=e=>"object"==typeof e?"url"in e?xs(e.url):e:xs(e),Ts=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 Ss(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("?"))),ks(t)){if(!0===e.ForcePathStyle)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!ws(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},Cs=({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 Es(r.serviceId),e&&(r.endpoint=()=>Promise.resolve(As(e)))}const i=await Ts(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=de(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})},Rs={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:ge.name},Os=(e,t)=>({applyToStack:r=>{r.addRelativeTo(Cs({config:e,instructions:t}),Rs)}});var Ps;!function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"}(Ps||(Ps={}));const _s=Ps.STANDARD,Is=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Ms=["TimeoutError","RequestTimeout","RequestTimeoutException"],Ns=[500,502,503,504],Fs=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],$s=e=>429===e.$metadata?.httpStatusCode||Is.includes(e.name)||1==e.$retryable?.throttling,Us=e=>(e=>e.$metadata?.clockSkewCorrected)(e)||Ms.includes(e.name)||Fs.includes(e?.code||"")||Ns.includes(e.$metadata?.httpStatusCode||0);class Ls{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=>Ls.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(),$s(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))}}Ls.setTimeoutFn=setTimeout;const Bs=({retryDelay:e,retryCount:t,retryCost:r})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(2e4,e),getRetryCost:()=>r});class Ds{constructor(e){this.maxAttempts=e,this.mode=Ps.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 Bs({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,Bs({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 zs{constructor(e,t){this.maxAttemptsProvider=e,this.mode=Ps.ADAPTIVE;const{rateLimiter:r}=t??{};this.rateLimiter=r??new Ls,this.standardRetryStrategy=new Ds(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 js;const qs=new Uint8Array(16);function Hs(){if(!js&&(js="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!js))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return js(qs)}const Ws=[];for(let e=0;e<256;++e)Ws.push((e+256).toString(16).slice(1));var Ks={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Vs(e,t,r){if(Ks.randomUUID&&!t&&!e)return Ks.randomUUID();const n=(e=e||{}).random||(e.rng||Hs)();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 Ws[e[t+0]]+Ws[e[t+1]]+Ws[e[t+2]]+Ws[e[t+3]]+"-"+Ws[e[t+4]]+Ws[e[t+5]]+"-"+Ws[e[t+6]]+Ws[e[t+7]]+"-"+Ws[e[t+8]]+Ws[e[t+9]]+"-"+Ws[e[t+10]]+Ws[e[t+11]]+Ws[e[t+12]]+Ws[e[t+13]]+Ws[e[t+14]]+Ws[e[t+15]]}(n)}const Qs=e=>e?.body instanceof ReadableStream,Gs=e=>void 0!==e.acquireInitialRetryToken&&void 0!==e.refreshRetryTokenForRetry&&void 0!==e.recordSuccess,Js=e=>{const t={error:e,errorType:Xs(e)},r=ea(e.$response);return r&&(t.retryAfterHint=r),t},Xs=e=>$s(e)?"THROTTLING":Us(e)?"TRANSIENT":(e=>{if(void 0!==e.$metadata?.httpStatusCode){const t=e.$metadata.httpStatusCode;return 500<=t&&t<=599&&!Us(e)}return!1})(e)?"SERVER_ERROR":"CLIENT_ERROR",Zs={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},Ys=e=>({applyToStack:t=>{t.add((e=>(t,r)=>async n=>{let i=await e.retryStrategy();const o=await e.maxAttempts();if(!Gs(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=H.isInstance(d);for(l&&(d.headers["amz-sdk-invocation-id"]=Vs());;)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=Js(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&&Qs(d))throw(r.logger instanceof Hr?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),Zs)}}),ea=e=>{if(!W.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)},ta=null;class ra{constructor(e){this.sigv4Signer=new go(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=ta,"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 na="required",ia="type",oa="conditions",sa="fn",aa="argv",ca="ref",ua="assign",da="url",la="properties",ha="backend",fa="authSchemes",pa="disableDoubleEncoding",ga="signingName",ma="signingRegion",ya="headers",va="signingRegionSet",ba=!0,wa="isSet",ka="booleanEquals",Sa="error",Ea="aws.partition",xa="stringEquals",Aa="getAttr",Ta="name",Ca="substring",Ra="bucketSuffix",Oa="parseURL",Pa="{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",_a="endpoint",Ia="tree",Ma="aws.isVirtualHostableS3Bucket",Na="{url#scheme}://{Bucket}.{url#authority}{url#path}",Fa="not",$a="{url#scheme}://{url#authority}{url#path}",Ua="hardwareType",La="regionPrefix",Ba="bucketAliasSuffix",Da="outpostId",za="isValidHostLabel",ja="sigv4a",qa="s3-outposts",Ha="s3",Wa="{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}",Ka="https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}",Va="https://{Bucket}.s3.{partitionResult#dnsSuffix}",Qa="aws.parseArn",Ga="bucketArn",Ja="arnType",Xa="s3-object-lambda",Za="accesspoint",Ya="accessPointName",ec="{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}",tc="mrapPartition",rc="outpostType",nc="arnPrefix",ic="{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}",oc="https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",sc="https://s3.{partitionResult#dnsSuffix}",ac={[na]:!1,[ia]:"String"},cc={[na]:!0,default:!1,[ia]:"Boolean"},uc={[na]:!1,[ia]:"Boolean"},dc={[sa]:ka,[aa]:[{[ca]:"Accelerate"},!0]},lc={[sa]:ka,[aa]:[{[ca]:"UseFIPS"},!0]},hc={[sa]:ka,[aa]:[{[ca]:"UseDualStack"},!0]},fc={[sa]:wa,[aa]:[{[ca]:"Endpoint"}]},pc={[sa]:Ea,[aa]:[{[ca]:"Region"}],[ua]:"partitionResult"},gc={[sa]:xa,[aa]:[{[sa]:Aa,[aa]:[{[ca]:"partitionResult"},Ta]},"aws-cn"]},mc={[sa]:wa,[aa]:[{[ca]:"Bucket"}]},yc={[ca]:"Bucket"},vc={[sa]:Oa,[aa]:[{[ca]:"Endpoint"}],[ua]:"url"},bc={[sa]:ka,[aa]:[{[sa]:Aa,[aa]:[{[ca]:"url"},"isIp"]},!0]},wc={[ca]:"url"},kc={[sa]:"uriEncode",[aa]:[yc],[ua]:"uri_encoded_bucket"},Sc={[ha]:"S3Express",[fa]:[{[pa]:!0,[Ta]:"sigv4",[ga]:"s3express",[ma]:"{Region}"}]},Ec={},xc={[sa]:Ma,[aa]:[yc,!1]},Ac={[Sa]:"S3Express bucket name is not a valid virtual hostable name.",[ia]:Sa},Tc={[ha]:"S3Express",[fa]:[{[pa]:!0,[Ta]:"sigv4-s3express",[ga]:"s3express",[ma]:"{Region}"}]},Cc={[sa]:wa,[aa]:[{[ca]:"UseS3ExpressControlEndpoint"}]},Rc={[sa]:ka,[aa]:[{[ca]:"UseS3ExpressControlEndpoint"},!0]},Oc={[sa]:Fa,[aa]:[fc]},Pc={[Sa]:"Unrecognized S3Express bucket name format.",[ia]:Sa},_c={[sa]:Fa,[aa]:[mc]},Ic={[ca]:Ua},Mc={[oa]:[Oc],[Sa]:"Expected a endpoint to be specified but no endpoint was found",[ia]:Sa},Nc={[fa]:[{[pa]:!0,[Ta]:ja,[ga]:qa,[va]:["*"]},{[pa]:!0,[Ta]:"sigv4",[ga]:qa,[ma]:"{Region}"}]},Fc={[sa]:ka,[aa]:[{[ca]:"ForcePathStyle"},!1]},$c={[ca]:"ForcePathStyle"},Uc={[sa]:ka,[aa]:[{[ca]:"Accelerate"},!1]},Lc={[sa]:xa,[aa]:[{[ca]:"Region"},"aws-global"]},Bc={[fa]:[{[pa]:!0,[Ta]:"sigv4",[ga]:Ha,[ma]:"us-east-1"}]},Dc={[sa]:Fa,[aa]:[Lc]},zc={[sa]:ka,[aa]:[{[ca]:"UseGlobalEndpoint"},!0]},jc={[da]:"https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[la]:{[fa]:[{[pa]:!0,[Ta]:"sigv4",[ga]:Ha,[ma]:"{Region}"}]},[ya]:{}},qc={[fa]:[{[pa]:!0,[Ta]:"sigv4",[ga]:Ha,[ma]:"{Region}"}]},Hc={[sa]:ka,[aa]:[{[ca]:"UseGlobalEndpoint"},!1]},Wc={[sa]:ka,[aa]:[{[ca]:"UseDualStack"},!1]},Kc={[da]:"https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",[la]:qc,[ya]:{}},Vc={[sa]:ka,[aa]:[{[ca]:"UseFIPS"},!1]},Qc={[da]:"https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",[la]:qc,[ya]:{}},Gc={[da]:"https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[la]:qc,[ya]:{}},Jc={[sa]:ka,[aa]:[{[sa]:Aa,[aa]:[wc,"isIp"]},!1]},Xc={[da]:Wa,[la]:qc,[ya]:{}},Zc={[da]:Na,[la]:qc,[ya]:{}},Yc={[_a]:Zc,[ia]:_a},eu={[da]:Ka,[la]:qc,[ya]:{}},tu={[da]:"https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",[la]:qc,[ya]:{}},ru={[Sa]:"Invalid region: region was not a valid DNS name.",[ia]:Sa},nu={[ca]:Ga},iu={[ca]:Ja},ou={[sa]:Aa,[aa]:[nu,"service"]},su={[ca]:Ya},au={[oa]:[hc],[Sa]:"S3 Object Lambda does not support Dual-stack",[ia]:Sa},cu={[oa]:[dc],[Sa]:"S3 Object Lambda does not support S3 Accelerate",[ia]:Sa},uu={[oa]:[{[sa]:wa,[aa]:[{[ca]:"DisableAccessPoints"}]},{[sa]:ka,[aa]:[{[ca]:"DisableAccessPoints"},!0]}],[Sa]:"Access points are not supported for this operation",[ia]:Sa},du={[oa]:[{[sa]:wa,[aa]:[{[ca]:"UseArnRegion"}]},{[sa]:ka,[aa]:[{[ca]:"UseArnRegion"},!1]},{[sa]:Fa,[aa]:[{[sa]:xa,[aa]:[{[sa]:Aa,[aa]:[nu,"region"]},"{Region}"]}]}],[Sa]:"Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",[ia]:Sa},lu={[sa]:Aa,[aa]:[{[ca]:"bucketPartition"},Ta]},hu={[sa]:Aa,[aa]:[nu,"accountId"]},fu={[fa]:[{[pa]:!0,[Ta]:"sigv4",[ga]:Xa,[ma]:"{bucketArn#region}"}]},pu={[Sa]:"Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",[ia]:Sa},gu={[Sa]:"Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",[ia]:Sa},mu={[Sa]:"Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",[ia]:Sa},yu={[Sa]:"Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",[ia]:Sa},vu={[Sa]:"Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",[ia]:Sa},bu={[Sa]:"Invalid ARN: Expected a resource of the format `accesspoint:` but no name was provided",[ia]:Sa},wu={[fa]:[{[pa]:!0,[Ta]:"sigv4",[ga]:Ha,[ma]:"{bucketArn#region}"}]},ku={[fa]:[{[pa]:!0,[Ta]:ja,[ga]:qa,[va]:["*"]},{[pa]:!0,[Ta]:"sigv4",[ga]:qa,[ma]:"{bucketArn#region}"}]},Su={[sa]:Qa,[aa]:[yc]},Eu={[da]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[la]:qc,[ya]:{}},xu={[da]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[la]:qc,[ya]:{}},Au={[da]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[la]:qc,[ya]:{}},Tu={[da]:ic,[la]:qc,[ya]:{}},Cu={[da]:"https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[la]:qc,[ya]:{}},Ru={[ca]:"UseObjectLambdaEndpoint"},Ou={[fa]:[{[pa]:!0,[Ta]:"sigv4",[ga]:Xa,[ma]:"{Region}"}]},Pu={[da]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[la]:qc,[ya]:{}},_u={[da]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}",[la]:qc,[ya]:{}},Iu={[da]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[la]:qc,[ya]:{}},Mu={[da]:$a,[la]:qc,[ya]:{}},Nu={[da]:"https://s3.{Region}.{partitionResult#dnsSuffix}",[la]:qc,[ya]:{}},Fu=[{[ca]:"Region"}],$u=[{[ca]:"Endpoint"}],Uu=[yc],Lu=[hc],Bu=[dc],Du=[fc,vc],zu=[{[sa]:wa,[aa]:[{[ca]:"DisableS3ExpressSessionAuth"}]},{[sa]:ka,[aa]:[{[ca]:"DisableS3ExpressSessionAuth"},!0]}],ju=[bc],qu=[kc],Hu=[xc],Wu=[lc],Ku=[{[sa]:Ca,[aa]:[yc,6,14,!0],[ua]:"s3expressAvailabilityZoneId"},{[sa]:Ca,[aa]:[yc,14,16,!0],[ua]:"s3expressAvailabilityZoneDelim"},{[sa]:xa,[aa]:[{[ca]:"s3expressAvailabilityZoneDelim"},"--"]}],Vu=[{[oa]:[lc],[_a]:{[da]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[la]:Sc,[ya]:{}},[ia]:_a},{[_a]:{[da]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[la]:Sc,[ya]:{}},[ia]:_a}],Qu=[{[sa]:Ca,[aa]:[yc,6,15,!0],[ua]:"s3expressAvailabilityZoneId"},{[sa]:Ca,[aa]:[yc,15,17,!0],[ua]:"s3expressAvailabilityZoneDelim"},{[sa]:xa,[aa]:[{[ca]:"s3expressAvailabilityZoneDelim"},"--"]}],Gu=[{[oa]:[lc],[_a]:{[da]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[la]:Tc,[ya]:{}},[ia]:_a},{[_a]:{[da]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[la]:Tc,[ya]:{}},[ia]:_a}],Ju=[mc],Xu=[{[sa]:za,[aa]:[{[ca]:Da},!1]}],Zu=[{[sa]:xa,[aa]:[{[ca]:La},"beta"]}],Yu=[pc],ed=[{[sa]:za,[aa]:[{[ca]:"Region"},!1]}],td=[{[sa]:xa,[aa]:[{[ca]:"Region"},"us-east-1"]}],rd=[{[sa]:xa,[aa]:[iu,Za]}],nd=[{[sa]:Aa,[aa]:[nu,"resourceId[1]"],[ua]:Ya},{[sa]:Fa,[aa]:[{[sa]:xa,[aa]:[su,""]}]}],id=[nu,"resourceId[1]"],od=[{[sa]:Fa,[aa]:[{[sa]:xa,[aa]:[{[sa]:Aa,[aa]:[nu,"region"]},""]}]}],sd=[{[sa]:Fa,[aa]:[{[sa]:wa,[aa]:[{[sa]:Aa,[aa]:[nu,"resourceId[2]"]}]}]}],ad=[nu,"resourceId[2]"],cd=[{[sa]:Ea,[aa]:[{[sa]:Aa,[aa]:[nu,"region"]}],[ua]:"bucketPartition"}],ud=[{[sa]:xa,[aa]:[lu,{[sa]:Aa,[aa]:[{[ca]:"partitionResult"},Ta]}]}],dd=[{[sa]:za,[aa]:[{[sa]:Aa,[aa]:[nu,"region"]},!0]}],ld=[{[sa]:za,[aa]:[hu,!1]}],hd=[{[sa]:za,[aa]:[su,!1]}],fd=[{[sa]:za,[aa]:[{[ca]:"Region"},!0]}],pd={version:"1.0",parameters:{Bucket:ac,Region:ac,UseFIPS:cc,UseDualStack:cc,Endpoint:ac,ForcePathStyle:cc,Accelerate:cc,UseGlobalEndpoint:cc,UseObjectLambdaEndpoint:uc,Key:ac,Prefix:ac,CopySource:ac,DisableAccessPoints:uc,DisableMultiRegionAccessPoints:cc,UseArnRegion:uc,UseS3ExpressControlEndpoint:uc,DisableS3ExpressSessionAuth:uc},rules:[{[oa]:[{[sa]:wa,[aa]:Fu}],rules:[{[oa]:[dc,lc],error:"Accelerate cannot be used with FIPS",[ia]:Sa},{[oa]:[hc,fc],error:"Cannot set dual-stack in combination with a custom endpoint.",[ia]:Sa},{[oa]:[fc,lc],error:"A custom endpoint cannot be combined with FIPS",[ia]:Sa},{[oa]:[fc,dc],error:"A custom endpoint cannot be combined with S3 Accelerate",[ia]:Sa},{[oa]:[lc,pc,gc],error:"Partition does not support FIPS",[ia]:Sa},{[oa]:[mc,{[sa]:Ca,[aa]:[yc,0,6,ba],[ua]:Ra},{[sa]:xa,[aa]:[{[ca]:Ra},"--x-s3"]}],rules:[{[oa]:Lu,error:"S3Express does not support Dual-stack.",[ia]:Sa},{[oa]:Bu,error:"S3Express does not support S3 Accelerate.",[ia]:Sa},{[oa]:Du,rules:[{[oa]:zu,rules:[{[oa]:ju,rules:[{[oa]:qu,rules:[{endpoint:{[da]:Pa,[la]:Sc,[ya]:Ec},[ia]:_a}],[ia]:Ia}],[ia]:Ia},{[oa]:Hu,rules:[{endpoint:{[da]:Na,[la]:Sc,[ya]:Ec},[ia]:_a}],[ia]:Ia},Ac],[ia]:Ia},{[oa]:ju,rules:[{[oa]:qu,rules:[{endpoint:{[da]:Pa,[la]:Tc,[ya]:Ec},[ia]:_a}],[ia]:Ia}],[ia]:Ia},{[oa]:Hu,rules:[{endpoint:{[da]:Na,[la]:Tc,[ya]:Ec},[ia]:_a}],[ia]:Ia},Ac],[ia]:Ia},{[oa]:[Cc,Rc],rules:[{[oa]:[kc,Oc],rules:[{[oa]:Wu,endpoint:{[da]:"https://s3express-control-fips.{Region}.amazonaws.com/{uri_encoded_bucket}",[la]:Sc,[ya]:Ec},[ia]:_a},{endpoint:{[da]:"https://s3express-control.{Region}.amazonaws.com/{uri_encoded_bucket}",[la]:Sc,[ya]:Ec},[ia]:_a}],[ia]:Ia}],[ia]:Ia},{[oa]:Hu,rules:[{[oa]:zu,rules:[{[oa]:Ku,rules:Vu,[ia]:Ia},{[oa]:Qu,rules:Vu,[ia]:Ia},Pc],[ia]:Ia},{[oa]:Ku,rules:Gu,[ia]:Ia},{[oa]:Qu,rules:Gu,[ia]:Ia},Pc],[ia]:Ia},Ac],[ia]:Ia},{[oa]:[_c,Cc,Rc],rules:[{[oa]:Du,endpoint:{[da]:$a,[la]:Sc,[ya]:Ec},[ia]:_a},{[oa]:Wu,endpoint:{[da]:"https://s3express-control-fips.{Region}.amazonaws.com",[la]:Sc,[ya]:Ec},[ia]:_a},{endpoint:{[da]:"https://s3express-control.{Region}.amazonaws.com",[la]:Sc,[ya]:Ec},[ia]:_a}],[ia]:Ia},{[oa]:[mc,{[sa]:Ca,[aa]:[yc,49,50,ba],[ua]:Ua},{[sa]:Ca,[aa]:[yc,8,12,ba],[ua]:La},{[sa]:Ca,[aa]:[yc,0,7,ba],[ua]:Ba},{[sa]:Ca,[aa]:[yc,32,49,ba],[ua]:Da},{[sa]:Ea,[aa]:Fu,[ua]:"regionPartition"},{[sa]:xa,[aa]:[{[ca]:Ba},"--op-s3"]}],rules:[{[oa]:Xu,rules:[{[oa]:[{[sa]:xa,[aa]:[Ic,"e"]}],rules:[{[oa]:Zu,rules:[Mc,{[oa]:Du,endpoint:{[da]:"https://{Bucket}.ec2.{url#authority}",[la]:Nc,[ya]:Ec},[ia]:_a}],[ia]:Ia},{endpoint:{[da]:"https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[la]:Nc,[ya]:Ec},[ia]:_a}],[ia]:Ia},{[oa]:[{[sa]:xa,[aa]:[Ic,"o"]}],rules:[{[oa]:Zu,rules:[Mc,{[oa]:Du,endpoint:{[da]:"https://{Bucket}.op-{outpostId}.{url#authority}",[la]:Nc,[ya]:Ec},[ia]:_a}],[ia]:Ia},{endpoint:{[da]:"https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[la]:Nc,[ya]:Ec},[ia]:_a}],[ia]:Ia},{error:'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',[ia]:Sa}],[ia]:Ia},{error:"Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",[ia]:Sa}],[ia]:Ia},{[oa]:Ju,rules:[{[oa]:[fc,{[sa]:Fa,[aa]:[{[sa]:wa,[aa]:[{[sa]:Oa,[aa]:$u}]}]}],error:"Custom endpoint `{Endpoint}` was not a valid URI",[ia]:Sa},{[oa]:[Fc,xc],rules:[{[oa]:Yu,rules:[{[oa]:ed,rules:[{[oa]:[dc,gc],error:"S3 Accelerate cannot be used in this region",[ia]:Sa},{[oa]:[hc,lc,Uc,Oc,Lc],endpoint:{[da]:"https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[hc,lc,Uc,Oc,Dc,zc],rules:[{endpoint:jc,[ia]:_a}],[ia]:Ia},{[oa]:[hc,lc,Uc,Oc,Dc,Hc],endpoint:jc,[ia]:_a},{[oa]:[Wc,lc,Uc,Oc,Lc],endpoint:{[da]:"https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[Wc,lc,Uc,Oc,Dc,zc],rules:[{endpoint:Kc,[ia]:_a}],[ia]:Ia},{[oa]:[Wc,lc,Uc,Oc,Dc,Hc],endpoint:Kc,[ia]:_a},{[oa]:[hc,Vc,dc,Oc,Lc],endpoint:{[da]:"https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[hc,Vc,dc,Oc,Dc,zc],rules:[{endpoint:Qc,[ia]:_a}],[ia]:Ia},{[oa]:[hc,Vc,dc,Oc,Dc,Hc],endpoint:Qc,[ia]:_a},{[oa]:[hc,Vc,Uc,Oc,Lc],endpoint:{[da]:"https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[hc,Vc,Uc,Oc,Dc,zc],rules:[{endpoint:Gc,[ia]:_a}],[ia]:Ia},{[oa]:[hc,Vc,Uc,Oc,Dc,Hc],endpoint:Gc,[ia]:_a},{[oa]:[Wc,Vc,Uc,fc,vc,bc,Lc],endpoint:{[da]:Wa,[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[Wc,Vc,Uc,fc,vc,Jc,Lc],endpoint:{[da]:Na,[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[Wc,Vc,Uc,fc,vc,bc,Dc,zc],rules:[{[oa]:td,endpoint:Xc,[ia]:_a},{endpoint:Xc,[ia]:_a}],[ia]:Ia},{[oa]:[Wc,Vc,Uc,fc,vc,Jc,Dc,zc],rules:[{[oa]:td,endpoint:Zc,[ia]:_a},Yc],[ia]:Ia},{[oa]:[Wc,Vc,Uc,fc,vc,bc,Dc,Hc],endpoint:Xc,[ia]:_a},{[oa]:[Wc,Vc,Uc,fc,vc,Jc,Dc,Hc],endpoint:Zc,[ia]:_a},{[oa]:[Wc,Vc,dc,Oc,Lc],endpoint:{[da]:Ka,[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[Wc,Vc,dc,Oc,Dc,zc],rules:[{[oa]:td,endpoint:eu,[ia]:_a},{endpoint:eu,[ia]:_a}],[ia]:Ia},{[oa]:[Wc,Vc,dc,Oc,Dc,Hc],endpoint:eu,[ia]:_a},{[oa]:[Wc,Vc,Uc,Oc,Lc],endpoint:{[da]:Va,[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[Wc,Vc,Uc,Oc,Dc,zc],rules:[{[oa]:td,endpoint:{[da]:Va,[la]:qc,[ya]:Ec},[ia]:_a},{endpoint:tu,[ia]:_a}],[ia]:Ia},{[oa]:[Wc,Vc,Uc,Oc,Dc,Hc],endpoint:tu,[ia]:_a}],[ia]:Ia},ru],[ia]:Ia}],[ia]:Ia},{[oa]:[fc,vc,{[sa]:xa,[aa]:[{[sa]:Aa,[aa]:[wc,"scheme"]},"http"]},{[sa]:Ma,[aa]:[yc,ba]},Fc,Vc,Wc,Uc],rules:[{[oa]:Yu,rules:[{[oa]:ed,rules:[Yc],[ia]:Ia},ru],[ia]:Ia}],[ia]:Ia},{[oa]:[Fc,{[sa]:Qa,[aa]:Uu,[ua]:Ga}],rules:[{[oa]:[{[sa]:Aa,[aa]:[nu,"resourceId[0]"],[ua]:Ja},{[sa]:Fa,[aa]:[{[sa]:xa,[aa]:[iu,""]}]}],rules:[{[oa]:[{[sa]:xa,[aa]:[ou,Xa]}],rules:[{[oa]:rd,rules:[{[oa]:nd,rules:[au,cu,{[oa]:od,rules:[uu,{[oa]:sd,rules:[du,{[oa]:cd,rules:[{[oa]:Yu,rules:[{[oa]:ud,rules:[{[oa]:dd,rules:[{[oa]:[{[sa]:xa,[aa]:[hu,""]}],error:"Invalid ARN: Missing account id",[ia]:Sa},{[oa]:ld,rules:[{[oa]:hd,rules:[{[oa]:Du,endpoint:{[da]:ec,[la]:fu,[ya]:Ec},[ia]:_a},{[oa]:Wu,endpoint:{[da]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[la]:fu,[ya]:Ec},[ia]:_a},{endpoint:{[da]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",[la]:fu,[ya]:Ec},[ia]:_a}],[ia]:Ia},pu],[ia]:Ia},gu],[ia]:Ia},mu],[ia]:Ia},yu],[ia]:Ia}],[ia]:Ia}],[ia]:Ia},vu],[ia]:Ia},{error:"Invalid ARN: bucket ARN is missing a region",[ia]:Sa}],[ia]:Ia},bu],[ia]:Ia},{error:"Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",[ia]:Sa}],[ia]:Ia},{[oa]:rd,rules:[{[oa]:nd,rules:[{[oa]:od,rules:[{[oa]:rd,rules:[{[oa]:od,rules:[uu,{[oa]:sd,rules:[du,{[oa]:cd,rules:[{[oa]:Yu,rules:[{[oa]:[{[sa]:xa,[aa]:[lu,"{partitionResult#name}"]}],rules:[{[oa]:dd,rules:[{[oa]:[{[sa]:xa,[aa]:[ou,Ha]}],rules:[{[oa]:ld,rules:[{[oa]:hd,rules:[{[oa]:Bu,error:"Access Points do not support S3 Accelerate",[ia]:Sa},{[oa]:[lc,hc],endpoint:{[da]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[la]:wu,[ya]:Ec},[ia]:_a},{[oa]:[lc,Wc],endpoint:{[da]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[la]:wu,[ya]:Ec},[ia]:_a},{[oa]:[Vc,hc],endpoint:{[da]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[la]:wu,[ya]:Ec},[ia]:_a},{[oa]:[Vc,Wc,fc,vc],endpoint:{[da]:ec,[la]:wu,[ya]:Ec},[ia]:_a},{[oa]:[Vc,Wc],endpoint:{[da]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",[la]:wu,[ya]:Ec},[ia]:_a}],[ia]:Ia},pu],[ia]:Ia},gu],[ia]:Ia},{error:"Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",[ia]:Sa}],[ia]:Ia},mu],[ia]:Ia},yu],[ia]:Ia}],[ia]:Ia}],[ia]:Ia},vu],[ia]:Ia}],[ia]:Ia}],[ia]:Ia},{[oa]:[{[sa]:za,[aa]:[su,ba]}],rules:[{[oa]:Lu,error:"S3 MRAP does not support dual-stack",[ia]:Sa},{[oa]:Wu,error:"S3 MRAP does not support FIPS",[ia]:Sa},{[oa]:Bu,error:"S3 MRAP does not support S3 Accelerate",[ia]:Sa},{[oa]:[{[sa]:ka,[aa]:[{[ca]:"DisableMultiRegionAccessPoints"},ba]}],error:"Invalid configuration: Multi-Region Access Point ARNs are disabled.",[ia]:Sa},{[oa]:[{[sa]:Ea,[aa]:Fu,[ua]:tc}],rules:[{[oa]:[{[sa]:xa,[aa]:[{[sa]:Aa,[aa]:[{[ca]:tc},Ta]},{[sa]:Aa,[aa]:[nu,"partition"]}]}],rules:[{endpoint:{[da]:"https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",[la]:{[fa]:[{[pa]:ba,name:ja,[ga]:Ha,[va]:["*"]}]},[ya]:Ec},[ia]:_a}],[ia]:Ia},{error:"Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",[ia]:Sa}],[ia]:Ia}],[ia]:Ia},{error:"Invalid Access Point Name",[ia]:Sa}],[ia]:Ia},bu],[ia]:Ia},{[oa]:[{[sa]:xa,[aa]:[ou,qa]}],rules:[{[oa]:Lu,error:"S3 Outposts does not support Dual-stack",[ia]:Sa},{[oa]:Wu,error:"S3 Outposts does not support FIPS",[ia]:Sa},{[oa]:Bu,error:"S3 Outposts does not support S3 Accelerate",[ia]:Sa},{[oa]:[{[sa]:wa,[aa]:[{[sa]:Aa,[aa]:[nu,"resourceId[4]"]}]}],error:"Invalid Arn: Outpost Access Point ARN contains sub resources",[ia]:Sa},{[oa]:[{[sa]:Aa,[aa]:id,[ua]:Da}],rules:[{[oa]:Xu,rules:[du,{[oa]:cd,rules:[{[oa]:Yu,rules:[{[oa]:ud,rules:[{[oa]:dd,rules:[{[oa]:ld,rules:[{[oa]:[{[sa]:Aa,[aa]:ad,[ua]:rc}],rules:[{[oa]:[{[sa]:Aa,[aa]:[nu,"resourceId[3]"],[ua]:Ya}],rules:[{[oa]:[{[sa]:xa,[aa]:[{[ca]:rc},Za]}],rules:[{[oa]:Du,endpoint:{[da]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",[la]:ku,[ya]:Ec},[ia]:_a},{endpoint:{[da]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",[la]:ku,[ya]:Ec},[ia]:_a}],[ia]:Ia},{error:"Expected an outpost type `accesspoint`, found {outpostType}",[ia]:Sa}],[ia]:Ia},{error:"Invalid ARN: expected an access point name",[ia]:Sa}],[ia]:Ia},{error:"Invalid ARN: Expected a 4-component resource",[ia]:Sa}],[ia]:Ia},gu],[ia]:Ia},mu],[ia]:Ia},yu],[ia]:Ia}],[ia]:Ia}],[ia]:Ia},{error:"Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",[ia]:Sa}],[ia]:Ia},{error:"Invalid ARN: The Outpost Id was not set",[ia]:Sa}],[ia]:Ia},{error:"Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",[ia]:Sa}],[ia]:Ia},{error:"Invalid ARN: No ARN type specified",[ia]:Sa}],[ia]:Ia},{[oa]:[{[sa]:Ca,[aa]:[yc,0,4,!1],[ua]:nc},{[sa]:xa,[aa]:[{[ca]:nc},"arn:"]},{[sa]:Fa,[aa]:[{[sa]:wa,[aa]:[Su]}]}],error:"Invalid ARN: `{Bucket}` was not a valid ARN",[ia]:Sa},{[oa]:[{[sa]:ka,[aa]:[$c,ba]},Su],error:"Path-style addressing cannot be used with ARN buckets",[ia]:Sa},{[oa]:qu,rules:[{[oa]:Yu,rules:[{[oa]:[Uc],rules:[{[oa]:[hc,Oc,lc,Lc],endpoint:{[da]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[hc,Oc,lc,Dc,zc],rules:[{endpoint:Eu,[ia]:_a}],[ia]:Ia},{[oa]:[hc,Oc,lc,Dc,Hc],endpoint:Eu,[ia]:_a},{[oa]:[Wc,Oc,lc,Lc],endpoint:{[da]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[Wc,Oc,lc,Dc,zc],rules:[{endpoint:xu,[ia]:_a}],[ia]:Ia},{[oa]:[Wc,Oc,lc,Dc,Hc],endpoint:xu,[ia]:_a},{[oa]:[hc,Oc,Vc,Lc],endpoint:{[da]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[hc,Oc,Vc,Dc,zc],rules:[{endpoint:Au,[ia]:_a}],[ia]:Ia},{[oa]:[hc,Oc,Vc,Dc,Hc],endpoint:Au,[ia]:_a},{[oa]:[Wc,fc,vc,Vc,Lc],endpoint:{[da]:ic,[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[Wc,fc,vc,Vc,Dc,zc],rules:[{[oa]:td,endpoint:Tu,[ia]:_a},{endpoint:Tu,[ia]:_a}],[ia]:Ia},{[oa]:[Wc,fc,vc,Vc,Dc,Hc],endpoint:Tu,[ia]:_a},{[oa]:[Wc,Oc,Vc,Lc],endpoint:{[da]:oc,[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[Wc,Oc,Vc,Dc,zc],rules:[{[oa]:td,endpoint:{[da]:oc,[la]:qc,[ya]:Ec},[ia]:_a},{endpoint:Cu,[ia]:_a}],[ia]:Ia},{[oa]:[Wc,Oc,Vc,Dc,Hc],endpoint:Cu,[ia]:_a}],[ia]:Ia},{error:"Path-style addressing cannot be used with S3 Accelerate",[ia]:Sa}],[ia]:Ia}],[ia]:Ia}],[ia]:Ia},{[oa]:[{[sa]:wa,[aa]:[Ru]},{[sa]:ka,[aa]:[Ru,ba]}],rules:[{[oa]:Yu,rules:[{[oa]:fd,rules:[au,cu,{[oa]:Du,endpoint:{[da]:$a,[la]:Ou,[ya]:Ec},[ia]:_a},{[oa]:Wu,endpoint:{[da]:"https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",[la]:Ou,[ya]:Ec},[ia]:_a},{endpoint:{[da]:"https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",[la]:Ou,[ya]:Ec},[ia]:_a}],[ia]:Ia},ru],[ia]:Ia}],[ia]:Ia},{[oa]:[_c],rules:[{[oa]:Yu,rules:[{[oa]:fd,rules:[{[oa]:[lc,hc,Oc,Lc],endpoint:{[da]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[lc,hc,Oc,Dc,zc],rules:[{endpoint:Pu,[ia]:_a}],[ia]:Ia},{[oa]:[lc,hc,Oc,Dc,Hc],endpoint:Pu,[ia]:_a},{[oa]:[lc,Wc,Oc,Lc],endpoint:{[da]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[lc,Wc,Oc,Dc,zc],rules:[{endpoint:_u,[ia]:_a}],[ia]:Ia},{[oa]:[lc,Wc,Oc,Dc,Hc],endpoint:_u,[ia]:_a},{[oa]:[Vc,hc,Oc,Lc],endpoint:{[da]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[Vc,hc,Oc,Dc,zc],rules:[{endpoint:Iu,[ia]:_a}],[ia]:Ia},{[oa]:[Vc,hc,Oc,Dc,Hc],endpoint:Iu,[ia]:_a},{[oa]:[Vc,Wc,fc,vc,Lc],endpoint:{[da]:$a,[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[Vc,Wc,fc,vc,Dc,zc],rules:[{[oa]:td,endpoint:Mu,[ia]:_a},{endpoint:Mu,[ia]:_a}],[ia]:Ia},{[oa]:[Vc,Wc,fc,vc,Dc,Hc],endpoint:Mu,[ia]:_a},{[oa]:[Vc,Wc,Oc,Lc],endpoint:{[da]:sc,[la]:Bc,[ya]:Ec},[ia]:_a},{[oa]:[Vc,Wc,Oc,Dc,zc],rules:[{[oa]:td,endpoint:{[da]:sc,[la]:qc,[ya]:Ec},[ia]:_a},{endpoint:Nu,[ia]:_a}],[ia]:Ia},{[oa]:[Vc,Wc,Oc,Dc,Hc],endpoint:Nu,[ia]:_a}],[ia]:Ia},ru],[ia]:Ia}],[ia]:Ia}],[ia]:Ia},{error:"A region must be set when sending requests to S3.",[ia]:Sa}]},gd=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"]}),md=(e,t={})=>gd.get(e,(()=>((e,t)=>{const{endpointParams:r,logger:n}=t,{parameters:i,rules:o}=e;t.logger?.debug?.(`${$o} Initial EndpointParams: ${Uo(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 Lo(`Missing required parameter: '${e}'`);const c=es(o,{endpointParams:r,logger:n,referenceRecord:{}});return t.logger?.debug?.(`${$o} Resolved endpoint: ${Uo(c)}`),c})(pd,{endpointParams:e,logger:t.logger})));Fo.aws=ns;const yd=(vd=async(e,t,r)=>({operation:de(t).operation,region:await le(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 vd(e,t,r),i=de(t)?.commandInstance?.constructor?.getEndpointParameterInstructions;if(!i)throw new Error(`getEndpointParameterInstructions() is not defined on \`${t.commandName}\``);const o=await Ts(r,{getEndpointParameterInstructions:i},e);return Object.assign(n,o)});var vd;function bd(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function wd(e){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}const kd=((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})(md,(e=>{const t=[];return e.operation,t.push(bd(e)),t.push(wd(e)),t}),{"aws.auth#sigv4":bd,"aws.auth#sigv4a":wd}),Sd=e=>{const t=(e=>(e.sigv4aSigningRegionSet=ke(e.sigv4aSigningRegionSet),e))(Ft(e));return{...t}},Ed={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 xd extends Pr{constructor(e){super(e),Object.setPrototypeOf(this,xd.prototype)}}class Ad extends xd{constructor(e){super({name:"NoSuchUpload",$fault:"client",...e}),this.name="NoSuchUpload",this.$fault="client",Object.setPrototypeOf(this,Ad.prototype)}}class Td extends xd{constructor(e){super({name:"ObjectNotInActiveTierError",$fault:"client",...e}),this.name="ObjectNotInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,Td.prototype)}}class Cd extends xd{constructor(e){super({name:"BucketAlreadyExists",$fault:"client",...e}),this.name="BucketAlreadyExists",this.$fault="client",Object.setPrototypeOf(this,Cd.prototype)}}class Rd extends xd{constructor(e){super({name:"BucketAlreadyOwnedByYou",$fault:"client",...e}),this.name="BucketAlreadyOwnedByYou",this.$fault="client",Object.setPrototypeOf(this,Rd.prototype)}}class Od extends xd{constructor(e){super({name:"NoSuchBucket",$fault:"client",...e}),this.name="NoSuchBucket",this.$fault="client",Object.setPrototypeOf(this,Od.prototype)}}var Pd,_d;!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])}(Pd||(Pd={})),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])}(_d||(_d={}));class Id extends xd{constructor(e){super({name:"InvalidObjectState",$fault:"client",...e}),this.name="InvalidObjectState",this.$fault="client",Object.setPrototypeOf(this,Id.prototype),this.StorageClass=e.StorageClass,this.AccessTier=e.AccessTier}}class Md extends xd{constructor(e){super({name:"NoSuchKey",$fault:"client",...e}),this.name="NoSuchKey",this.$fault="client",Object.setPrototypeOf(this,Md.prototype)}}class Nd extends xd{constructor(e){super({name:"NotFound",$fault:"client",...e}),this.name="NotFound",this.$fault="client",Object.setPrototypeOf(this,Nd.prototype)}}const Fd=e=>({...e,...e.SecretAccessKey&&{SecretAccessKey:Ht},...e.SessionToken&&{SessionToken:Ht}}),$d=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Ht},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Ht},...e.Credentials&&{Credentials:Fd(e.Credentials)}}),Ud=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Ht},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Ht}}),Ld=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Ht}}),Bd=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:Ht}});class Dd extends xd{constructor(e){super({name:"EncryptionTypeMismatch",$fault:"client",...e}),this.name="EncryptionTypeMismatch",this.$fault="client",Object.setPrototypeOf(this,Dd.prototype)}}class zd extends xd{constructor(e){super({name:"InvalidRequest",$fault:"client",...e}),this.name="InvalidRequest",this.$fault="client",Object.setPrototypeOf(this,zd.prototype)}}class jd extends xd{constructor(e){super({name:"InvalidWriteOffset",$fault:"client",...e}),this.name="InvalidWriteOffset",this.$fault="client",Object.setPrototypeOf(this,jd.prototype)}}class qd extends xd{constructor(e){super({name:"TooManyParts",$fault:"client",...e}),this.name="TooManyParts",this.$fault="client",Object.setPrototypeOf(this,qd.prototype)}}class Hd extends xd{constructor(e){super({name:"ObjectAlreadyInActiveTierError",$fault:"client",...e}),this.name="ObjectAlreadyInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,Hd.prototype)}}var Wd;!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])}(Wd||(Wd={}));const Kd=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Ht},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Ht}}),Vd=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:Ht},...e.SSEKMSKeyId&&{SSEKMSKeyId:Ht},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Ht}}),Qd=async(e,t)=>{const r=Xe(e,t),n=Wr({},jr,{[tp]:e[Zh],[Ap]:e[Yh],[Tp]:e[of],[Rp]:e[nf],[Cp]:[()=>jr(e[Il]),()=>e[Il].toString()]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=Wr({[Wf]:[,""]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Gd=async(e,t)=>{const r=Xe(e,t),n=Wr({},jr,{[lp]:e[Eh],[kp]:e[Wh],[Gf]:[()=>jr(e[_l]),()=>e[_l].toString()],[ip]:e[th],[Of]:e[hh],[up]:[()=>jr(e[fh]),()=>hr(e[fh]).toString()],[dp]:[()=>jr(e[ph]),()=>e[ph].toString()]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=Wr({[Up]:[,"DeleteObject"],[Vf]:[,e[df]]});return r.m("DELETE").h(n).q(i).b(undefined),r.build()},Jd=async(e,t)=>{const r=Xe(e,t),n=Wr({},jr,{[Of]:e[hh],[Pf]:[()=>jr(e[gh]),()=>hr(e[gh]).toString()],[_f]:e[mh],[If]:[()=>jr(e[bh]),()=>hr(e[bh]).toString()],[Lf]:e[$h],[Op]:e[ef],[Pp]:e[tf],[_p]:e[rf],[kp]:e[Wh],[ip]:e[th],[Zf]:e[jl]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=Wr({[Up]:[,"GetObject"],[Bf]:[,e[Lh]],[Df]:[,e[Bh]],[zf]:[,e[Dh]],[jf]:[,e[zh]],[qf]:[,e[jh]],[Hf]:[()=>void 0!==e.ResponseExpires,()=>hr(e[qh]).toString()],[Vf]:[,e[df]],[$f]:[()=>void 0!==e.PartNumber,()=>e[Fh].toString()]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Xd=async(e,t)=>{const r=Xe(e,t),n=Wr({},jr,{[kp]:e[Wh],[ip]:e[th],[yp]:[()=>jr(e[Ih]),()=>(e[Ih]||[]).map(Jr).join(", ")]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=Wr({[Nf]:[,"2"],[Ef]:[,e[Xl]],[Af]:[,e[nh]],[Ff]:[()=>void 0!==e.MaxKeys,()=>e[xh].toString()],[Uf]:[,e[Mh]],[Sf]:[,e[Gl]],[Rf]:[()=>void 0!==e.FetchOwner,()=>e[sh].toString()],[Kf]:[,e[Gh]]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Zd=async(e,t)=>{const r=Xe(e,t),n=Wr({},jr,{[kf]:e[Ql]||"application/octet-stream",[Qf]:e[Cl],[pf]:e[Fl],[gf]:e[Ll],[mf]:e[Bl],[yf]:e[Dl],[vf]:[()=>jr(e[zl]),()=>e[zl].toString()],[bf]:e[ql],[xp]:e[Nl],[Jf]:e[$l],[Xf]:e[Ul],[Yf]:e[Kl],[ep]:e[Vl],[xf]:[()=>jr(e[eh]),()=>hr(e[eh]).toString()],[Of]:e[hh],[_f]:e[mh],[op]:e[ah],[sp]:e[ch],[ap]:e[uh],[cp]:e[dh],[Fp]:[()=>jr(e[lf]),()=>e[lf].toString()],[Ap]:e[Yh],[Ep]:e[Xh],[$p]:e[hf],[Op]:e[ef],[Pp]:e[tf],[_p]:e[rf],[Tp]:e[of],[Rp]:e[nf],[Cp]:[()=>jr(e[Il]),()=>e[Il].toString()],[kp]:e[Wh],[Ip]:e[cf],[gp]:e[Ph],[mp]:[()=>jr(e[_h]),()=>{return(t=e[_h],t.toISOString().replace(".000Z","Z")).toString();var t}],[pp]:e[Oh],[ip]:e[th],...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=Wr({[Up]:[,"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()},Yd=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return il(e,t);const r=Wr({$metadata:Tl(e),[Yh]:[,e.headers[Ap]],[of]:[,e.headers[Tp]],[nf]:[,e.headers[Rp]],[Il]:[()=>void 0!==e.headers[Cp],()=>Wt(e.headers[Cp])]}),n=er(tr(await vi(e.body,t)),"body");return null!=n[Ml]&&(r[Ml]=Al(n[Ml])),r},el=async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return il(e,t);const r=Wr({$metadata:Tl(e),[Zl]:[()=>void 0!==e.headers[rp],()=>Wt(e.headers[rp])],[df]:[,e.headers[Np]],[Uh]:[,e.headers[wp]]});return await Ge(e.body,t),r},tl=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return il(e,t);const r=Wr({$metadata:Tl(e),[Zl]:[()=>void 0!==e.headers[rp],()=>Wt(e.headers[rp])],[Ol]:[,e.headers[ff]],[oh]:[,e.headers[np]],[Qh]:[,e.headers[bp]],[Sh]:[()=>void 0!==e.headers[Mf],()=>er(vr(e.headers[Mf]))],[zl]:[()=>void 0!==e.headers[vf],()=>or(e.headers[vf])],[ih]:[,e.headers[Tf]],[$l]:[,e.headers[Jf]],[Ul]:[,e.headers[Xf]],[Kl]:[,e.headers[Yf]],[Vl]:[,e.headers[ep]],[Ah]:[()=>void 0!==e.headers[hp],()=>sr(e.headers[hp])],[df]:[,e.headers[Np]],[Fl]:[,e.headers[pf]],[Ll]:[,e.headers[gf]],[Bl]:[,e.headers[mf]],[Dl]:[,e.headers[yf]],[Wl]:[,e.headers[wf]],[Ql]:[,e.headers[kf]],[eh]:[()=>void 0!==e.headers[xf],()=>er(vr(e.headers[xf]))],[rh]:[,e.headers[Cf]],[hf]:[,e.headers[$p]],[Yh]:[,e.headers[Ap]],[ef]:[,e.headers[Op]],[rf]:[,e.headers[_p]],[of]:[,e.headers[Tp]],[Il]:[()=>void 0!==e.headers[Cp],()=>Wt(e.headers[Cp])],[Xh]:[,e.headers[Ep]],[Uh]:[,e.headers[wp]],[Kh]:[,e.headers[Sp]],[Nh]:[()=>void 0!==e.headers[fp],()=>sr(e.headers[fp])],[uf]:[()=>void 0!==e.headers[Mp],()=>sr(e.headers[Mp])],[Ph]:[,e.headers[gp]],[_h]:[()=>void 0!==e.headers[mp],()=>er(pr(e.headers[mp]))],[Oh]:[,e.headers[pp]],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},rl=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return il(e,t);const r=Wr({$metadata:Tl(e),[Uh]:[,e.headers[wp]]}),n=er(tr(await vi(e.body,t)),"body");return""===n.CommonPrefixes?r[Hl]=[]:null!=n[Hl]&&(r[Hl]=wl(Dr(n[Hl]))),""===n.Contents?r[Jl]=[]:null!=n[Jl]&&(r[Jl]=Sl(Dr(n[Jl]))),null!=n[Gl]&&(r[Gl]=rr(n[Gl])),null!=n[Xl]&&(r[Xl]=rr(n[Xl])),null!=n[nh]&&(r[nh]=rr(n[nh])),null!=n[vh]&&(r[vh]=Wt(n[vh])),null!=n[kh]&&(r[kh]=sr(n[kh])),null!=n[xh]&&(r[xh]=sr(n[xh])),null!=n[Th]&&(r[Th]=rr(n[Th])),null!=n[Ch]&&(r[Ch]=rr(n[Ch])),null!=n[Mh]&&(r[Mh]=rr(n[Mh])),null!=n[Gh]&&(r[Gh]=rr(n[Gh])),r},nl=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return il(e,t);const r=Wr({$metadata:Tl(e),[oh]:[,e.headers[np]],[ih]:[,e.headers[Tf]],[$l]:[,e.headers[Jf]],[Ul]:[,e.headers[Xf]],[Kl]:[,e.headers[Yf]],[Vl]:[,e.headers[ep]],[Yh]:[,e.headers[Ap]],[df]:[,e.headers[Np]],[ef]:[,e.headers[Op]],[rf]:[,e.headers[_p]],[of]:[,e.headers[Tp]],[nf]:[,e.headers[Rp]],[Il]:[()=>void 0!==e.headers[Cp],()=>Wt(e.headers[Cp])],[af]:[()=>void 0!==e.headers[vp],()=>or(e.headers[vp])],[Uh]:[,e.headers[wp]]});return await Ge(e.body,t),r},il=async(e,t)=>{const r={...e,body:await bi(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 gl(r,t);case"ObjectNotInActiveTierError":case"com.amazonaws.s3#ObjectNotInActiveTierError":throw await vl(r,t);case"BucketAlreadyExists":case"com.amazonaws.s3#BucketAlreadyExists":throw await al(r,t);case"BucketAlreadyOwnedByYou":case"com.amazonaws.s3#BucketAlreadyOwnedByYou":throw await cl(r,t);case"NoSuchBucket":case"com.amazonaws.s3#NoSuchBucket":throw await fl(r,t);case"InvalidObjectState":case"com.amazonaws.s3#InvalidObjectState":throw await dl(r,t);case"NoSuchKey":case"com.amazonaws.s3#NoSuchKey":throw await pl(r,t);case"NotFound":case"com.amazonaws.s3#NotFound":throw await ml(r,t);case"EncryptionTypeMismatch":case"com.amazonaws.s3#EncryptionTypeMismatch":throw await ul(r,t);case"InvalidRequest":case"com.amazonaws.s3#InvalidRequest":throw await ll(r,t);case"InvalidWriteOffset":case"com.amazonaws.s3#InvalidWriteOffset":throw await hl(r,t);case"TooManyParts":case"com.amazonaws.s3#TooManyParts":throw await bl(r,t);case"ObjectAlreadyInActiveTierError":case"com.amazonaws.s3#ObjectAlreadyInActiveTierError":throw await yl(r,t);default:const i=r.body;return ol({output:e,parsedBody:i,errorCode:n})}},ol=(sl=xd,({output:e,parsedBody:t,errorCode:r})=>{(({output:e,parsedBody:t,exceptionCtor:r,errorCode:n})=>{const i=Ir(e),o=i.httpStatusCode?i.httpStatusCode+"":void 0,s=new r({name:t?.code||t?.Code||n||o||"UnknownError",$fault:"client",$metadata:i});throw _r(s,t)})({output:e,parsedBody:t,exceptionCtor:sl,errorCode:r})});var sl;const al=async(e,t)=>{const r=Wr({});e.body;const n=new Cd({$metadata:Tl(e),...r});return _r(n,e.body)},cl=async(e,t)=>{const r=Wr({});e.body;const n=new Rd({$metadata:Tl(e),...r});return _r(n,e.body)},ul=async(e,t)=>{const r=Wr({});e.body;const n=new Dd({$metadata:Tl(e),...r});return _r(n,e.body)},dl=async(e,t)=>{const r=Wr({}),n=e.body;null!=n[Pl]&&(r[Pl]=rr(n[Pl])),null!=n[Xh]&&(r[Xh]=rr(n[Xh]));const i=new Id({$metadata:Tl(e),...r});return _r(i,e.body)},ll=async(e,t)=>{const r=Wr({});e.body;const n=new zd({$metadata:Tl(e),...r});return _r(n,e.body)},hl=async(e,t)=>{const r=Wr({});e.body;const n=new jd({$metadata:Tl(e),...r});return _r(n,e.body)},fl=async(e,t)=>{const r=Wr({});e.body;const n=new Od({$metadata:Tl(e),...r});return _r(n,e.body)},pl=async(e,t)=>{const r=Wr({});e.body;const n=new Md({$metadata:Tl(e),...r});return _r(n,e.body)},gl=async(e,t)=>{const r=Wr({});e.body;const n=new Ad({$metadata:Tl(e),...r});return _r(n,e.body)},ml=async(e,t)=>{const r=Wr({});e.body;const n=new Nd({$metadata:Tl(e),...r});return _r(n,e.body)},yl=async(e,t)=>{const r=Wr({});e.body;const n=new Hd({$metadata:Tl(e),...r});return _r(n,e.body)},vl=async(e,t)=>{const r=Wr({});e.body;const n=new Td({$metadata:Tl(e),...r});return _r(n,e.body)},bl=async(e,t)=>{const r=Wr({});e.body;const n=new qd({$metadata:Tl(e),...r});return _r(n,e.body)},wl=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>(e=>{const t={};return null!=e[Mh]&&(t[Mh]=rr(e[Mh])),t})(e))),kl=(e,t)=>{const r={};return null!=e[wh]&&(r[wh]=rr(e[wh])),null!=e[Sh]&&(r[Sh]=er(pr(e[Sh]))),null!=e[ih]&&(r[ih]=rr(e[ih])),""===e.ChecksumAlgorithm?r[Nl]=[]:null!=e[Nl]&&(r[Nl]=(e=>(e||[]).filter((e=>null!=e)).map((e=>rr(e))))(Dr(e[Nl]))),null!=e[af]&&(r[af]=or(e[af])),null!=e[Xh]&&(r[Xh]=rr(e[Xh])),null!=e[Rh]&&(r[Rh]=El(e[Rh])),null!=e[Vh]&&(r[Vh]=xl(e[Vh])),r},Sl=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>kl(e))),El=(e,t)=>{const r={};return null!=e[Yl]&&(r[Yl]=rr(e[Yl])),null!=e[lh]&&(r[lh]=rr(e[lh])),r},xl=(e,t)=>{const r={};return null!=e[yh]&&(r[yh]=Wt(e[yh])),null!=e[Hh]&&(r[Hh]=er(pr(e[Hh]))),r},Al=(e,t)=>{const r={};return null!=e[Rl]&&(r[Rl]=rr(e[Rl])),null!=e[Jh]&&(r[Jh]=rr(e[Jh])),null!=e[sf]&&(r[sf]=rr(e[sf])),null!=e[oh]&&(r[oh]=er(pr(e[oh]))),r},Tl=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"]}),Cl="ACL",Rl="AccessKeyId",Ol="AcceptRanges",Pl="AccessTier",_l="BypassGovernanceRetention",Il="BucketKeyEnabled",Ml="Credentials",Nl="ChecksumAlgorithm",Fl="CacheControl",$l="ChecksumCRC32",Ul="ChecksumCRC32C",Ll="ContentDisposition",Bl="ContentEncoding",Dl="ContentLanguage",zl="ContentLength",jl="ChecksumMode",ql="ContentMD5",Hl="CommonPrefixes",Wl="ContentRange",Kl="ChecksumSHA1",Vl="ChecksumSHA256",Ql="ContentType",Gl="ContinuationToken",Jl="Contents",Xl="Delimiter",Zl="DeleteMarker",Yl="DisplayName",eh="Expires",th="ExpectedBucketOwner",rh="ExpiresString",nh="EncodingType",ih="ETag",oh="Expiration",sh="FetchOwner",ah="GrantFullControl",ch="GrantRead",uh="GrantReadACP",dh="GrantWriteACP",lh="ID",hh="IfMatch",fh="IfMatchLastModifiedTime",ph="IfMatchSize",gh="IfModifiedSince",mh="IfNoneMatch",yh="IsRestoreInProgress",vh="IsTruncated",bh="IfUnmodifiedSince",wh="Key",kh="KeyCount",Sh="LastModified",Eh="MFA",xh="MaxKeys",Ah="MissingMeta",Th="Name",Ch="NextContinuationToken",Rh="Owner",Oh="ObjectLockLegalHoldStatus",Ph="ObjectLockMode",_h="ObjectLockRetainUntilDate",Ih="OptionalObjectAttributes",Mh="Prefix",Nh="PartsCount",Fh="PartNumber",$h="Range",Uh="RequestCharged",Lh="ResponseCacheControl",Bh="ResponseContentDisposition",Dh="ResponseContentEncoding",zh="ResponseContentLanguage",jh="ResponseContentType",qh="ResponseExpires",Hh="RestoreExpiryDate",Wh="RequestPayer",Kh="ReplicationStatus",Vh="RestoreStatus",Qh="Restore",Gh="StartAfter",Jh="SecretAccessKey",Xh="StorageClass",Zh="SessionMode",Yh="ServerSideEncryption",ef="SSECustomerAlgorithm",tf="SSECustomerKey",rf="SSECustomerKeyMD5",nf="SSEKMSEncryptionContext",of="SSEKMSKeyId",sf="SessionToken",af="Size",cf="Tagging",uf="TagCount",df="VersionId",lf="WriteOffsetBytes",hf="WebsiteRedirectLocation",ff="accept-ranges",pf="cache-control",gf="content-disposition",mf="content-encoding",yf="content-language",vf="content-length",bf="content-md5",wf="content-range",kf="content-type",Sf="continuation-token",Ef="delimiter",xf="expires",Af="encoding-type",Tf="etag",Cf="expiresstring",Rf="fetch-owner",Of="if-match",Pf="if-modified-since",_f="if-none-match",If="if-unmodified-since",Mf="last-modified",Nf="list-type",Ff="max-keys",$f="partNumber",Uf="prefix",Lf="range",Bf="response-cache-control",Df="response-content-disposition",zf="response-content-encoding",jf="response-content-language",qf="response-content-type",Hf="response-expires",Wf="session",Kf="start-after",Vf="versionId",Qf="x-amz-acl",Gf="x-amz-bypass-governance-retention",Jf="x-amz-checksum-crc32",Xf="x-amz-checksum-crc32c",Zf="x-amz-checksum-mode",Yf="x-amz-checksum-sha1",ep="x-amz-checksum-sha256",tp="x-amz-create-session-mode",rp="x-amz-delete-marker",np="x-amz-expiration",ip="x-amz-expected-bucket-owner",op="x-amz-grant-full-control",sp="x-amz-grant-read",ap="x-amz-grant-read-acp",cp="x-amz-grant-write-acp",up="x-amz-if-match-last-modified-time",dp="x-amz-if-match-size",lp="x-amz-mfa",hp="x-amz-missing-meta",fp="x-amz-mp-parts-count",pp="x-amz-object-lock-legal-hold",gp="x-amz-object-lock-mode",mp="x-amz-object-lock-retain-until-date",yp="x-amz-optional-object-attributes",vp="x-amz-object-size",bp="x-amz-restore",wp="x-amz-request-charged",kp="x-amz-request-payer",Sp="x-amz-replication-status",Ep="x-amz-storage-class",xp="x-amz-sdk-checksum-algorithm",Ap="x-amz-server-side-encryption",Tp="x-amz-server-side-encryption-aws-kms-key-id",Cp="x-amz-server-side-encryption-bucket-key-enabled",Rp="x-amz-server-side-encryption-context",Op="x-amz-server-side-encryption-customer-algorithm",Pp="x-amz-server-side-encryption-customer-key",_p="x-amz-server-side-encryption-customer-key-md5",Ip="x-amz-tagging",Mp="x-amz-tagging-count",Np="x-amz-version-id",Fp="x-amz-write-offset-bytes",$p="x-amz-website-redirect-location",Up="x-id";class Lp extends(jt.classBuilder().ep({...Ed,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(e,t,r,n){return[me(r,this.serialize,this.deserialize),Os(r,e.getEndpointParameterInstructions()),Co(r)]})).s("AmazonS3","CreateSession",{}).n("S3Client","CreateSessionCommand").f(Ud,$d).ser(Qd).de(Yd).build()){}var Bp="3.701.0";function Dp(e){return"string"==typeof e?0===e.length:0===e.byteLength}var zp={name:"SHA-1"},jp={name:"HMAC",hash:zp},qp=new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]);const Hp={};function Wp(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:Hp}var Kp=function(){function e(e){this.toHash=new Uint8Array(0),void 0!==e&&(this.key=new Promise((function(t,r){Wp().crypto.subtle.importKey("raw",Vp(e),jp,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))}return e.prototype.update=function(e){if(!Dp(e)){var t=Vp(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 Wp().crypto.subtle.sign(jp,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):Dp(this.toHash)?Promise.resolve(qp):Promise.resolve().then((function(){return Wp().crypto.subtle.digest(zp,e.toHash)})).then((function(e){return Promise.resolve(new Uint8Array(e))}))},e.prototype.reset=function(){this.toHash=new Uint8Array(0)},e}();function Vp(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 Qp=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function Gp(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&&Qp.every((function(t){return"function"==typeof e[t]}))}(e.crypto.subtle)}var Jp=function(){function e(e){if(!Gp(Wp()))throw new Error("SHA1 not supported");this.hash=new Kp(e)}return e.prototype.update=function(e,t){this.hash.update(Ci(e))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e}(),Xp={name:"SHA-256"},Zp={name:"HMAC",hash:Xp},Yp=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]),eg=function(){function e(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return e.prototype.update=function(e){if(!Ri(e)){var t=Ci(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 Wp().crypto.subtle.sign(Zp,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):Ri(this.toHash)?Promise.resolve(Yp):Promise.resolve().then((function(){return Wp().crypto.subtle.digest(Xp,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){Wp().crypto.subtle.importKey("raw",Ci(e.secret),Zp,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))},e}();function tg(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 rg(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]sg)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;r>0;)this.buffer[this.bufferLength++]=e[t++],r--,this.bufferLength===ng&&(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%ng>=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+(ig[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}(),cg=function(){function e(e){this.secret=e,this.hash=new ag,this.reset()}return e.prototype.update=function(e){if(!Ri(e)&&!this.error)try{this.hash.update(Ci(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 tg(this,void 0,void 0,(function(){return rg(this,(function(e){return[2,this.digestSync()]}))}))},e.prototype.reset=function(){if(this.hash=new ag,this.secret){this.outer=new ag;var e=function(e){var t=Ci(e);if(t.byteLength>ng){var r=new ag;r.update(t),t=r.digest()}var n=new Uint8Array(ng);return n.set(t),n}(this.secret),t=new Uint8Array(ng);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 lg=Xr(dg.exports);const hg=({serviceId:e,clientVersion:t})=>async r=>{const n="undefined"!=typeof window&&window?.navigator?.userAgent?lg.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 fg{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&&pg(t),new fg(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&pg(e),parseInt(ze(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function pg(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}class gg{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(fg.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!Tg.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(De(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 Ui;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 Ui).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 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.decoder.decode(e);yield t}}}class Og{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 Pg{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 _g{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 Ig(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 Mg{constructor({utf8Encoder:e,utf8Decoder:t}){this.eventStreamCodec=new Cg(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 Fg=e=>"function"==typeof ReadableStream&&e instanceof ReadableStream,$g=e=>new Ng(e);const Ug=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()},Lg=64,Bg=[1732584193,4023233417,2562383102,271733878];class Dg{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 Ae(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===Lg&&(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%Lg>=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=jg(r,n,i,o,e.getUint32(0,!0),7,3614090360),o=jg(o,r,n,i,e.getUint32(4,!0),12,3905402710),i=jg(i,o,r,n,e.getUint32(8,!0),17,606105819),n=jg(n,i,o,r,e.getUint32(12,!0),22,3250441966),r=jg(r,n,i,o,e.getUint32(16,!0),7,4118548399),o=jg(o,r,n,i,e.getUint32(20,!0),12,1200080426),i=jg(i,o,r,n,e.getUint32(24,!0),17,2821735955),n=jg(n,i,o,r,e.getUint32(28,!0),22,4249261313),r=jg(r,n,i,o,e.getUint32(32,!0),7,1770035416),o=jg(o,r,n,i,e.getUint32(36,!0),12,2336552879),i=jg(i,o,r,n,e.getUint32(40,!0),17,4294925233),n=jg(n,i,o,r,e.getUint32(44,!0),22,2304563134),r=jg(r,n,i,o,e.getUint32(48,!0),7,1804603682),o=jg(o,r,n,i,e.getUint32(52,!0),12,4254626195),i=jg(i,o,r,n,e.getUint32(56,!0),17,2792965006),n=jg(n,i,o,r,e.getUint32(60,!0),22,1236535329),r=qg(r,n,i,o,e.getUint32(4,!0),5,4129170786),o=qg(o,r,n,i,e.getUint32(24,!0),9,3225465664),i=qg(i,o,r,n,e.getUint32(44,!0),14,643717713),n=qg(n,i,o,r,e.getUint32(0,!0),20,3921069994),r=qg(r,n,i,o,e.getUint32(20,!0),5,3593408605),o=qg(o,r,n,i,e.getUint32(40,!0),9,38016083),i=qg(i,o,r,n,e.getUint32(60,!0),14,3634488961),n=qg(n,i,o,r,e.getUint32(16,!0),20,3889429448),r=qg(r,n,i,o,e.getUint32(36,!0),5,568446438),o=qg(o,r,n,i,e.getUint32(56,!0),9,3275163606),i=qg(i,o,r,n,e.getUint32(12,!0),14,4107603335),n=qg(n,i,o,r,e.getUint32(32,!0),20,1163531501),r=qg(r,n,i,o,e.getUint32(52,!0),5,2850285829),o=qg(o,r,n,i,e.getUint32(8,!0),9,4243563512),i=qg(i,o,r,n,e.getUint32(28,!0),14,1735328473),n=qg(n,i,o,r,e.getUint32(48,!0),20,2368359562),r=Hg(r,n,i,o,e.getUint32(20,!0),4,4294588738),o=Hg(o,r,n,i,e.getUint32(32,!0),11,2272392833),i=Hg(i,o,r,n,e.getUint32(44,!0),16,1839030562),n=Hg(n,i,o,r,e.getUint32(56,!0),23,4259657740),r=Hg(r,n,i,o,e.getUint32(4,!0),4,2763975236),o=Hg(o,r,n,i,e.getUint32(16,!0),11,1272893353),i=Hg(i,o,r,n,e.getUint32(28,!0),16,4139469664),n=Hg(n,i,o,r,e.getUint32(40,!0),23,3200236656),r=Hg(r,n,i,o,e.getUint32(52,!0),4,681279174),o=Hg(o,r,n,i,e.getUint32(0,!0),11,3936430074),i=Hg(i,o,r,n,e.getUint32(12,!0),16,3572445317),n=Hg(n,i,o,r,e.getUint32(24,!0),23,76029189),r=Hg(r,n,i,o,e.getUint32(36,!0),4,3654602809),o=Hg(o,r,n,i,e.getUint32(48,!0),11,3873151461),i=Hg(i,o,r,n,e.getUint32(60,!0),16,530742520),n=Hg(n,i,o,r,e.getUint32(8,!0),23,3299628645),r=Wg(r,n,i,o,e.getUint32(0,!0),6,4096336452),o=Wg(o,r,n,i,e.getUint32(28,!0),10,1126891415),i=Wg(i,o,r,n,e.getUint32(56,!0),15,2878612391),n=Wg(n,i,o,r,e.getUint32(20,!0),21,4237533241),r=Wg(r,n,i,o,e.getUint32(48,!0),6,1700485571),o=Wg(o,r,n,i,e.getUint32(12,!0),10,2399980690),i=Wg(i,o,r,n,e.getUint32(40,!0),15,4293915773),n=Wg(n,i,o,r,e.getUint32(4,!0),21,2240044497),r=Wg(r,n,i,o,e.getUint32(32,!0),6,1873313359),o=Wg(o,r,n,i,e.getUint32(60,!0),10,4264355552),i=Wg(i,o,r,n,e.getUint32(24,!0),15,2734768916),n=Wg(n,i,o,r,e.getUint32(52,!0),21,1309151649),r=Wg(r,n,i,o,e.getUint32(16,!0),6,4149444226),o=Wg(o,r,n,i,e.getUint32(44,!0),10,3174756917),i=Wg(i,o,r,n,e.getUint32(8,!0),15,718787259),n=Wg(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(Bg),this.buffer=new DataView(new ArrayBuffer(Lg)),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}}function zg(e,t,r,n,i,o){return((t=(t+e&4294967295)+(n+o&4294967295)&4294967295)<>>32-i)+r&4294967295}function jg(e,t,r,n,i,o,s){return zg(t&r|~t&n,e,t,i,o,s)}function qg(e,t,r,n,i,o,s){return zg(t&n|r&~n,e,t,i,o,s)}function Hg(e,t,r,n,i,o,s){return zg(t^r^n,e,t,i,o,s)}function Wg(e,t,r,n,i,o,s){return zg(r^(t|~n),e,t,i,o,s)}const Kg="function"==typeof TextEncoder?new TextEncoder:null,Vg=e=>{if("string"==typeof e){if(Kg)return Kg.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}`)},Qg=["in-region","cross-region","mobile","standard","legacy"],Gg=()=>{const e="undefined"!=typeof window&&window?.navigator?.userAgent?lg.parse(window.navigator.userAgent):void 0,t=e?.platform?.type;return"tablet"===t||"mobile"===t},Jg=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(Gg()?"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 ${Qg.join(", ")}, got ${t}`)}})))(e),r=()=>t().then(Mr),n=(e=>({apiVersion:"2006-03-01",base64Decoder:e?.base64Decoder??xe,base64Encoder:e?.base64Encoder??Re,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??md,extensions:e?.extensions??[],getAwsChunkedEncodingStream:e?.getAwsChunkedEncodingStream??Pe,httpAuthSchemeProvider:e?.httpAuthSchemeProvider??kd,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new ce},{schemeId:"aws.auth#sigv4a",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4a"),signer:new ue}],logger:e?.logger??new Hr,sdkStreamMixin:e?.sdkStreamMixin??He,serviceId:e?.serviceId??"S3",signerConstructor:e?.signerConstructor??ra,signingEscapePath:e?.signingEscapePath??!1,urlParser:e?.urlParser??xs,useArnRegion:e?.useArnRegion??!1,utf8Decoder:e?.utf8Decoder??Ae,utf8Encoder:e?.utf8Encoder??Ce}))(e);return{...n,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??Vg,credentialDefaultProvider:e?.credentialDefaultProvider??(e=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??hg({serviceId:n.serviceId,clientVersion:Bp}),eventStreamSerdeProvider:e?.eventStreamSerdeProvider??$g,maxAttempts:e?.maxAttempts??3,md5:e?.md5??Dg,region:e?.region??(i="Region is missing",()=>Promise.reject(i)),requestHandler:$e.create(e?.requestHandler??r),retryMode:e?.retryMode??(async()=>(await r()).retryMode||_s),sha1:e?.sha1??Jp,sha256:e?.sha256??ug,streamCollector:e?.streamCollector??Ue,streamHasher:e?.streamHasher??Ug,useDualstackEndpoint:e?.useDualstackEndpoint??(()=>Promise.resolve(false)),useFipsEndpoint:e?.useFipsEndpoint??(()=>Promise.resolve(false))};var i},Xg=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}},Zg=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}},Yg=e=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()});class em extends zt{constructor(...[e]){const t=Jg(e||{});var r;const n=function(e){const t=ke(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()=>As(await le(r)()):void 0,i=!!r,o={...e,endpoint:n,tls:t,isCustomEndpoint:i,useDualstackEndpoint:le(e.useDualstackEndpoint??!1),useFipsEndpoint:le(e.useFipsEndpoint??!1)};let s;return o.serviceConfiguredEndpoint=async()=>(e.serviceId&&!s&&(s=Es(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 fs(t);const e=await t();return fs(e)},useFipsEndpoint:async()=>{const e="string"==typeof t?t:await t();return!!hs(e)||("function"!=typeof r?Promise.resolve(!!r):r())}}})((e=>{const{retryStrategy:t}=e,r=le(e.maxAttempts??3);return{...e,maxAttempts:r,retryStrategy:async()=>t||(await le(e.retryMode)()===Ps.ADAPTIVE?new zs(r):new Ds(r))}})((i=n,{...i,requestChecksumCalculation:le(i.requestChecksumCalculation??G),responseChecksumValidation:le(i.responseChecksumValidation??J)}))))),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 lo((async e=>r().send(new n({Bucket:e,SessionMode:"ReadWrite"})))),bucketEndpoint:e.bucketEndpoint??!1}})(Sd(o),{session:[()=>this,Lp]}),a=((e,t)=>{const r={...Xg(e),...Lr(e),...F(e),...Zg(e)};return t.forEach((e=>e.configure(r))),{...e,...(i=r,{region:i.region()}),...Br(r),...(n=r,{httpHandler:n.httpHandler()}),...Yg(r)};var n,i})(s,e?.extensions||[]);super(a),this.config=a,this.middlewareStack.use((e=>({applyToStack:t=>{t.add(us(e),ls)}}))(this.config)),this.middlewareStack.use(Ys(this.config)),this.middlewareStack.use(ms(this.config)),this.middlewareStack.use(Ji(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}}),Xi)}})),this.middlewareStack.use(eo(this.config)),this.middlewareStack.use(((e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(he(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r}),fe)}}))(this.config,{httpAuthSchemeParametersProvider:yd,identityProviderConfigProvider:async e=>new Ye({"aws.auth#sigv4":e.credentials,"aws.auth#sigv4a":e.credentials})})),this.middlewareStack.use(we(this.config)),this.middlewareStack.use(Po(this.config)),this.middlewareStack.use(V(this.config)),this.middlewareStack.use(oo(this.config)),this.middlewareStack.use(bo(this.config)),this.middlewareStack.use((e=>({applyToStack:t=>{t.addRelativeTo(So(e),be)}}))(this.config))}destroy(){super.destroy()}}const tm={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0},rm=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?nm(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})}),tm)}});function nm(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 im extends(jt.classBuilder().ep({...Ed,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[me(r,this.serialize,this.deserialize),Os(r,e.getEndpointParameterInstructions()),Co(r)]})).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").f(void 0,void 0).ser(Gd).de(el).build()){}class om extends(jt.classBuilder().ep({...Ed,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[me(r,this.serialize,this.deserialize),Os(r,e.getEndpointParameterInstructions()),Qi(r,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC32","CRC32C","SHA256","SHA1"]}),rm(r),ao()]})).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").f(Bd,Ld).ser(Jd).de(tl).build()){}class sm extends(jt.classBuilder().ep({...Ed,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(e,t,r,n){return[me(r,this.serialize,this.deserialize),Os(r,e.getEndpointParameterInstructions()),Co(r)]})).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").f(void 0,void 0).ser(Xd).de(rl).build()){}class am extends(jt.classBuilder().ep({...Ed,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[me(r,this.serialize,this.deserialize),Os(r,e.getEndpointParameterInstructions()),Qi(r,{requestAlgorithmMember:"ChecksumAlgorithm",requestAlgorithmMemberHttpHeader:"x-amz-sdk-checksum-algorithm",requestChecksumRequired:!1}),ro(),Co(r),rm(r)]})).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").f(Vd,Kd).ser(Zd).de(nl).build()){}class cm{constructor(e){this.config=e,this.taskQueue=new p(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return a(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);""===a||a.endsWith("/")||(a+="/");const c=new em({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o}});try{let e,t=[],r=[],i=!0;for(;i;){const o=yield c.send(new sm({Bucket:n,Prefix:a,Delimiter:"/",ContinuationToken:e}));o.Contents&&(t=t.concat(o.Contents)),o.CommonPrefixes&&(r=r.concat(o.CommonPrefixes)),e=o.NextContinuationToken,i=!!e}let o=[];return t.forEach((e=>{if(!e.Key.endsWith("/")){const t=e.Key.substring(a.length);t.includes("/")||o.push({name:t,size:e.Size||0,type:"file",modified:e.LastModified?e.LastModified.toISOString():""})}})),r.forEach((e=>{const t=e.Prefix.substring(a.length).replace(/\/$/,"");t&&o.push({name:t,size:0,type:"folder",modified:""})})),console.log("File list:",o),o}catch(e){return console.error(e),[]}}))}deleteFile(e){return a(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 em({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 im({Bucket:n,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class um extends cm{constructor(e){super(e)}uploadFile(e,t){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){let{endpoint:r,region:n,bucketName:i,accessKeyId:o,secretAccessKey:s,dir:a}=this.config;const c=new em({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 am({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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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 em({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 om({Bucket:n,Key:c}));if(!e.Body)return console.error("No response body"),!1;const t=yield e.Body.transformToByteArray();return this.taskQueue.setDownloadedSize(t.length),t.buffer}catch(t){return console.error("Error downloading file:",t,e),!1}}))))))}))}}class dm{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.url=o,this.dir=s,this.taskQueue=new p(5)}retryOperation(e,t=0){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(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 a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){if(this.taskQueue.setDownloadedSize(0),console.log(t),-1===t.indexOf("."))return new ArrayBuffer(0);try{const r=btoa(this.username+":"+this.password);let n=this.url.endsWith("/")?this.url:this.url+"/",i=this.dir.startsWith("/")?this.dir.substring(1):this.dir;const o=yield e({url:n+i+"/"+t,method:"get",headers:{Authorization:"Basic "+r},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0,onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return o.status>=300?(console.error("Error occurred during file download:",o),!1):o.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return a(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).filter((t=>"."!==t.filename&&".."!==t.filename&&t.filename!==e)).map((e=>({name:e.basename,size:e.size||0,type:"directory"===e.type?"folder":"file",modified:e.lastmod})))}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 a(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 lm{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.refreshTokenPromise=null,this.taskQueue=new p(3)}retryOperation(e,t=3){return a(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return a(this,void 0,void 0,(function*(){try{return(yield e.get(`${this.url}/list`,{params:{dir:t},auth:{username:this.username,password:this.password}})).data.files.map((e=>({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modifiedTime})))||[]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return a(this,void 0,void 0,(function*(){try{return(yield e.delete(`${this.url}/delete`,{params:{dir:t.split("/").slice(0,-1).join("/")||"",filename:t.split("/").pop()},auth:{username:this.username,password:this.password}})).data.success}catch(e){return console.error("Error deleting file:",e),!1}}))}}class hm extends lm{constructor(e){super(e)}getAuthHeader(){return`Basic ${btoa(`${this.username}:${this.password}`)}`}uploadFile(t,r){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){try{const n=r.split("/").pop()||"",i=r.substring(0,r.lastIndexOf("/"))||"";let o=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const s=new FormData;s.append("file",o);const a=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(i)}`,s,{headers:{Authorization:this.getAuthHeader(),"Content-Type":"multipart/form-data"},maxContentLength:1/0,maxBodyLength:1/0});return!(a.status>=300)||(console.error("Error occurred during file upload:",a),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return a(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>a(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const r=t.split("/").pop()||"",n=t.substring(0,t.lastIndexOf("/"))||"",i=yield e({url:`${this.url}/download`,method:"GET",params:{dir:n,filename:r},headers:{Authorization:this.getAuthHeader()},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});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}}))))))}))}}const fm=["book","config","cover","font"];class pm{constructor(e,t,r){this.type=e,this.remote="dropbox"===e?new A(t,r):"microsoft"===e?new _(t,r):"google"===e?new C(t,r):"microsoft_exp"===e?new _(Object.assign(Object.assign({},t),{isExp:!0}),r):"google_exp"===e?new C(Object.assign(Object.assign({},t),{isExp:!0}),r):"s3compatible"===e?new um(t):"webdav"===e?new dm(t):"docker"===e?new hm(t):"boxnet"===e?new E(t,r):"mega"===e?new O(t):"adrive"===e?new k(t,r):"pcloud"===e?new N(t,r):new I}downloadFile(e,t){return a(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 a(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r,t+"/"+e)}))}deleteFile(e,t){return a(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 a(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}listFileInfos(e){return a(this,void 0,void 0,(function*(){return yield this.remote.listFileInfos(e)}))}isExist(e,t){return a(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}downloadAllFiles(){return a(this,void 0,void 0,(function*(){for(let e of fm){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,e)}}))}authToken(e){return a(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()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const gm={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 = ?"},mm={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},ym={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function vm(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const bm={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 wm,km={sqlStatement:{createTableStatement:vm({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:vm({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:vm({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:vm({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:vm({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:vm({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:vm({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:vm(gm),getByBookKeyStatement:vm(mm),getByBookKeysStatement:vm({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:vm(ym)},jsonToSqlite:vm({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:vm(bm)};class Sm{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 Em{static generateBook(e,t,r,n,i,o,s){return new Promise(((c,u)=>a(this,void 0,void 0,(function*(){try{let a,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 s.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 s.getMetadata(),m=g.cover;break;case"txt":g=yield s.getMetadata(o),f=g.charset}let y=t.toUpperCase();a=(new Date).getTime()+"",c(new Sm(a,u,d,h,r,m,y,l,n,p,i,f))}catch(e){console.error(e),u(e)}}))))}}wm=Em,Em.getRendition=(e,t,r)=>{let n,i=t.format.toUpperCase();var o,s;return"CACHE"===i?n=new r.CacheRender(e,t):"MOBI"===i||"AZW3"===i||"AZW"===i?n=new r.MobiRender(e,t):"EPUB"===i?n=new r.EpubRender(e,t):"TXT"===i?n=new r.TxtRender(e,t):"MD"===i?n=new r.MdRender(e,t):"PDF"===i?n=new r.PdfRender(e,t):"FB2"===i?n=new r.Fb2Render(e,t):"DOCX"===i?n=new r.DocxRender(e,t):"HTML"===i||"XHTML"===i||"MHTML"===i||"HTM"===i||"XML"===i?n=new r.HtmlRender(e,t):"CBR"!==i&&"CBT"!==i&&"CBZ"!==i&&"CB7"!==i||(n=new r.ComicRender((o=e,s=new ArrayBuffer(o.byteLength),new Uint8Array(s).set(new Uint8Array(o)),s),t)),n},Em.initMobileBook=(e,t,r,n,i,o,s,c,u,d)=>a(void 0,void 0,void 0,(function*(){try{window.ReactNativeWebView.postMessage(JSON.stringify({event:"user-agent",userAgent:navigator.userAgent}));const a=yield fetch(e);if(!a.ok)throw new Error(`Failed to download book: ${a.status} ${a.statusText}`);const l=yield a.arrayBuffer();window.ReactNativeWebView.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=l;let h=wm.getRendition(l,{format:t,readerMode:r,charset:n,animation:i,convertChinese:o,parserRegex:s,isDarkMode:u,isMobile:"yes",password:d},window.Kookit);window.rendition=h;let f=document.getElementById("page-area");t&&"TXT"===t.toUpperCase()?yield window.rendition.renderTo(f,c):yield window.rendition.renderTo(f),window.rendition.on("rendered",(()=>{let e=window.rendition.getPosition();"PDF"===t&&(e.chapterDocIndex=window.chapterDocIndex),window.ReactNativeWebView.postMessage(JSON.stringify({event:"content-loaded",bookLocation:e})),window.rendition.tranformText()})),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"}))}})),Em.addMobileBook=(e,t,r,n,i,o,s="")=>a(void 0,void 0,void 0,(function*(){var a;try{if(window.ReactNativeWebView.postMessage(JSON.stringify({event:"user-agent",userAgent:navigator.userAgent})),"PDF"===r.toUpperCase()&&i>314572800){t=t.replace(/\.[^/.]+$/,"");let e=r.toUpperCase(),s=(new Date).getTime()+"",a=new Sm(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===(a=window.ReactNativeWebView)||void 0===a||a.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=u;let d=wm.getRendition(u,{format:r.toUpperCase(),readerMode:"",charset:"",animation:"",convertChinese:"no",parserRegex:s||"",isDarkMode:"no",isMobile:"yes",password:""},window.Kookit);window.rendition=d,t=t.replace(/\.[^/.]+$/,"");let l=yield Em.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"}))}})),Em.precacheMobileBook=(e,t)=>a(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 xm=m.cloudUrl,Am=m.cloudCNUrl;class Tm{constructor(e,t){this.TokenService=e,this.ConfigService=t,this.baseUrl="china"===t.getItem("serverRegion")?Am:xm,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return a(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(this.baseUrl+"/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 a(this,void 0,void 0,(function*(){return Tm.requestQueue||(Tm.requestQueue=[]),new Promise(((t,r)=>{Tm.requestQueue.push({config:e,resolve:t,reject:r}),Tm.processingQueue||this.processQueue()}))}))}processQueue(){return a(this,void 0,void 0,(function*(){if(!Tm.processingQueue){Tm.processingQueue=!0;try{for(;Tm.requestQueue.length>0;){const e=Tm.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{Tm.processingQueue=!1}}}))}executeRequest(t){return a(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);if(t.baseURL=this.baseUrl,t.headers)t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r;else{let e=this.ConfigService.getItem("appVersion"),n=this.ConfigService.getItem("appPlatform");t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r,"X-App-Version":e||"1.0.0","X-App-Platform":n||"web"}}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 a(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>a(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,s)=>{let c=this.ConfigService.getItem("appVersion"),u=this.ConfigService.getItem("appPlatform");const d=new r(this.baseUrl+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+n,"X-Request-ID":i,"X-App-Version":c||"1.0.0","X-App-Platform":u||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});d.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),d.addEventListener("message",(e=>a(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(d.close(),o(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),d.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);o(t),d.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return a(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>a(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,s)=>a(this,void 0,void 0,(function*(){let s=this.ConfigService.getItem("appVersion"),c=this.ConfigService.getItem("appPlatform");var u=new o(this.baseUrl+e.url,{headers:{"Content-Type":"text/plain",Authorization:"Bearer "+r,"X-Request-ID":n,"X-App-Version":s||"1.0.0","X-App-Platform":c||"web"},payload:JSON.stringify(e.data),method:"POST"});u.addEventListener("message",(e=>a(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(u.close(),i(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),u.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),u.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const t=JSON.parse(e.data);i(t),u.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}Tm.processingQueue=!1,Tm.requestQueue=[];class Cm extends Tm{constructor(e,t){super(e,t)}getTransStream(e,t,r){return a(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 a(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 a(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 a(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 a(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 a(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 a(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 a(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 a(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 Rm extends Tm{constructor(e,t){super(e,t)}encryptToken(e){return a(this,void 0,void 0,(function*(){let t=e.token,r=f.encode(t),{extracted:n,remaining:i}=function(e){let t="",r="",n=[],i=1;for(;i<=e.length;)n.push(i-1),i*=2;for(let i=0;i-1){let r=t.split("#");e.encrypted_token=r[1]}const r={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};let n=yield this.requestWithRetry(r);if(t.indexOf("#")>-1){let e=t.split("#"),r=function(e,t){let r="",n=[],i=1,o=e.length+t.length;for(;i<=o;)n.push(i-1),i*=2;let s=0,a=0;for(let i=0;i{let r="";if("github"===e?r=`https://github.com/login/oauth/authorize?client_id=${y.githubClientId}&redirect_uri=${y.callbackUrl}&scope=${v.github.scopes.join(" ")}&response_type=code`:"google"===e?r=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${y.callbackUrl}&prompt=consent&response_type=code&client_id=${y.googleClientId}&scope=${v.google.scopes.join(" ")}&access_type=offline`:"facebook"===e?r=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${y.facebookClientId}&redirect_uri=${y.callbackUrl}&scope=&response_type=code`:"microsoft"===e&&(r=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${y.microsoftClientId}&scope=${v.microsoft.scopes.join(" ")}&response_type=code&redirect_uri=${y.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 _m{static CompareDatabase(e,t,r){return a(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 a(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:[],save:[],upload:[]},mapConfig:{update:[],delete:[],conflict:[],save:[],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 a(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 a(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 a(this,void 0,void 0,(function*(){let o=[];for(let t of u){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 u)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 a(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 a(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 a(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 Im=(Mm=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,t){localStorage.setItem(e,t)}static removeItem(e){localStorage.removeItem(e)}},Nm="browser",class extends Mm{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:Nm,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 Mm,Nm;class Fm{static saveAllToken(e){return a(this,void 0,void 0,(function*(){if(e)if(s){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 a(this,void 0,void 0,(function*(){if(s){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 a(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 a(this,void 0,void 0,(function*(){return JSON.parse((yield this.getAllToken())||"{}")[e]||null}))}static deleteToken(e){return a(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 a(this,void 0,void 0,(function*(){try{let t=yield this.getFingerprint();const r=yield Lm(t),n="undefined"!=typeof crypto&&crypto.subtle?yield function(e,t,r={alg:"HS256",typ:"JWT"}){return a(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=h((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<=iy}}function Iy(e){return function(t){return null==t?void 0:t[e]}}var My=Iy("byteLength"),Ny=_y(My),Fy=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var $y=Qm?function(e){return Ym?Ym(e)&&!xy(e):Ny(e)&&Fy.test(Km.call(e))}:Py(!1),Uy=Iy("length");function Ly(e,t){t=function(e){for(var t={},r=e.length,n=0;n":">",'"':""","'":"'","`":"`"},Rv=Tv(Cv),Ov=Tv(ov(Cv)),Pv=zy.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},_v=/(.)^/,Iv={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},Mv=/\\|'|\r|\n|\u2028|\u2029/g;function Nv(e){return"\\"+Iv[e]}var Fv=/^\s*(\w|\$)+\s*$/;var $v=0;function Uv(e,t,r,n,i){if(!(n instanceof t))return e.apply(r,i);var o=lv(e.prototype),s=e.apply(o,i);return sy(s)?s:o}var Lv=oy((function(e,t){var r=Lv.placeholder,n=function(){for(var i=0,o=t.length,s=Array(o),a=0;a1)zv(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 Vv=Lv(Kv,2);function Qv(e,t,r){t=Sv(t,r);for(var n,i=By(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(Wm.call(n,s,a),Oy))>=0?o+s:-1;for(o=e>0?s:a-1;o>=0&&o=3;return function(t,r,n,i){var o=!Dv(t)&&By(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 hb=oy((function(e,t,r){var n,i;return by(t)?i=t:(t=fv(t),n=t.slice(0,-1),t=t[t.length-1]),ib(e,(function(e){var o=i;if(!o){if(n&&n.length&&(e=pv(e,n)),null==e)return;o=e[t]}return null==o?o:o.apply(e,r)}))}));function fb(e,t){return ib(e,vv(t))}function pb(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=Dv(e)?e:iv(e)).length;ao&&(o=n);else t=Sv(t,r),nb(e,(function(e,r,n){((i=t(e,r,n))>s||i===-1/0&&o===-1/0)&&(o=e,s=i)}));return o}var gb=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;function mb(e){return e?Ay(e)?Wm.call(e):dy(e)?e.match(gb):Dv(e)?ib(e,mv):iv(e):[]}function yb(e,t,r){if(null==t||r)return Dv(e)||(e=iv(e)),e[xv(e.length-1)];var n=mb(e),i=Uy(n);t=Math.max(Math.min(t,i),0);for(var o=i-1,s=0;s1&&(n=bv(n,t[1])),t=Ky(e)):(n=Eb,t=zv(t,!1,!1),e=Object(e));for(var i=0,o=t.length;i1&&(r=t[1])):(t=ib(zv(t,!1,!1),String),n=function(e,r){return!lb(t,r)}),xb(e,n,r)}));function Tb(e,t,r){return Wm.call(e,0,Math.max(0,e.length-(null==t||r?1:t)))}function Cb(e,t,r){return null==e||e.length<1?null==t||r?void 0:[]:null==t||r?e[0]:Tb(e,e.length-t)}function Rb(e,t,r){return Wm.call(e,null==t||r?1:t)}var Ob=oy((function(e,t){return t=zv(t,!0,!0),cb(e,(function(e){return!lb(t,e)}))})),Pb=oy((function(e,t){return Ob(e,t)}));function _b(e,t,r,n){cy(t)||(n=r,r=t,t=!1),null!=r&&(r=Sv(r,n));for(var i=[],o=[],s=0,a=Uy(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=Av()-i;t>u?n=setTimeout(c,t-u):(n=null,r||(s=e.apply(a,o)),n||(o=a=null))},u=oy((function(u){return a=this,o=u,i=Av(),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 Lv(t,e)},negate:Wv,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:Kv,once:Vv,findKey:Qv,findIndex:Jv,findLastIndex:Xv,sortedIndex:Zv,indexOf:eb,lastIndexOf:tb,find:rb,detect:rb,findWhere:function(e,t){return rb(e,yv(t))},each:nb,forEach:nb,map:ib,collect:ib,reduce:sb,foldl:sb,inject:sb,reduceRight:ab,foldr:ab,filter:cb,select:cb,reject:function(e,t,r){return cb(e,Wv(Sv(t)),r)},every:ub,all:ub,some:db,any:db,contains:lb,includes:lb,include:lb,invoke:hb,pluck:fb,where:function(e,t){return cb(e,yv(t))},max:pb,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=Dv(e)?e:iv(e)).length;an||void 0===r)return 1;if(re.map((e=>e.name)),Db=e=>e.map((e=>e.key)),zb=(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 jb{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?zb(i,n).reverse():zb(i,n);if(2===t.sort){let r=Bb(e),n=Bb(e).sort();return 1===t.order?zb(n,r).reverse():zb(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=Db(e);return 1===t.order?zb(Lb.union(n,i),i).reverse():zb(Lb.union(n,i),i)}if(5===t.sort){let r=Db(e),n=(e=>Lb.sortBy(e.map((e=>({key:e.key,author:e.author}))),"author").map((e=>e.key)))(e);return 1===t.order?zb(n,r).reverse():zb(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=Db(e);return 1===t.order?zb(n,i).reverse():zb(n,i)}}static sortNotes(e,t,r=[]){if(3===t.sort){let r=Lb.clone(e).reverse(),n=Lb.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:e.chapterIndex}))));n=1===t.order?Lb.sortBy(n,"chapterIndex"):Lb.sortBy(n,"chapterIndex").reverse();let i=Lb.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=Lb.clone(e).reverse(),n=Lb.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=Lb.clone(e).reverse(),i=Lb.uniq(e.map((e=>{let t=Lb.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=Lb.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=Lb.clone(e).reverse(),n=Lb.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:parseInt(JSON.parse(e.cfi).chapterDocIndex)}))));n=1===t.order?Lb.sortBy(n,"chapterIndex"):Lb.sortBy(n,"chapterIndex").reverse();let i=Lb.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 qb{static getDefaultCss(e){return`::selection{background:#f3a6a68c}::-moz-selection{background:#f3a6a68c}.kookit-note:hover{cursor:pointer;}body,html{margin: 0px !important; padding: 0px !important; font-size: 18px;}.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"):""}px !important;line-height: ${e.getReaderConfig("lineHeight")||""} !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":""};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;word-wrap: break-word !important; writing-mode: horizontal-tb !important; `}}class Hb{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{Em as BookHelper,g as CommonTool,Im as ConfigService,b as KookitConfig,Pm as LoginHelper,Cm as ReaderRequest,Hb as SearchUtil,jb as SortUtil,km as SqlStatement,qb as StyleHelper,_m as SyncHelper,pm as SyncUtil,Rm as ThirdpartyRequest,Fm as TokenService,Om as UserRequest}; diff --git a/src/assets/lib/kookit-extra.min.mjs b/src/assets/lib/kookit-extra.min.mjs index 56b5563e..1201ce54 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 l,GetObjectCommand as c}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{SSE as g}from"sse.js";import m from"electron-store";import v from"node-machine-id";function k(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 T=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 b{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.hasFailedTasks=!1,this.downloadedSize=0,this.maxConcurrency=e}addTask(e){return k(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,i)=>{const r=()=>k(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 this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(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 console.log("Total items fetched:",r),[...new Set(r.map((e=>({name:e.name,size:e.size||0,type:e[".tag"],modified:e.client_modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(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 k(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=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${S}&redirect_uri=${E}`}}const I=r(o.pipeline);class P extends C{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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});let d=0;return a.data.on("data",(e=>{d+=e.length,this.taskQueue.setDownloadedSize(d)})),yield I(a.data,n),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class Q{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new b(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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=()=>k(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,r){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;const s=yield this.getClient(),n=t.createWriteStream(i.join(this.storagePath,r)),a=()=>k(this,void 0,void 0,(function*(){s.trackProgress((e=>{this.taskQueue.setDownloadedSize(e.bytes||0)})),yield s.downloadTo(n,o+"/"+e),s.trackProgress()}));try{return yield a(),!0}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return k(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=()=>k(this,void 0,void 0,(function*(){return yield i.list(t+"/"+e)}));try{return(yield r()).map((e=>({name:e.name,size:e.size||0,type:e.isFile?"file":"folder",modified:e.modifiedAt?e.modifiedAt.toISOString():""})))}catch(e){return console.error(e),[]}}))}deleteFile(e){return k(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=()=>k(this,void 0,void 0,(function*(){yield i.remove(t+"/"+e)}));try{return yield r(),!0}catch(e){return console.error(e),!1}}))}}class z{constructor(e,t){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new b(3),this.isExp=this.config.isExp||!1,this.baseUrl=this.isExp?"https://graph.microsoft.com/v1.0/me/drive/root":"https://graph.microsoft.com/v1.0/me/drive/special/approot",void 0===this.config.baseFolder?this.baseFolder=this.isExp?"KoodoReader":"":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let r,o=[];if(""===t)r=`${this.baseUrl}/children`;else{const e=encodeURIComponent(t);r=`${this.baseUrl}:/${e}:/children`}for(;r;){const t=yield e.get(r,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(t.status>=300)break;const s=t.data.value||[];o=o.concat(s),r=t.data["@odata.nextLink"]||""}return console.log("All items fetched:",o),[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:e.folder?"folder":"file",modified:e.lastModifiedDateTime}))))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const r=yield e.delete(`${this.baseUrl}:/${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 k(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=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${O}&scope=${this.isExp?"files.readwrite.all":"files.readwrite.appfolder"} offline_access&response_type=code&redirect_uri=${E}`}}const L=209715200;class $ extends z{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){var s;let n=null;try{const s=yield this.refreshToken();for(o=this.baseFolder+"/"+o;o.startsWith("/");)o=o.substring(1);const a=i.join(this.storagePath,r),d=yield this.getFileSize(a),l=o.split(".").pop(),c=(T(l||""),`${this.baseUrl}:/${o}:/createUploadSession`),h=(yield e.post(c,{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(L);for(;uthis.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken();for(r=this.baseFolder+"/"+r;r.startsWith("/");)r=r.substring(1);const n=`${this.baseUrl}:/${r}:/content`;let a=(yield fetch(n,{headers:{Authorization:"Bearer "+s},redirect:"manual"})).headers.get("location");if(a){const r=yield e.get(a,{responseType:"stream"});let s=0;const n=t.createWriteStream(i.join(this.storagePath,o));return r.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),yield new Promise(((e,t)=>{r.data.pipe(n),n.on("finish",(()=>{e()})),n.on("error",t)})),!0}return!1}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return k(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class j{constructor(e,t){this.isExp=!1,this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new b(3),this.isExp=this.config.isExp||!1,void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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&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 k(this,void 0,void 0,(function*(){t=this.baseFolder+"/"+t;const i=yield this.refreshToken();if(""===t)return"root";const r=t.split("/").filter((e=>""!==e.trim()));let o="root";for(const t of r){let r=yield this.getFolderId(t,o);if(!r){const s={name:t,mimeType:"application/vnd.google-apps.folder",parents:[o]};try{r=(yield e.post("https://www.googleapis.com/drive/v3/files",s,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error(`Error occurred during folder creation for ${t}:`,e),e}}o=r}return o}))}getFolderId(t,i){return k(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t=encodeURIComponent(t)}'+and+mimeType='application/vnd.google-apps.folder'+and+'${i}'+in+parents&fields=files(id,name)`;try{const t=(yield e.get(o,{headers:{Authorization:`Bearer ${r}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(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&fields=nextPageToken,files(id,name,size,mimeType)&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 console.log("Total items fetched:",o),[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:"application/vnd.google-apps.folder"===e.mimeType?"folder":"file",modified:e.modifiedTime}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return k(this,void 0,void 0,(function*(){const i=t.split("/")[1],r=yield this.checkFolder(t),o=yield this.refreshToken(),s=yield this.getFileId(i,r);if(""===s)return console.error("File not found:",i),!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 k(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=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${E}&prompt=consent&response_type=code&client_id=${_}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class D extends j{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken();let n=r.split("/").pop(),a=o.split(".").pop(),d=T(a||""),l=o.split("/").slice(0,-1).join("/"),c=yield this.checkFolder(l),h=yield this.getFileId(n||"",c);const u={mimeType:d,name:n,parents:[c]},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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken();let n=r.split("/").pop(),a=r.split("/").slice(0,-1).join("/"),d=yield this.checkFolder(a),l=yield this.getFileId(n||"",d);if(!l)return console.error("File not found"),!0;const c=`https://www.googleapis.com/drive/v3/files/${l}?alt=media`;return new Promise((r=>{const n=t.createWriteStream(i.join(this.storagePath,o));e({url:c,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+s},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{let t=0;e.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),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 k(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class B{constructor(e){this.config=e,this.taskQueue=new b(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return k(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 l=d+"/"+e;for(;l.startsWith("/");)l=l.substring(1);""===l||l.endsWith("/")||(l+="/");const c=new n({endpoint:t,region:i,credentials:{accessKeyId:o,secretAccessKey:s}});try{let e,t=[],i=[],o=!0;for(;o;){const s=yield c.send(new a({Bucket:r,Prefix:l,Delimiter:"/",ContinuationToken:e}));s.Contents&&(t=t.concat(s.Contents)),s.CommonPrefixes&&(i=i.concat(s.CommonPrefixes)),e=s.NextContinuationToken,o=!!e}let s=[];return t.forEach((e=>{if(!e.Key.endsWith("/")){const t=e.Key.substring(l.length);t.includes("/")||s.push({name:t,size:e.Size||0,type:"file",modified:e.LastModified?e.LastModified.toISOString():""})}})),i.forEach((e=>{const t=e.Prefix.substring(l.length).replace(/\/$/,"");t&&s.push({name:t,size:0,type:"folder",modified:""})})),console.log("File list:",s),s}catch(e){return console.error(e),[]}}))}deleteFile(e){return k(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 l=new n({endpoint:t,region:i,credentials:{accessKeyId:o,secretAccessKey:s}});let c=a+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield l.send(new d({Bucket:r,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class W extends B{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,r){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){let{endpoint:o,region:s,bucketName:a,accessKeyId:d,secretAccessKey:c,dir:h}=this.config;const u=new n({endpoint:o,region:s,credentials:{accessKeyId:d,secretAccessKey:c}});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 l({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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let{endpoint:o,region:s,bucketName:a,accessKeyId:d,secretAccessKey:l,dir:h}=this.config;h=h&&"KoodoReader"===this.baseFolder?h:this.baseFolder;const u=(e,t,i,r)=>new Promise(((o,s)=>k(this,void 0,void 0,(function*(){const s=yield e.send(new c({Bucket:t,Key:i}));let n=0;s.Body?(s.Body.on("data",(e=>{n+=e.length,this.taskQueue.setDownloadedSize(n)})),s.Body.pipe(r),r.on("finish",(e=>{e&&o(!1),o(!0)}))):o(!1)})))),p=()=>new Promise(((c,p)=>{const f=new n({region:s,endpoint:o,credentials:{accessKeyId:d,secretAccessKey:l}});let y=t.createWriteStream(i.join(this.storagePath,r)),g=h+"/"+e;for(;g.startsWith("/");)g=g.substring(1);u(f,a,g,y).then((e=>{c(!0)})).catch((e=>{console.error(e),c(!1)}))}));try{return yield p()}catch(e){return console.error(e),!1}}))))))}))}}class M{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 b(5)}retryOperation(e,t=0){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){if(this.taskQueue.setDownloadedSize(0),-1===e.indexOf("."))return new ArrayBuffer(0);try{if(!1===(yield this.client.exists(this.dir+"/"+e)))return!0;let o=0,s=t.createWriteStream(i.join(this.storagePath,r)),n=this.client.createReadStream(this.dir+"/"+e);return n.on("data",(e=>{o+=e.length,this.taskQueue.setDownloadedSize(o)})),n.pipe(s),new Promise(((e,t)=>{s.on("finish",(()=>{e(!0)})),s.on("error",(t=>{e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return k(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).filter((t=>"."!==t.filename&&".."!==t.filename&&t.filename!==e)).map((e=>({name:e.basename,size:e.size||0,type:"directory"===e.type?"folder":"file",modified:e.lastmod})))}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 k(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 b(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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)=>k(this,void 0,void 0,(function*(){let a=t.createReadStream(i.join(this.storagePath,e)),d="/"+o+"/"+r,l="/"+o+"/"+i.dirname(r);(yield s.exists(l))||(yield s.mkdir(l,!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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>k(this,void 0,void 0,(function*(){let a="/"+o+"/"+e,d=i.join(this.storagePath,r),l=t.createWriteStream(d);s.get(a,l).then((()=>{this.taskQueue.setDownloadedSize(l.bytesWritten||0),n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return k(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)=>k(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=>({name:e.name,size:e.size||0,type:"d"===e.type?"folder":"file",modified:e.modifyTime}))))})).catch((e=>k(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 k(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 K{downloadFile(e,t){return k(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return k(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return k(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return k(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class q{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new b(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(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);console.log(o,"folderId");let 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}`}});console.log("Response data:",t.data);const r=t.data.entries||[];s=s.concat(r),n+=r.length,a=r.length===d&&t.data.total_count>n}return console.log("All items:",s),[...new Set(s.map((e=>({name:e.name,size:e.size||0,type:e.type,modified:e.content_modified_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(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 k(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=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:R,redirect_uri:E,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class U extends q{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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 l=yield this.getFolderIdByPath(d);if(!l)throw new Error("Folder not found");const c=yield this.listFiles(n);c.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(n+"/"+a));const h=new f,u=JSON.stringify({name:a,parent:{id:l}});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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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 l=yield this.getFolderIdByPath(d);if(!l)return console.error("Folder not found"),!0;const c=`https://api.box.com/2.0/folders/${l}/items?fields=id,name&type=file&limit=1000`,h=(yield e.get(c,{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)=>{let s=0;const n=t.createWriteStream(i.join(this.storagePath,o));u.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),u.data.pipe(n),n.on("finish",e),n.on("error",r)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class J{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new b(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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 k(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 k(this,void 0,void 0,(function*(){const i=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(i))return yield this.folderCreationLocks.get(i);const r=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return k(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=>({name:e.name,size:e.size||0,type:e.directory?"folder":"file",modified:e.timestamp?new Date(1e3*e.timestamp).toISOString():""})))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return k(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 H extends J{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,r){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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)),l=t.statSync(i.join(this.storagePath,e)).size;return yield o.upload({name:n,size:l},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,r){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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));let l=0;return new Promise((e=>{const t=a.download();t.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),t.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 V{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new b(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=5){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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 k(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(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(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 console.log("All items:",s),[...new Set(s.map((e=>({name:e.name,size:e.size,type:e.type,modified:e.updated_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(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 k(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 k(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=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:A,redirect_uri:E,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class X extends V{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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 l=yield this.getFolderIdByPath(this.baseFolder+"/"+a),c=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:l,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}=c.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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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"}}),l=yield e({url:d.data.url,method:"get",responseType:"stream"});let c=0;const h=t.createWriteStream(i.join(this.storagePath,o));return l.data.on("data",(e=>{c+=e.length,this.taskQueue.setDownloadedSize(c)})),l.data.pipe(h),new Promise((e=>{h.on("finish",(()=>{e(!0)})),h.on("error",(t=>{console.error("Error occurred during file download:",t),e(!1)}))}))}catch(e){return console.error("Error downloading file:",e),!1}}))))))}))}}class Y{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new b(3)}retryOperation(e,t=5){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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 k(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(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(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=>({name:e.name,size:e.size||0,type:e.isfolder?"folder":"file",modified:e.modified})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(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 k(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:E,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${x}&response_type=code&redirect_uri=${E}`}}class G extends Y{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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),l=t.statSync(a),c=i.basename(r),h=yield e({method:"put",url:"https://api.pcloud.com/uploadfile",params:{access_token:s,path:`/${n}`,renew:1,filename:c},data:d,headers:{"Content-Length":l.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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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),l=`https://${n.data.hosts[0]}${n.data.path}`,c=yield e({method:"get",url:l,responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});return new Promise((e=>{let t=0;c.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),c.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}}))))))}))}}class Z{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.refreshTokenPromise=null,this.taskQueue=new b(3)}retryOperation(e,t=3){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(this,void 0,void 0,(function*(){try{return(yield e.get(`${this.url}/list`,{params:{dir:t},auth:{username:this.username,password:this.password}})).data.files.map((e=>({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modifiedTime})))||[]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(this,void 0,void 0,(function*(){try{return(yield e.delete(`${this.url}/delete`,{params:{dir:t.split("/").slice(0,-1).join("/")||"",filename:t.split("/").pop()},auth:{username:this.username,password:this.password}})).data.success}catch(e){return console.error("Error deleting file:",e),!1}}))}}const ee=r(o.pipeline);class te extends Z{constructor(e,t){super(e),this.storagePath=t}getAuthHeader(){return`Basic ${btoa(`${this.username}:${this.password}`)}`}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){try{o.split("/").pop();const s=o.substring(0,o.lastIndexOf("/"))||"",n=t.createReadStream(i.join(this.storagePath,r)),a=new f;a.append("file",n);const d=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(s)}`,a,{headers:Object.assign(Object.assign({},a.getHeaders()),{Authorization:this.getAuthHeader()}),maxContentLength:1/0,maxBodyLength:1/0});return!(d.status>=300)||(console.error("Error occurred during file upload:",d),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=r.split("/").pop()||"",n=r.substring(0,r.lastIndexOf("/"))||"",a=t.createWriteStream(i.join(this.storagePath,o)),d=yield e({url:`${this.url}/download`,method:"GET",params:{dir:n,filename:s},headers:{Authorization:this.getAuthHeader()},maxContentLength:1/0,maxBodyLength:1/0,responseType:"stream"});if(d.status>=300)return console.error("Error occurred during file download:",d),a.destroy(),t.existsSync(i.join(this.storagePath,o))&&t.unlinkSync(i.join(this.storagePath,o)),!1;let l=0;return d.data.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),yield ee(d.data,a),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}const ie=["book","config","cover","font"];class re{constructor(e,t,i,r){this.type=e,this.storagePath=i,this.remote="dropbox"===e?new P(t,i,r):"microsoft"===e?new $(t,i,r):"google"===e?new D(t,i,r):"microsoft_exp"===e?new $(Object.assign(Object.assign({},t),{isExp:!0}),i,r):"google_exp"===e?new D(Object.assign(Object.assign({},t),{isExp:!0}),i,r):"s3compatible"===e?new W(t,i):"webdav"===e?new M(t,i):"docker"===e?new te(t,i):"ftp"===e?new Q(t,i):"sftp"===e?new N(t,i):"boxnet"===e?new U(t,i,r):"mega"===e?new H(t,i):"adrive"===e?new X(t,i,r):"pcloud"===e?new G(t,i,r):new K}downloadFile(e,r,o){return k(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 k(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(i+"/"+e,i+"/"+t)}))}deleteFile(e,t){return k(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 k(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}listFiles(e){return k(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}listFileInfos(e){return k(this,void 0,void 0,(function*(){return yield this.remote.listFileInfos(e)}))}downloadAllFiles(){return k(this,void 0,void 0,(function*(){for(let e of ie){let t=yield this.listFiles(e);for(let i of t)yield this.downloadFile(i,i,e)}}))}authToken(e){return k(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()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const oe={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 = ?"},se={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},ne={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function ae(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const de={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 le={sqlStatement:{createTableStatement:ae({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:ae({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:ae({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:ae({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:ae({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:ae({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:ae({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:ae(oe),getByBookKeyStatement:ae(se),getByBookKeysStatement:ae({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:ae(ne)},jsonToSqlite:ae({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:ae(de)};const ce=F,he=w;class ue{constructor(e,t){this.TokenService=e,this.ConfigService=t,this.baseUrl="china"===t.getItem("serverRegion")?he:ce,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return k(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(this.baseUrl+"/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 k(this,void 0,void 0,(function*(){return ue.requestQueue||(ue.requestQueue=[]),new Promise(((t,i)=>{ue.requestQueue.push({config:e,resolve:t,reject:i}),ue.processingQueue||this.processQueue()}))}))}processQueue(){return k(this,void 0,void 0,(function*(){if(!ue.processingQueue){ue.processingQueue=!0;try{for(;ue.requestQueue.length>0;){const e=ue.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{ue.processingQueue=!1}}}))}executeRequest(t){return k(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);if(t.baseURL=this.baseUrl,t.headers)t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=i;else{let e=this.ConfigService.getItem("appVersion"),r=this.ConfigService.getItem("appPlatform");t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":i,"X-App-Version":e||"1.0.0","X-App-Platform":r||"web"}}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 k(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>k(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)=>{let a=this.ConfigService.getItem("appVersion"),d=this.ConfigService.getItem("appPlatform");const l=new i(this.baseUrl+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+r,"X-Request-ID":o,"X-App-Version":a||"1.0.0","X-App-Platform":d||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});l.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),l.addEventListener("message",(e=>k(this,void 0,void 0,(function*(){if(!e.data)return;const i=JSON.parse(e.data);i.done?(l.close(),s(i)):(402===i.code&&(yield this.refreshUserToken()),t(i.data))})))),l.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);s(t),l.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return k(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>k(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)=>k(this,void 0,void 0,(function*(){let s=this.ConfigService.getItem("appVersion"),n=this.ConfigService.getItem("appPlatform");var a=new g(this.baseUrl+e.url,{headers:{"Content-Type":"text/plain",Authorization:"Bearer "+i,"X-Request-ID":r,"X-App-Version":s||"1.0.0","X-App-Platform":n||"web"},payload:JSON.stringify(e.data),method:"POST"});a.addEventListener("message",(e=>k(this,void 0,void 0,(function*(){if(!e.data)return;const i=JSON.parse(e.data);i.done?(a.close(),o(i)):(402===i.code&&(yield this.refreshUserToken()),t(i.data))})))),a.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),a.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const t=JSON.parse(e.data);o(t),a.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}ue.processingQueue=!1,ue.requestQueue=[];class pe extends ue{constructor(e,t){super(e,t)}encryptToken(e){return k(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 k(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 k(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 k(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/refresh_token",data:e};return yield this.requestWithRetry(t)}))}getSyncData(){return k(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_data"})}))}updateSyncData(e){return k(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 fe=new m;const ye=(ge=class{static getItem(e){return fe.get(e)}static setItem(e,t){fe.set(e,t)}static removeItem(e){fe.delete(e)}},me="desktop",class extends ge{static getReaderConfig(e){return JSON.parse(this.getItem("readerConfig")||"{}")[e]}static setReaderConfig(e,t,i=!0){let r=JSON.parse(this.getItem("readerConfig")||"{}");r[e]=t,this.setItem("readerConfig",JSON.stringify(r)),i&&this.setSyncRecord({type:"config",catergory:"readerConfig",name:me,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 i=this.getAllListConfig(t);const r=i.indexOf(e);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 ge,me;let ve;const ke=new Uint8Array(16);function Te(){if(!ve&&(ve="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ve))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ve(ke)}const be=[];for(let e=0;e<256;++e)be.push((e+256).toString(16).slice(1));var Fe={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function we(e,t,i){if(Fe.randomUUID&&!t&&!e)return Fe.randomUUID();const r=(e=e||{}).random||(e.rng||Te)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){i=i||0;for(let e=0;e<16;++e)t[i+e]=r[e];return t}return function(e,t=0){return be[e[t+0]]+be[e[t+1]]+be[e[t+2]]+be[e[t+3]]+"-"+be[e[t+4]]+be[e[t+5]]+"-"+be[e[t+6]]+be[e[t+7]]+"-"+be[e[t+8]]+be[e[t+9]]+"-"+be[e[t+10]]+be[e[t+11]]+be[e[t+12]]+be[e[t+13]]+be[e[t+14]]+be[e[t+15]]}(r)}const Ee=new m;class Se{static encrypt(e,t){let i="";for(let r=0;r"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,b={_chars:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",encode(e){if("string"!=typeof e)throw new Error("Input must be a string");let t="",i=0;const r=this._stringToUtf8Bytes(e),o=r.length;for(;i>2,d=(3&e)<<4|s>>4,l=(15&s)<<2|n>>6,c=63&n;t+=this._chars.charAt(a),t+=this._chars.charAt(d),t+=i-2>=o?"=":this._chars.charAt(l),t+=i-1>=o?"=":this._chars.charAt(c)}return t},decode(e){if("string"!=typeof e)throw new Error("Input must be a string");if((e=e.replace(/[^A-Za-z0-9+/]/g,"")).length%4!=0)throw new Error("Invalid Base64 string length");const t=[];let i=0;const r=e.length;for(;i>4,d=(15&o)<<4|s>>2,l=(3&s)<<6|n;t.push(a),-1!==s&&t.push(d),-1!==n&&t.push(l)}return this._utf8BytesToString(t)},_stringToUtf8Bytes(e){const t=[];for(let i=0;i>6),t.push(128|63&r);else if(55296==(64512&r)&&i+1>18),t.push(128|e>>12&63),t.push(128|e>>6&63),t.push(128|63&e)}else t.push(239,191,189),i--}else t.push(224|r>>12),t.push(128|r>>6&63),t.push(128|63&r)}return t},_utf8BytesToString(e){let t="",i=0;for(;i65535){const i=e-65536;t+=String.fromCharCode(55296|i>>10),t+=String.fromCharCode(56320|1023&i)}else t+=String.fromCharCode(e)}else t+="�"}else t+="�"}return t},encodeURL(e){return this.encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},decodeURL(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return this.decode(e)}};class w{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.hasFailedTasks=!1,this.downloadedSize=0,this.maxConcurrency=e}addTask(e){return k(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,i)=>{const r=()=>k(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 this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(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 console.log("Total items fetched:",r),[...new Set(r.map((e=>({name:e.name,size:e.size||0,type:e[".tag"],modified:e.client_modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(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 k(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=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:S,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${x}&redirect_uri=${S}`}}const P=r(o.pipeline);class Q extends I{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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});let d=0;return a.data.on("data",(e=>{d+=e.length,this.taskQueue.setDownloadedSize(d)})),yield P(a.data,n),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class z{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new w(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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=()=>k(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,r){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;const s=yield this.getClient(),n=t.createWriteStream(i.join(this.storagePath,r)),a=()=>k(this,void 0,void 0,(function*(){s.trackProgress((e=>{this.taskQueue.setDownloadedSize(e.bytes||0)})),yield s.downloadTo(n,o+"/"+e),s.trackProgress()}));try{return yield a(),!0}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return k(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=()=>k(this,void 0,void 0,(function*(){return yield i.list(t+"/"+e)}));try{return(yield r()).map((e=>({name:e.name,size:e.size||0,type:e.isFile?"file":"folder",modified:e.modifiedAt?e.modifiedAt.toISOString():""})))}catch(e){return console.error(e),[]}}))}deleteFile(e){return k(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=()=>k(this,void 0,void 0,(function*(){yield i.remove(t+"/"+e)}));try{return yield r(),!0}catch(e){return console.error(e),!1}}))}}class L{constructor(e,t){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new w(3),this.isExp=this.config.isExp||!1,this.baseUrl=this.isExp?"https://graph.microsoft.com/v1.0/me/drive/root":"https://graph.microsoft.com/v1.0/me/drive/special/approot",void 0===this.config.baseFolder?this.baseFolder=this.isExp?"KoodoReader":"":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let r,o=[];if(""===t)r=`${this.baseUrl}/children`;else{const e=encodeURIComponent(t);r=`${this.baseUrl}:/${e}:/children`}for(;r;){const t=yield e.get(r,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(t.status>=300)break;const s=t.data.value||[];o=o.concat(s),r=t.data["@odata.nextLink"]||""}return console.log("All items fetched:",o),[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:e.folder?"folder":"file",modified:e.lastModifiedDateTime}))))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const r=yield e.delete(`${this.baseUrl}:/${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 k(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=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:S,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${O}&scope=${this.isExp?"files.readwrite.all":"files.readwrite.appfolder"} offline_access&response_type=code&redirect_uri=${S}`}}const $=209715200;class j extends L{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){var s;let n=null;try{const s=yield this.refreshToken();for(o=this.baseFolder+"/"+o;o.startsWith("/");)o=o.substring(1);const a=i.join(this.storagePath,r),d=yield this.getFileSize(a),l=o.split(".").pop(),c=(T(l||""),`${this.baseUrl}:/${o}:/createUploadSession`),h=(yield e.post(c,{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($);for(;uthis.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken();for(r=this.baseFolder+"/"+r;r.startsWith("/");)r=r.substring(1);const n=`${this.baseUrl}:/${r}:/content`;let a=(yield fetch(n,{headers:{Authorization:"Bearer "+s},redirect:"manual"})).headers.get("location");if(a){const r=yield e.get(a,{responseType:"stream"});let s=0;const n=t.createWriteStream(i.join(this.storagePath,o));return r.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),yield new Promise(((e,t)=>{r.data.pipe(n),n.on("finish",(()=>{e()})),n.on("error",t)})),!0}return!1}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return k(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class D{constructor(e,t){this.isExp=!1,this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new w(3),this.isExp=this.config.isExp||!1,void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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&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 k(this,void 0,void 0,(function*(){t=this.baseFolder+"/"+t;const i=yield this.refreshToken();if(""===t)return"root";const r=t.split("/").filter((e=>""!==e.trim()));let o="root";for(const t of r){let r=yield this.getFolderId(t,o);if(!r){const s={name:t,mimeType:"application/vnd.google-apps.folder",parents:[o]};try{r=(yield e.post("https://www.googleapis.com/drive/v3/files",s,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error(`Error occurred during folder creation for ${t}:`,e),e}}o=r}return o}))}getFolderId(t,i){return k(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t=encodeURIComponent(t)}'+and+mimeType='application/vnd.google-apps.folder'+and+'${i}'+in+parents&fields=files(id,name)`;try{const t=(yield e.get(o,{headers:{Authorization:`Bearer ${r}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(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&fields=nextPageToken,files(id,name,size,mimeType)&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 console.log("Total items fetched:",o),[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:"application/vnd.google-apps.folder"===e.mimeType?"folder":"file",modified:e.modifiedTime}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return k(this,void 0,void 0,(function*(){const i=t.split("/")[1],r=yield this.checkFolder(t),o=yield this.refreshToken(),s=yield this.getFileId(i,r);if(""===s)return console.error("File not found:",i),!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 k(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=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:S,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${S}&prompt=consent&response_type=code&client_id=${C}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class B extends D{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken();let n=r.split("/").pop(),a=o.split(".").pop(),d=T(a||""),l=o.split("/").slice(0,-1).join("/"),c=yield this.checkFolder(l),h=yield this.getFileId(n||"",c);const u={mimeType:d,name:n,parents:[c]},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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken();let n=r.split("/").pop(),a=r.split("/").slice(0,-1).join("/"),d=yield this.checkFolder(a),l=yield this.getFileId(n||"",d);if(!l)return console.error("File not found"),!0;const c=`https://www.googleapis.com/drive/v3/files/${l}?alt=media`;return new Promise((r=>{const n=t.createWriteStream(i.join(this.storagePath,o));e({url:c,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+s},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{let t=0;e.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),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 k(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class W{constructor(e){this.config=e,this.taskQueue=new w(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return k(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 l=d+"/"+e;for(;l.startsWith("/");)l=l.substring(1);""===l||l.endsWith("/")||(l+="/");const c=new n({endpoint:t,region:i,credentials:{accessKeyId:o,secretAccessKey:s}});try{let e,t=[],i=[],o=!0;for(;o;){const s=yield c.send(new a({Bucket:r,Prefix:l,Delimiter:"/",ContinuationToken:e}));s.Contents&&(t=t.concat(s.Contents)),s.CommonPrefixes&&(i=i.concat(s.CommonPrefixes)),e=s.NextContinuationToken,o=!!e}let s=[];return t.forEach((e=>{if(!e.Key.endsWith("/")){const t=e.Key.substring(l.length);t.includes("/")||s.push({name:t,size:e.Size||0,type:"file",modified:e.LastModified?e.LastModified.toISOString():""})}})),i.forEach((e=>{const t=e.Prefix.substring(l.length).replace(/\/$/,"");t&&s.push({name:t,size:0,type:"folder",modified:""})})),console.log("File list:",s),s}catch(e){return console.error(e),[]}}))}deleteFile(e){return k(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 l=new n({endpoint:t,region:i,credentials:{accessKeyId:o,secretAccessKey:s}});let c=a+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield l.send(new d({Bucket:r,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class M extends W{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,r){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){let{endpoint:o,region:s,bucketName:a,accessKeyId:d,secretAccessKey:c,dir:h}=this.config;const u=new n({endpoint:o,region:s,credentials:{accessKeyId:d,secretAccessKey:c}});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 l({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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let{endpoint:o,region:s,bucketName:a,accessKeyId:d,secretAccessKey:l,dir:h}=this.config;h=h&&"KoodoReader"===this.baseFolder?h:this.baseFolder;const u=(e,t,i,r)=>new Promise(((o,s)=>k(this,void 0,void 0,(function*(){const s=yield e.send(new c({Bucket:t,Key:i}));let n=0;s.Body?(s.Body.on("data",(e=>{n+=e.length,this.taskQueue.setDownloadedSize(n)})),s.Body.pipe(r),r.on("finish",(e=>{e&&o(!1),o(!0)}))):o(!1)})))),p=()=>new Promise(((c,p)=>{const f=new n({region:s,endpoint:o,credentials:{accessKeyId:d,secretAccessKey:l}});let y=t.createWriteStream(i.join(this.storagePath,r)),g=h+"/"+e;for(;g.startsWith("/");)g=g.substring(1);u(f,a,g,y).then((e=>{c(!0)})).catch((e=>{console.error(e),c(!1)}))}));try{return yield p()}catch(e){return console.error(e),!1}}))))))}))}}class N{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 w(5)}retryOperation(e,t=0){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){if(console.log(e),this.taskQueue.setDownloadedSize(0),-1===e.indexOf("."))return new ArrayBuffer(0);try{if(!1===(yield this.client.exists(this.dir+"/"+e)))return!0;let o=0,s=t.createWriteStream(i.join(this.storagePath,r)),n=this.client.createReadStream(this.dir+"/"+e);return n.on("data",(e=>{o+=e.length,this.taskQueue.setDownloadedSize(o)})),n.pipe(s),new Promise(((e,t)=>{s.on("finish",(()=>{e(!0)})),s.on("error",(t=>{e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return k(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).filter((t=>"."!==t.filename&&".."!==t.filename&&t.filename!==e)).map((e=>({name:e.basename,size:e.size||0,type:"directory"===e.type?"folder":"file",modified:e.lastmod})))}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 k(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 K{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new w(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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)=>k(this,void 0,void 0,(function*(){let a=t.createReadStream(i.join(this.storagePath,e)),d="/"+o+"/"+r,l="/"+o+"/"+i.dirname(r);(yield s.exists(l))||(yield s.mkdir(l,!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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>k(this,void 0,void 0,(function*(){let a="/"+o+"/"+e,d=i.join(this.storagePath,r),l=t.createWriteStream(d);s.get(a,l).then((()=>{this.taskQueue.setDownloadedSize(l.bytesWritten||0),n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return k(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)=>k(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=>({name:e.name,size:e.size||0,type:"d"===e.type?"folder":"file",modified:e.modifyTime}))))})).catch((e=>k(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 k(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 q{downloadFile(e,t){return k(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return k(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return k(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return k(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class U{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new w(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(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);console.log(o,"folderId");let 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}`}});console.log("Response data:",t.data);const r=t.data.entries||[];s=s.concat(r),n+=r.length,a=r.length===d&&t.data.total_count>n}return console.log("All items:",s),[...new Set(s.map((e=>({name:e.name,size:e.size||0,type:e.type,modified:e.content_modified_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(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 k(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=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:S,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:_,redirect_uri:S,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class J extends U{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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 l=yield this.getFolderIdByPath(d);if(!l)throw new Error("Folder not found");const c=yield this.listFiles(n);c.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(n+"/"+a));const h=new f,u=JSON.stringify({name:a,parent:{id:l}});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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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 l=yield this.getFolderIdByPath(d);if(!l)return console.error("Folder not found"),!0;const c=`https://api.box.com/2.0/folders/${l}/items?fields=id,name&type=file&limit=1000`,h=(yield e.get(c,{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)=>{let s=0;const n=t.createWriteStream(i.join(this.storagePath,o));u.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),u.data.pipe(n),n.on("finish",e),n.on("error",r)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class H{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new w(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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 k(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 k(this,void 0,void 0,(function*(){const i=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(i))return yield this.folderCreationLocks.get(i);const r=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return k(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=>({name:e.name,size:e.size||0,type:e.directory?"folder":"file",modified:e.timestamp?new Date(1e3*e.timestamp).toISOString():""})))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return k(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 V extends H{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,r){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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)),l=t.statSync(i.join(this.storagePath,e)).size;return yield o.upload({name:n,size:l},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,r){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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));let l=0;return new Promise((e=>{const t=a.download();t.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),t.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 X{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new w(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=5){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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 k(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(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(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 console.log("All items:",s),[...new Set(s.map((e=>({name:e.name,size:e.size,type:e.type,modified:e.updated_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(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 k(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 k(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=(()=>k(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 k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:S,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:A,redirect_uri:S,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class Y extends X{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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 l=yield this.getFolderIdByPath(this.baseFolder+"/"+a),c=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:l,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}=c.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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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"}}),l=yield e({url:d.data.url,method:"get",responseType:"stream"});let c=0;const h=t.createWriteStream(i.join(this.storagePath,o));return l.data.on("data",(e=>{c+=e.length,this.taskQueue.setDownloadedSize(c)})),l.data.pipe(h),new Promise((e=>{h.on("finish",(()=>{e(!0)})),h.on("error",(t=>{console.error("Error occurred during file download:",t),e(!1)}))}))}catch(e){return console.error("Error downloading file:",e),!1}}))))))}))}}class G{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new w(3)}retryOperation(e,t=5){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(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 k(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(e){return k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(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=>({name:e.name,size:e.size||0,type:e.isfolder?"folder":"file",modified:e.modified})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(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 k(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return k(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:S,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${R}&response_type=code&redirect_uri=${S}`}}class Z extends G{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(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),l=t.statSync(a),c=i.basename(r),h=yield e({method:"put",url:"https://api.pcloud.com/uploadfile",params:{access_token:s,path:`/${n}`,renew:1,filename:c},data:d,headers:{"Content-Length":l.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 k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);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),l=`https://${n.data.hosts[0]}${n.data.path}`,c=yield e({method:"get",url:l,responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});return new Promise((e=>{let t=0;c.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),c.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}}))))))}))}}class ee{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.refreshTokenPromise=null,this.taskQueue=new w(3)}retryOperation(e,t=3){return k(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),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 k(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return k(this,void 0,void 0,(function*(){try{return(yield e.get(`${this.url}/list`,{params:{dir:t},auth:{username:this.username,password:this.password}})).data.files.map((e=>({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modifiedTime})))||[]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return k(this,void 0,void 0,(function*(){try{return(yield e.delete(`${this.url}/delete`,{params:{dir:t.split("/").slice(0,-1).join("/")||"",filename:t.split("/").pop()},auth:{username:this.username,password:this.password}})).data.success}catch(e){return console.error("Error deleting file:",e),!1}}))}}const te=r(o.pipeline);class ie extends ee{constructor(e,t){super(e),this.storagePath=t}getAuthHeader(){return`Basic ${btoa(`${this.username}:${this.password}`)}`}uploadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){try{o.split("/").pop();const s=o.substring(0,o.lastIndexOf("/"))||"",n=t.createReadStream(i.join(this.storagePath,r)),a=new f;a.append("file",n);const d=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(s)}`,a,{headers:Object.assign(Object.assign({},a.getHeaders()),{Authorization:this.getAuthHeader()}),maxContentLength:1/0,maxBodyLength:1/0});return!(d.status>=300)||(console.error("Error occurred during file upload:",d),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(r,o){return k(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>k(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=r.split("/").pop()||"",n=r.substring(0,r.lastIndexOf("/"))||"",a=t.createWriteStream(i.join(this.storagePath,o)),d=yield e({url:`${this.url}/download`,method:"GET",params:{dir:n,filename:s},headers:{Authorization:this.getAuthHeader()},maxContentLength:1/0,maxBodyLength:1/0,responseType:"stream"});if(d.status>=300)return console.error("Error occurred during file download:",d),a.destroy(),t.existsSync(i.join(this.storagePath,o))&&t.unlinkSync(i.join(this.storagePath,o)),!1;let l=0;return d.data.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),yield te(d.data,a),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}const re=["book","config","cover","font"];class oe{constructor(e,t,i,r){this.type=e,this.storagePath=i,this.remote="dropbox"===e?new Q(t,i,r):"microsoft"===e?new j(t,i,r):"google"===e?new B(t,i,r):"microsoft_exp"===e?new j(Object.assign(Object.assign({},t),{isExp:!0}),i,r):"google_exp"===e?new B(Object.assign(Object.assign({},t),{isExp:!0}),i,r):"s3compatible"===e?new M(t,i):"webdav"===e?new N(t,i):"docker"===e?new ie(t,i):"ftp"===e?new z(t,i):"sftp"===e?new K(t,i):"boxnet"===e?new J(t,i,r):"mega"===e?new V(t,i):"adrive"===e?new Y(t,i,r):"pcloud"===e?new Z(t,i,r):new q}downloadFile(e,r,o){return k(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 k(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(i+"/"+e,i+"/"+t)}))}deleteFile(e,t){return k(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 k(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}listFiles(e){return k(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}listFileInfos(e){return k(this,void 0,void 0,(function*(){return yield this.remote.listFileInfos(e)}))}downloadAllFiles(){return k(this,void 0,void 0,(function*(){for(let e of re){let t=yield this.listFiles(e);for(let i of t)yield this.downloadFile(i,i,e)}}))}authToken(e){return k(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()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const se={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 = ?"},ne={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},ae={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function de(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const le={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 ce={sqlStatement:{createTableStatement:de({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:de({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:de({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:de({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:de({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:de({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:de({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:de(se),getByBookKeyStatement:de(ne),getByBookKeysStatement:de({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:de(ae)},jsonToSqlite:de({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:de(le)};const he=F,ue=E;class pe{constructor(e,t){this.TokenService=e,this.ConfigService=t,this.baseUrl="china"===t.getItem("serverRegion")?ue:he,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return k(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(this.baseUrl+"/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 k(this,void 0,void 0,(function*(){return pe.requestQueue||(pe.requestQueue=[]),new Promise(((t,i)=>{pe.requestQueue.push({config:e,resolve:t,reject:i}),pe.processingQueue||this.processQueue()}))}))}processQueue(){return k(this,void 0,void 0,(function*(){if(!pe.processingQueue){pe.processingQueue=!0;try{for(;pe.requestQueue.length>0;){const e=pe.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{pe.processingQueue=!1}}}))}executeRequest(t){return k(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);if(t.baseURL=this.baseUrl,t.headers)t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=i;else{let e=this.ConfigService.getItem("appVersion"),r=this.ConfigService.getItem("appPlatform");t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":i,"X-App-Version":e||"1.0.0","X-App-Platform":r||"web"}}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 k(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>k(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)=>{let a=this.ConfigService.getItem("appVersion"),d=this.ConfigService.getItem("appPlatform");const l=new i(this.baseUrl+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+r,"X-Request-ID":o,"X-App-Version":a||"1.0.0","X-App-Platform":d||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});l.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),l.addEventListener("message",(e=>k(this,void 0,void 0,(function*(){if(!e.data)return;const i=JSON.parse(e.data);i.done?(l.close(),s(i)):(402===i.code&&(yield this.refreshUserToken()),t(i.data))})))),l.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);s(t),l.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return k(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>k(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)=>k(this,void 0,void 0,(function*(){let s=this.ConfigService.getItem("appVersion"),n=this.ConfigService.getItem("appPlatform");var a=new g(this.baseUrl+e.url,{headers:{"Content-Type":"text/plain",Authorization:"Bearer "+i,"X-Request-ID":r,"X-App-Version":s||"1.0.0","X-App-Platform":n||"web"},payload:JSON.stringify(e.data),method:"POST"});a.addEventListener("message",(e=>k(this,void 0,void 0,(function*(){if(!e.data)return;const i=JSON.parse(e.data);i.done?(a.close(),o(i)):(402===i.code&&(yield this.refreshUserToken()),t(i.data))})))),a.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),a.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const t=JSON.parse(e.data);o(t),a.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}pe.processingQueue=!1,pe.requestQueue=[];class fe extends pe{constructor(e,t){super(e,t)}encryptToken(e){return k(this,void 0,void 0,(function*(){let t=e.token,i=b.encode(t),{extracted:r,remaining:o}=function(e){let t="",i="",r=[],o=1;for(;o<=e.length;)r.push(o-1),o*=2;for(let o=0;o-1){let i=t.split("#");e.encrypted_token=i[1]}const i={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};let r=yield this.requestWithRetry(i);if(t.indexOf("#")>-1){let e=t.split("#"),i=function(e,t){let i="",r=[],o=1,s=e.length+t.length;for(;o<=s;)r.push(o-1),o*=2;let n=0,a=0;for(let o=0;o-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 me,ve;let ke;const Te=new Uint8Array(16);function be(){if(!ke&&(ke="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ke))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ke(Te)}const we=[];for(let e=0;e<256;++e)we.push((e+256).toString(16).slice(1));var Fe={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Ee(e,t,i){if(Fe.randomUUID&&!t&&!e)return Fe.randomUUID();const r=(e=e||{}).random||(e.rng||be)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){i=i||0;for(let e=0;e<16;++e)t[i+e]=r[e];return t}return function(e,t=0){return we[e[t+0]]+we[e[t+1]]+we[e[t+2]]+we[e[t+3]]+"-"+we[e[t+4]]+we[e[t+5]]+"-"+we[e[t+6]]+we[e[t+7]]+"-"+we[e[t+8]]+we[e[t+9]]+"-"+we[e[t+10]]+we[e[t+11]]+we[e[t+12]]+we[e[t+13]]+we[e[t+14]]+we[e[t+15]]}(r)}const Se=new m;class xe{static encrypt(e,t){let i="";for(let r=0;r