From cf37c90d4796921e8a2915722e7c121fed5da6b2 Mon Sep 17 00:00:00 2001 From: troyeguo <13820674+troyeguo@users.noreply.github.com> Date: Wed, 29 Apr 2026 16:38:57 +0800 Subject: [PATCH] feat: update text parser configuration and localization - Added new localization entries for "Number parser" and its description in zh-CN.json. - Refactored dropdown list component to utilize KookitConfig for content regex configurations instead of the removed contentRegxConfig. - Updated ChapterSetting component to use KookitConfig.ContentRegxConfig for built-in parsers. - Adjusted common utility functions to integrate KookitConfig.ContentRegxConfig for text parsing. --- src/assets/lib/kookit-extra-browser.min.js | 2 +- src/assets/locales/zh-CN.json | 2 ++ .../readerSettings/dropdownList/component.tsx | 15 ++++++++------ src/constants/dropdownList.tsx | 20 ------------------- .../settings/chapterSetting/component.tsx | 8 +++++--- src/utils/common.ts | 3 +-- 6 files changed, 18 insertions(+), 32 deletions(-) diff --git a/src/assets/lib/kookit-extra-browser.min.js b/src/assets/lib/kookit-extra-browser.min.js index 119ffc0e..31e5a4ff 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{AuthType as n,createClient 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,d=["books","notes","bookmarks","plugins","words"],u=e=>{const t=atob(e),r=t.length,n=new Uint8Array(r);for(let e=0;e{let t="";const r=new Uint8Array(e),n=r.byteLength;for(let e=0;ee>>>t|e<<32-t,n=(e,t,r)=>e&t^~e&r,i=(e,t,r)=>e&t^e&r^t&r,o=e=>r(e,2)^r(e,13)^r(e,22),s=e=>r(e,6)^r(e,11)^r(e,25),a=e=>r(e,7)^r(e,18)^e>>>3,c=e=>r(e,17)^r(e,19)^e>>>10,d=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],u=8*e.length,l=(960-(8*e.length+1)%512)%512,h=e.length+Math.ceil((l+1)/8)+8,p=new Uint8Array(h);p.set(e),p[e.length]=128;new DataView(p.buffer,p.byteLength-8).setBigUint64(0,BigInt(u),!1);for(let e=0;e>>0;let[l,h,f,g,m,y,b,v]=d;for(let e=0;e<64;e++){const r=v+s(m)+n(m,y,b)+t[e]+u[e]>>>0,a=o(l)+i(l,h,f)>>>0;v=b,b=y,y=m,m=g+r>>>0,g=f,f=h,h=l,l=r+a>>>0}d[0]=d[0]+l>>>0,d[1]=d[1]+h>>>0,d[2]=d[2]+f>>>0,d[3]=d[3]+g>>>0,d[4]=d[4]+m>>>0,d[5]=d[5]+y>>>0,d[6]=d[6]+b>>>0,d[7]=d[7]+v>>>0}const f=new ArrayBuffer(32),g=new DataView(f);return d.forEach(((e,t)=>{g.setUint32(4*t,e,!1)})),f}const p={_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,d=(15&o)<<2|s>>6,u=63&s;t+=this._chars.charAt(a),t+=this._chars.charAt(c),t+=r-2>=i?"=":this._chars.charAt(d),t+=r-1>=i?"=":this._chars.charAt(u)}return t},decode(e){if("string"!=typeof e)throw new Error("Input must be a string");for(e=e.replace(/[^A-Za-z0-9+/]/g,"");e.length%4!=0;)e+="=";const t=[];let r=0;const n=e.length;for(;r>4,c=(15&i)<<4|o>>2,d=(3&o)<<6|s;t.push(a),-1!==o&&t.push(c),-1!==s&&t.push(d)}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 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)=>{if(this.hasFailedTasks)return void t(void 0);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:d,configList:["themeColors","readingTime","appVersion","cloudSyncTime","lastSyncTime","recentBooks","recentAdd","deletedBooks","favoriteBooks","shelfList","txtParsers","noteTags","recordLocation","thirdpartyToken","sortedShelfList","kindleDeviceList","thirdpartyToken","opdsCatalogs","opdsCatalogList"],copyArrayBuffer:e=>{var t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t},base64ToArrayBuffer:u,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}))},getDisableThinkingParams:e=>{const t=new Set(["anthropic","zhipu","doubao","moonshot","deepseek"]),r=new Set(["qwen","hunyuan","siliconflow","infini"]);return e&&"custom"!==e?t.has(e)?{thinking:{type:"disabled"}}:r.has(e)?{enable_thinking:!1}:{}:{}},EmailProviders:["gmail.com","qq.com","163.com","yahoo.com","sina.com","sina.cn","126.com","outlook.com","yeah.net","foxmail.com","hotmail.com","protonmail.com","proton.me","icloud.com","mail.com","live.com","aliyun.com","sohu.com","yandex.com","naver.com","mail.ru","yahoo.co.jp","139.com","189.com","yandex.ru","189.cn"],Base64:p};const m={cloudUrl:"https://cloud.koodoreader.com",cloudCNUrl:"https://cloud.koodoreader.cn",testUrl:"https://cloudtest.960960.xyz",devUrl:"http://192.168.28.159:8000"},y={callbackUrl:"https://web.koodoreader.com/",cnCallbackUrl:"https://web.koodoreader.cn/",dropboxClientId:"vnc67byrssocvy1",yandexClientId:"e5305b62f53844b1994f77a840fd0a37",pcloudClientId:"pg8ten0B3vH",boxClientId:"ltimecqanmpxoaicn9qw3es6l3sdl1ya",duboxClientId:"kc0Ls6xLZugGgLLVhZ8yhUU1cRkRoKNU",yiyiwuClientId:"100197197",microsoftClientId:"506df58a-29ab-4020-afc5-6f423dc80f35",googleClientId:"1051055003225-ph1f5fvh328dhv7bco5jitlnfhg6ks2t.apps.googleusercontent.com",appleClientId:"com.koodoreader.auth",facebookClientId:"2845583825559500",githubClientId:"Ov23liJVzfvJMMEEZ8v2",adriveClientId:"a128ae7b9c094545af623de61dc0a1ef"},b={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"}},apple:{clientId:y.appleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{scope:""}}};var v={CloudMode:"production",CloudConfig:m,ConvertLangMap:{zhCN:"Chinese",zhTW:"Chinese",zhMO:"Chinese",ja:"Japanese",uk:"Ukrainian",ko:"Korean",vi:"Vietnamese",th:"Thai",ru:"Russian",ar:"Arabic",fr:"French",de:"German",es:"Spanish",it:"Italian",pt:"Portuguese",ptBR:"Portuguese",nl:"Dutch",id:"Indonesian",tr:"Turkish",pl:"Polish",cs:"Czech",sv:"Swedish",bn:"Bengali",tl:"Tagalog",ga:"Irish",bg:"Bulgarian",fa:"Persian"},ThirdpartyConfig:y,LoginAuthRequest:b,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"},apple:{authorizationEndpoint:"https://appleid.apple.com/auth/authorize",tokenEndpoint:"https://appleid.apple.com/auth/token"},email:{authorizationEndpoint:"",tokenEndpoint:""}},DriveAuthRequest:{dropbox:{clientId:y.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{token_access_type:"offline"}},yandex:{clientId:y.yandexClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{response_type:"code",force_confirm:"true"}},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"}},dubox:{clientId:y.duboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{response_type:"code",scope:"basic,netdisk",device_id:"119827642",qrcode:"1"}},yiyiwu:{clientId:y.yiyiwuClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{response_type:"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"},yandex:{authorizationEndpoint:"https://oauth.yandex.com/authorize",tokenEndpoint:"https://oauth.yandex.com/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"},dubox:{authorizationEndpoint:"https://openapi.baidu.com/oauth/2.0/authorize",tokenEndpoint:"https://openapi.baidu.com/oauth/2.0/token"},yiyiwu:{authorizationEndpoint:"https://passportapi.115.com/open/authorize",tokenEndpoint:"https://passportapi.115.com/open/authorize"},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"}},AiProviderList:[{id:"custom",name:"Custom model",defaultEndpoint:"",modelsEndpoint:""},{id:"openai",name:"OpenAI",defaultEndpoint:"https://api.openai.com/v1",modelsEndpoint:"https://api.openai.com/v1/models"},{id:"anthropic",name:"Anthropic",defaultEndpoint:"https://api.anthropic.com/v1",modelsEndpoint:"https://api.anthropic.com/v1/models"},{id:"google",name:"Google Gemini",defaultEndpoint:"https://generativelanguage.googleapis.com/v1beta/openai",modelsEndpoint:"https://generativelanguage.googleapis.com/v1beta/openai/models"},{id:"deepseek",name:"DeepSeek",defaultEndpoint:"https://api.deepseek.com/v1",modelsEndpoint:"https://api.deepseek.com/v1/models"},{id:"mistral",name:"Mistral AI",defaultEndpoint:"https://api.mistral.ai/v1",modelsEndpoint:"https://api.mistral.ai/v1/models"},{id:"cohere",name:"Cohere",defaultEndpoint:"https://api.cohere.ai/compatibility/v1",modelsEndpoint:"https://api.cohere.ai/compatibility/v1/models"},{id:"groq",name:"Groq",defaultEndpoint:"https://api.groq.com/openai/v1",modelsEndpoint:"https://api.groq.com/openai/v1/models"},{id:"together",name:"Together AI",defaultEndpoint:"https://api.together.xyz/v1",modelsEndpoint:"https://api.together.xyz/v1/models"},{id:"fireworks",name:"Fireworks AI",defaultEndpoint:"https://api.fireworks.ai/inference/v1",modelsEndpoint:"https://api.fireworks.ai/inference/v1/models"},{id:"perplexity",name:"Perplexity",defaultEndpoint:"https://api.perplexity.ai",modelsEndpoint:"https://api.perplexity.ai/v1/models"},{id:"openrouter",name:"OpenRouter",defaultEndpoint:"https://openrouter.ai/api/v1",modelsEndpoint:"https://openrouter.ai/api/v1/models"},{id:"ai21",name:"AI21 Labs",defaultEndpoint:"https://api.ai21.com/studio/v1",modelsEndpoint:"https://api.ai21.com/studio/v1/models"},{id:"xai",name:"xAI (Grok)",defaultEndpoint:"https://api.x.ai/v1",modelsEndpoint:"https://api.x.ai/v1/models"},{id:"sambanova",name:"SambaNova",defaultEndpoint:"https://api.sambanova.ai/v1",modelsEndpoint:"https://api.sambanova.ai/v1/models"},{id:"cerebras",name:"Cerebras",defaultEndpoint:"https://api.cerebras.ai/v1",modelsEndpoint:"https://api.cerebras.ai/v1/models"},{id:"hyperbolic",name:"Hyperbolic",defaultEndpoint:"https://api.hyperbolic.xyz/v1",modelsEndpoint:"https://api.hyperbolic.xyz/v1/models"},{id:"novita",name:"Novita AI",defaultEndpoint:"https://api.novita.ai/openai",modelsEndpoint:"https://api.novita.ai/openai/models"},{id:"lepton",name:"Lepton AI",defaultEndpoint:"https://llm.lepton.run/api/v1",modelsEndpoint:"https://llm.lepton.run/api/v1/models"},{id:"deepinfra",name:"DeepInfra",defaultEndpoint:"https://api.deepinfra.com/v1/openai",modelsEndpoint:"https://api.deepinfra.com/v1/openai/models"},{id:"replicate",name:"Replicate",defaultEndpoint:"https://api.replicate.com/v1",modelsEndpoint:"https://api.replicate.com/v1/models"},{id:"zhipu",name:"Zhipu AI (智谱)",defaultEndpoint:"https://open.bigmodel.cn/api/paas/v4",modelsEndpoint:"https://open.bigmodel.cn/api/paas/v4/models"},{id:"qwen",name:"Alibaba Qwen (通义千问)",defaultEndpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1",modelsEndpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/models"},{id:"moonshot",name:"Moonshot (月之暗面)",defaultEndpoint:"https://api.moonshot.cn/v1",modelsEndpoint:"https://api.moonshot.cn/v1/models"},{id:"baidu",name:"Baidu ERNIE (文心一言)",defaultEndpoint:"https://qianfan.baidubce.com/v2",modelsEndpoint:"https://qianfan.baidubce.com/v2/models"},{id:"doubao",name:"Volcengine Doubao (豆包)",defaultEndpoint:"https://ark.cn-beijing.volces.com/api/v3",modelsEndpoint:"https://ark.cn-beijing.volces.com/api/v3/models"},{id:"spark",name:"iFlytek Spark (讯飞星火)",defaultEndpoint:"https://spark-api-open.xf-yun.com/v1",modelsEndpoint:"https://spark-api-open.xf-yun.com/v1/models"},{id:"hunyuan",name:"Tencent Hunyuan (腾讯混元)",defaultEndpoint:"https://api.hunyuan.cloud.tencent.com/v1",modelsEndpoint:"https://api.hunyuan.cloud.tencent.com/v1/models"},{id:"minimax",name:"MiniMax",defaultEndpoint:"https://api.minimax.chat/v1",modelsEndpoint:"https://api.minimax.chat/v1/models"},{id:"baichuan",name:"Baichuan (百川)",defaultEndpoint:"https://api.baichuan-ai.com/v1",modelsEndpoint:"https://api.baichuan-ai.com/v1/models"},{id:"stepfun",name:"StepFun (阶跃星辰)",defaultEndpoint:"https://api.stepfun.com/v1",modelsEndpoint:"https://api.stepfun.com/v1/models"},{id:"lingyi",name:"Lingyiwanwu (零一万物)",defaultEndpoint:"https://api.lingyiwanwu.com/v1",modelsEndpoint:"https://api.lingyiwanwu.com/v1/models"},{id:"siliconflow",name:"SiliconFlow (硅基流动)",defaultEndpoint:"https://api.siliconflow.cn/v1",modelsEndpoint:"https://api.siliconflow.cn/v1/models"},{id:"infini",name:"Infini AI (无问芯穹)",defaultEndpoint:"https://cloud.infini-ai.com/maas/v1",modelsEndpoint:"https://cloud.infini-ai.com/maas/v1/models"},{id:"ollama",name:"Ollama (Local)",defaultEndpoint:"http://localhost:11434/v1",modelsEndpoint:"http://localhost:11434/v1/models"},{id:"lmstudio",name:"LM Studio (Local)",defaultEndpoint:"http://localhost:1234/v1",modelsEndpoint:"http://localhost:1234/v1/models"},{id:"vllm",name:"vLLM (Local)",defaultEndpoint:"http://localhost:8000/v1",modelsEndpoint:"http://localhost:8000/v1/models"},{id:"azure",name:"Azure OpenAI",defaultEndpoint:"",modelsEndpoint:""},{id:"aws_bedrock",name:"AWS Bedrock",defaultEndpoint:"",modelsEndpoint:""}],DefaultPrompts:{aiTranslate:"You are a professional translator. Translate the following text from {from} to {to}. Only return the translated text, no explanations.\n\nText: {text}",aiDict:"You are a professional dictionary assistant. Analyze the word or phrase: {word}\nProvide a comprehensive explanation including pronunciation, definitions, example sentences, and usage notes using {to} as the target language. ",aiAssistance:"You are a helpful reading assistant. The user is reading a book. Here is the context:\n{text}\n\nAnswer the user's question concisely and helpfully, and reply with the same language."},SpeechList:[{label:"English",code:"en",example:"To be, or not to be, that is the question."},{label:"Simplified Chinese",code:"zh",example:"千里之行,始于足下。"},{label:"Japanese",code:"ja",example:"猿も木から落ちる。"},{label:"Korean",code:"ko",example:"가는 날이 장날이다."},{label:"French",code:"fr",example:"Liberté, égalité, fraternité."},{label:"German",code:"de",example:"Der Weg ist das Ziel."},{label:"Spanish",code:"es",example:"La vida es un sueño."},{label:"Italian",code:"it",example:"Dolce far niente."},{label:"Russian",code:"ru",example:"Век живи, век учись."},{label:"Portuguese",code:"pt",example:"Saudade é um sentimento profundo."},{label:"Hindi",code:"hi",example:"सपने वो नहीं जो हम सोते वक्त देखते हैं।"},{label:"Afrikaans",code:"af",example:"Die lewe is 'n geskenk."},{label:"Amharic",code:"am",example:"ዕውቀት ብርሃን ነው።"},{label:"Arabic",code:"ar",example:"العلم نور والجهل ظلام."},{label:"Azerbaijani",code:"az",example:"Elm işıqdır, cəhalət zülmət."},{label:"Bulgarian",code:"bg",example:"Знанието е сила."},{label:"Bengali",code:"bn",example:"জ্ঞানই শক্তি।"},{label:"Bosnian",code:"bs",example:"Znanje je moć."},{label:"Catalan",code:"ca",example:"El saber no ocupa lloc."},{label:"Czech",code:"cs",example:"Bez práce nejsou koláče."},{label:"Welsh",code:"cy",example:"Nid aur popeth melyn."},{label:"Danish",code:"da",example:"Lykken er ikke et sted, men en retning."},{label:"Greek",code:"el",example:"Η γνώση είναι δύναμη."},{label:"Estonian",code:"et",example:"Teadmine on jõud."},{label:"Basque",code:"eu",example:"Jakitea boterea da."},{label:"Persian",code:"fa",example:"دانش قدرت است."},{label:"Finnish",code:"fi",example:"Tieto on valtaa."},{label:"Filipino",code:"fil",example:"Ang kaalaman ay kapangyarihan."},{label:"Irish",code:"ga",example:"Is fearr Gaeilge briste ná Béarla cliste."},{label:"Galician",code:"gl",example:"O saber non ocupa lugar."},{label:"Gujarati",code:"gu",example:"જ્ઞાન શક્તિ છે."},{label:"Hebrew",code:"he",example:"ידע הוא כוח."},{label:"Croatian",code:"hr",example:"Znanje je moć."},{label:"Hungarian",code:"hu",example:"A tudás hatalom."},{label:"Armenian",code:"hy",example:"Գիտելիքը ուժ է."},{label:"Indonesian",code:"id",example:"Pengetahuan adalah kekuatan."},{label:"Icelandic",code:"is",example:"Þekking er máttur."},{label:"Inuktitut",code:"iu",example:"ᐃᓕᓐᓂᐊᕐᓂᖅ ᐱᒻᒪᕆᐅᕗᖅ."},{label:"Javanese",code:"jv",example:"Ilmu iku kelakone kanthi laku."},{label:"Georgian",code:"ka",example:"ცოდნა ძალაა."},{label:"Kazakh",code:"kk",example:"Білім — күш."},{label:"Khmer",code:"km",example:"ចំណេះដឹងគឺជាអំណាច។"},{label:"Kannada",code:"kn",example:"ಜ್ಞಾನವೇ ಶಕ್ತಿ."},{label:"Lao",code:"lo",example:"ຄວາມຮູ້ຄືພະລັງ."},{label:"Lithuanian",code:"lt",example:"Žinios yra jėga."},{label:"Latvian",code:"lv",example:"Zināšanas ir spēks."},{label:"Macedonian",code:"mk",example:"Знаењето е моќ."},{label:"Malayalam",code:"ml",example:"അറിവ് ശക്തിയാണ്."},{label:"Mongolian",code:"mn",example:"Мэдлэг бол хүч."},{label:"Marathi",code:"mr",example:"ज्ञान हीच शक्ती आहे."},{label:"Malay",code:"ms",example:"Ilmu itu cahaya."},{label:"Maltese",code:"mt",example:"L-għarfien huwa l-poter."},{label:"Burmese",code:"my",example:"ဗဟုသုတသည် အားဖြစ်သည်။"},{label:"Norwegian",code:"nb",example:"Kunnskap er makt."},{label:"Nepali",code:"ne",example:"ज्ञान नै शक्ति हो।"},{label:"Dutch",code:"nl",example:"Kennis is macht."},{label:"Odia",code:"or",example:"ଜ୍ଞାନ ହିଁ ଶକ୍ତି।"},{label:"Punjabi",code:"pa",example:"ਗਿਆਨ ਹੀ ਸ਼ਕਤੀ ਹੈ।"},{label:"Polish",code:"pl",example:"Wiedza to potęga."},{label:"Pashto",code:"ps",example:"د پوهې ډیوه روښانه ده."},{label:"Romanian",code:"ro",example:"Cartea este o comoară."},{label:"Sinhala",code:"si",example:"දැනුම බලයකි."},{label:"Slovak",code:"sk",example:"Vedomosti sú sila."},{label:"Slovenian",code:"sl",example:"Znanje je moč."},{label:"Somali",code:"so",example:"Aqoontu waa iftiin."},{label:"Albanian",code:"sq",example:"Dija është fuqi."},{label:"Serbian",code:"sr",example:"Знање је моћ."},{label:"Sundanese",code:"su",example:"Élmu éta cahaya."},{label:"Swedish",code:"sv",example:"Kunskap är makt."},{label:"Swahili",code:"sw",example:"Maarifa ni nguvu."},{label:"Tamil",code:"ta",example:"அறிவே ஆற்றல்."},{label:"Telugu",code:"te",example:"జ్ఞానమే శక్తి."},{label:"Thai",code:"th",example:"ความรู้คือพลัง."},{label:"Turkish",code:"tr",example:"Bilgi güçtür."},{label:"Ukrainian",code:"uk",example:"Знання — сила."},{label:"Urdu",code:"ur",example:"علم ہی طاقت ہے۔"},{label:"Uzbek",code:"uz",example:"Bilim – kuch."},{label:"Vietnamese",code:"vi",example:"Học vấn là sức mạnh."},{label:"Wu Chinese",code:"wuu",example:"学问是力量。"},{label:"Cantonese",code:"yue",example:"知識就係力量。"},{label:"Zulu",code:"zu",example:"Ulwazi lungamandla."}]};class w{constructor(e){this.config=e,this.driveId="",this.taskQueue=new f(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)))}}))}getDriveId(){return a(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const t=this.config.access_token,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=this.config.access_token,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=this.config.access_token,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.filter((e=>!e.punish_flag||2!==e.punish_flag))||[];o=o.concat(c),s=t.data.next_marker,a=!!s&&100===c.length}return[...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=this.config.access_token,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=this.config.access_token,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){}}))}getAuthUrl(e){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:y.adriveClientId,redirect_uri:e,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class S extends w{constructor(e){super(e)}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=this.config.access_token,o=yield this.getDriveId(),s=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1),c=yield this.getFolderIdByPath(this.baseFolder+"/"+s),d=yield t.arrayBuffer(),u=d.byteLength,l=yield crypto.subtle.digest("SHA-1",d),h=Array.from(new Uint8Array(l)).map((e=>e.toString(16).padStart(2,"0"))).join(""),p=function(e){function t(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function r(e,r,n,i,o,s){return t((a=t(t(r,e),t(i,s)))<<(c=o)|a>>>32-c,n);var a,c}function n(e,t,n,i,o,s,a){return r(t&n|~t&i,e,t,o,s,a)}function i(e,t,n,i,o,s,a){return r(t&i|n&~i,e,t,o,s,a)}function o(e,t,n,i,o,s,a){return r(t^n^i,e,t,o,s,a)}function s(e,t,n,i,o,s,a){return r(n^(t|~i),e,t,o,s,a)}const a=function(e){const t=e.length,r=1+(t+8>>6),n=new Array(16*r).fill(0);for(let r=0;r>2]|=e.charCodeAt(r)<>2]|=128<{let t="";for(let r=0;r<4;r++)t+=("0"+(e>>8*r&255).toString(16)).slice(-2);return t})).join("")}(i),f=Number(BigInt("0x"+p.slice(0,16))%BigInt(u||1)),g=new Uint8Array(d.slice(f,Math.min(f+8,u))),m=btoa(String.fromCharCode(...g)),y=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",size:u,content_hash:h,content_hash_name:"sha1",proof_code:m,proof_version:"v1",part_info_list:[{part_number:1}]},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),{file_id:b,upload_id:v,rapid_upload:w,part_info_list:S}=y.data;if(w)return console.info("阿里云盘秒传成功"),void n(!0);yield e.put(S[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:b,upload_id:v},{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=this.config.access_token,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){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)))}}))}getFolderIdByPath(t){return a(this,void 0,void 0,(function*(){if(""==t)return"0";const r=this.config.access_token,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=this.config.access_token;let n=this.baseFolder+"/"+t;for(;n.startsWith("/");)n=n.substring(1);let i=yield this.getFolderIdByPath(n),o=[],s=0,a=!0;const c=1e3;for(;a;){const t=yield e.get(`https://api.box.com/2.0/folders/${i}/items`,{params:{limit:c,offset:s},headers:{Authorization:`Bearer ${r}`}}),n=t.data.entries||[];o=o.concat(n),s+=n.length,a=n.length===c&&t.data.total_count>s}return[...new Set(o.map((e=>({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=this.config.access_token,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}}))}getAuthUrl(e){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:y.boxClientId,redirect_uri:e,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class E extends k{constructor(e){super(e)}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=this.config.access_token,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 d=new File([t],o,{lastModified:(new Date).getTime(),type:t.type});const u=new FormData;u.append("file",d),u.append("parent_id",a);const l=yield e.post("https://upload.box.com/api/2.0/files/content",u,{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=this.config.access_token,n=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1);let o=this.baseFolder+"/"+n;for(;o.startsWith("/");)o=o.substring(1);const s=yield this.getFolderIdByPath(o);if(!s)return console.error("Folder not found"),!0;const a=`https://api.box.com/2.0/folders/${s}/items?fields=id,name&type=file&limit=1000`,c=(yield e.get(a,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));if(!c)return console.error("File not found:",i),!0;const d=yield e({url:`https://api.box.com/2.0/files/${c.id}/content`,method:"get",headers:{Authorization:`Bearer ${r}`},responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return d.status>=300?(console.error("Error occurred during file download:",d),!1):d.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class x{constructor(e){this.config=e,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=this.config.access_token;let n=[],i=!0,o=null;for(;i;){let s;s=o?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:o},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t,limit:2e3},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});const a=s.data.entries||[];n=n.concat(a),i=s.data.has_more,o=s.data.cursor}return[...new Set(n.map((e=>({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=this.config.access_token;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}}))}getAuthUrl(e){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${y.dropboxClientId}&redirect_uri=${e}`}}class A extends x{constructor(e){super(e)}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=this.config.access_token;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=this.config.access_token,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 C{constructor(e){this.folderExistsCache=new Set,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)))}}))}listFiles(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){var r,n;return a(this,void 0,void 0,(function*(){try{const i=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let o=[],s=0;const a=1e3;let c=!0;for(;c;){const d=yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",limit:a,offset:s,fields:"_embedded.items.name,_embedded.items.size,_embedded.items.type,_embedded.items.modified,_embedded.total"}}),u=(null===(r=d.data._embedded)||void 0===r?void 0:r.items)||[];o=o.concat(u);const l=(null===(n=d.data._embedded)||void 0===n?void 0:n.total)||0;s+=u.length,c=s({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.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=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const n=yield e.delete("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${r}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",permanently:!1}});return 202===n.status||204===n.status}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(t){var r,n;return a(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=t.split("/").filter((e=>e.length>0));let s="";for(const t of o)if(s+="/"+t,!this.folderExistsCache.has(s))try{yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:s}}),this.folderExistsCache.add(s)}catch(t){if(404!==(null===(r=t.response)||void 0===r?void 0:r.status))return console.error("Error checking directory:",t),!1;try{yield e.put(`https://cloud-api.yandex.net/v1/disk/resources?path=${encodeURIComponent(s)}`,null,{headers:{Authorization:`OAuth ${i}`}}),this.folderExistsCache.add(s)}catch(e){if(409!==(null===(n=e.response)||void 0===n?void 0:n.status))return console.error("Error creating directory:",e),!1;this.folderExistsCache.add(s)}}return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}getAuthUrl(e){return`https://oauth.yandex.com/authorize?response_type=code&client_id=${y.yandexClientId}&redirect_uri=${e}&force_confirm=true`}}class T extends C{constructor(e){super(e)}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=this.config.access_token;let i=this.baseFolder+"/"+r;for(;i.startsWith("/");)i=i.substring(1);const o=i.substring(0,i.lastIndexOf("/"));if(o){if(!(yield this.ensureDirectoryExists(o)))return console.error("Failed to create directory:",o),!1}const s=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/upload",{headers:{Authorization:`OAuth ${n}`,"Content-Type":"application/json"},params:{path:`/${i}`,overwrite:!0}});if(200!==s.status)return console.error("Error getting upload URL:",s),!1;const a=s.data.href;let c=r.split("/").pop()||"",d=new File([t],c,{lastModified:(new Date).getTime(),type:t.type});const u=yield e.put(a,d,{headers:{"Content-Type":t.type||"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file upload:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(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=this.config.access_token;let n=this.baseFolder+"/"+t;for(;n.startsWith("/");)n=n.substring(1);const i=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/download",{headers:{Authorization:`OAuth ${r}`,"Content-Type":"application/json"},params:{path:`/${n}`}});if(200!==i.status)return console.error("Error getting download URL:",i),!1;const o=i.data.href,s=yield e({url:o,method:"get",maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return s.status>=300?(console.error("Error occurred during file download:",s),!1):s.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class R{constructor(e){this.isExp=!1,this.folderIdCache=new Map,this.config=e,this.taskQueue=new f(3),this.isExp=this.config.isExp||!1,this.baseFolder="KoodoReader"}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=this.config.access_token,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=this.config.access_token;if(""===t)return"root";if(this.folderIdCache.has(t))return this.folderIdCache.get(t);const n=t.split("/").filter((e=>""!==e.trim()));let i="root",o="";for(const t of n){if(o=o?o+"/"+t:t,this.folderIdCache.has(o)){i=this.folderIdCache.get(o);continue}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}}this.folderIdCache.set(o,n),i=n}return i}))}getFolderId(t,r){return a(this,void 0,void 0,(function*(){const n=this.config.access_token,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=this.config.access_token;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[...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("/").pop()||"",n=t.split("/").slice(0,-1).join("/"),i=yield this.checkFolder(n),o=this.config.access_token,s=yield this.getFileId(r,i);if(""===s)return console.error("File not found:",r),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${s}`,{headers:{Authorization:`Bearer ${o}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${e}&prompt=consent&response_type=code&client_id=${y.googleClientId}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class O extends R{constructor(e){super(e)}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=this.config.access_token;let i=r.split("/").pop()||"",o=new File([t],i,{lastModified:(new Date).getTime(),type:t.type}),s=r.split(".").pop(),a=c(s||""),d=r.split("/")[0],u=yield this.checkFolder(d),l=yield this.getFileId(i||"",u);const h={mimeType:a,name:i,parents:[u]},p=l?`https://www.googleapis.com/upload/drive/v3/files/${l}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:l?"PATCH":"POST",url:p,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(f,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=this.config.access_token;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 P{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=2){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,userAgent:"KoodoReader/1.0"}).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 I extends P{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),d=r.from(c),u=n.children.find((e=>e.name===o&&!e.directory));return u&&(yield u.delete()),yield n.upload({name:o,size:s.size},d).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 _{constructor(e){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,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=this.config.access_token;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[...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=this.config.access_token;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}}))}getAuthUrl(e){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=${e}`}}class M extends _{constructor(e){super(e)}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=this.config.access_token;let i=r.split("/").pop()||"",o=new File([t],i,{lastModified:(new Date).getTime(),type:t.type}),s=this.baseFolder+"/"+r;for(;s.startsWith("/");)s=s.substring(1);const a=this.baseUrl+":/"+s+":/createUploadSession",c=yield e.post(a,null,{headers:{Authorization:"Bearer "+n,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0});let d=o.size;const u=o.type,l=c.data.uploadUrl,h=yield e.put(l,o,{headers:{"Content-Type":u,"Content-Range":`bytes 0-${d-1}/${d}`},maxContentLength:1/0,maxBodyLength:1/0});return!(h.status>=300)||(console.error("Error occurred during file download:",h),!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=this.config.access_token;let n=this.baseFolder+"/"+t;for(;n.startsWith("/");)n=n.substring(1);const i=`${this.baseUrl}:/${n}:/content`,o=yield e.get(i,{responseType:"arraybuffer",headers:{Authorization:"Bearer "+r},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}}))))))}))}}class N{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([])}))}))}getAuthUrl(){return""}}class ${constructor(e){this.baseUrl="https://api.pcloud.com",this.config=e,this.taskQueue=new f(3),this.baseUrl="2"===e.region?"https://eapi.pcloud.com":"https://api.pcloud.com"}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)))}}))}checkFolderExists(t,r){return a(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/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(`${this.baseUrl}/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=this.config.refresh_token,n=yield e.get(`${this.baseUrl}/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=this.config.refresh_token,n=yield e.get(`${this.baseUrl}/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}}))}getAuthUrl(e){return`https://my.pcloud.com/oauth2/authorize?client_id=${y.pcloudClientId}&response_type=code&redirect_uri=${e}`}}class F extends ${constructor(e){super(e)}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=this.config.refresh_token,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(`${this.baseUrl}/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=this.config.refresh_token,n=yield e.get(`${this.baseUrl}/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 U=e=>{let t=e.httpHandler;return{setHttpHandler(e){t=e},httpHandler:()=>t,updateHttpClientConfig(e,r){t.updateHttpClientConfig(e,r)},httpHandlerConfigs:()=>t.httpHandlerConfigs()}};var L,D,B,z,j;!function(e){e.HEADER="header",e.QUERY="query"}(L||(L={})),function(e){e.HEADER="header",e.QUERY="query"}(D||(D={})),function(e){e.HTTP="http",e.HTTPS="https"}(B||(B={})),function(e){e.MD5="md5",e.CRC32="crc32",e.CRC32C="crc32c",e.SHA1="sha1",e.SHA256="sha256"}(z||(z={})),function(e){e[e.HEADER=0]="HEADER",e[e.TRAILER=1]="TRAILER"}(j||(j={}));const q="__smithy_context";var H,W;!function(e){e.PROFILE="profile",e.SSO_SESSION="sso-session",e.SERVICES="services"}(H||(H={})),function(e){e.HTTP_0_9="http/0.9",e.HTTP_1_0="http/1.0",e.TDS_8_0="tds/8.0"}(W||(W={}));class K{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 K({...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 K.clone(this)}}class V{constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;const t=e;return"number"==typeof t.statusCode&&"object"==typeof t.headers}}const Q={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0},G=e=>({applyToStack:t=>{t.add(function(e){return t=>async r=>{const{request:n}=r;return K.isInstance(n)&&n.body&&"node"===e.runtime&&"FetchHttpHandler"!==e.requestHandler?.constructor?.name&&(n.headers={...n.headers,Expect:"100-continue"}),t({...r,request:n})}}(e),Q)}}),J="WHEN_SUPPORTED",Y=J,X=J;var Z,ee;!function(e){e.MD5="MD5",e.CRC32="CRC32",e.CRC32C="CRC32C",e.SHA1="SHA1",e.SHA256="SHA256"}(Z||(Z={})),function(e){e.HEADER="header",e.TRAILER="trailer"}(ee||(ee={}));const te=Z.MD5,re=Z.CRC32;var ne;function ie(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"}(ne||(ne={}));const oe=e=>V.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,se=e=>new Date(Date.now()+e),ae=(e,t)=>{const r=Date.parse(e);return((e,t)=>Math.abs(se(t).getTime()-e)>=3e5)(r,t)?r-Date.now():t},ce=(e,t)=>{if(!t)throw new Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},de=async e=>{const t=ce("context",e.context),r=ce("config",e.config),n=t.endpointV2?.properties?.authSchemes?.[0],i=ce("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 ue{async sign(e,t,r){if(!K.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const n=await de(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:se(i.systemClockOffset),signingRegion:s,signingService:a})}errorHandler(e){return t=>{const r=t.ServerTime??oe(t.$response);if(r){const n=ce("config",e.config),i=n.systemClockOffset;n.systemClockOffset=ae(r,n.systemClockOffset);n.systemClockOffset!==i&&t.$metadata&&(t.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const r=oe(e);if(r){const e=ce("config",t.config);e.systemClockOffset=ae(r,e.systemClockOffset)}}}class le extends ue{async sign(e,t,r){if(!K.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 de(r),c=(await(n.sigv4aSigningRegionSet?.())??s??[o]).join(",");return await i.sign(e,{signingDate:se(n.systemClockOffset),signingRegion:c,signingService:a})}}const he=e=>e[q]||(e[q]={}),pe=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t};const fe=(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=he(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:d={},signingProperties:u={}}=r.propertiesExtractor?.(e,n)||{};r.identityProperties=Object.assign(r.identityProperties||{},d),r.signingProperties=Object.assign(r.signingProperties||{},u),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)},ge={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},me={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},ye={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function be(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),me),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),ye)}}}const ve=e=>e=>{throw e},we=(e,t)=>{},Se={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},ke=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{if(!K.isInstance(r.request))return e(r);const n=he(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||ve)(i));return(s.successHandler||we)(a.response,i),a}),Se)}}),Ee=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t},xe={},Ae=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);xe[r]=e,Ae[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;xe[r]=n,Ae[n]=r}for(let e=0;e<10;e++){xe[e.toString(10)]=e+52;const t=e.toString(10),r=e+52;xe[t]=r,Ae[r]=t}xe["+"]=62,Ae[62]="+",xe["/"]=63,Ae[63]="/";const Ce=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)},Te=e=>(new TextEncoder).encode(e),Re=e=>"string"==typeof e?Te(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e),Oe=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 Pe(e){let t;t="string"==typeof e?Te(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 Ie extends Uint8Array{static fromString(e,t="utf-8"){if("string"==typeof e)return function(e,t){return"base64"===t?Ie.mutate(Ce(e)):Ie.mutate(Te(e))}(e,t);throw new Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,Ie.prototype),e}transformToString(e="utf-8"){return function(e,t="utf-8"){return"base64"===t?Pe(e):Oe(e)}(this,e)}}const _e=(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,d=e.getReader();return new ReadableStream({async pull(e){const{value:t,done:i}=await d.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`)}})},Me=e=>encodeURIComponent(e).replace(/[!'()*]/g,Ne),Ne=e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`;function $e(e,t){return new Request(e,t)}function Fe(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 Ue={supported:void 0};class Le{static create(e){return"function"==typeof e?.handle?e:new Le(e)}constructor(e){"function"==typeof e?this.configProvider=e().then((e=>e||{})):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),void 0===Ue.supported&&(Ue.supported=Boolean("undefined"!=typeof Request&&"keepalive"in $e("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=Me(r),Array.isArray(n))for(let e=0,i=n.length;e{};const f=$e(u,h),g=[fetch(f).then((e=>{const t=e.headers,r={};for(const e of t.entries())r[e[0]]=e[1];return null!=e.body?{response:new V({headers:r,reason:e.statusText,statusCode:e.status,body:e.body})}:e.blob().then((t=>({response:new V({headers:r,reason:e.statusText,statusCode:e.status,body:t})})))})),Fe(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}),p=()=>e.removeEventListener("abort",n)}else t.onabort=n}))),Promise.race(g).finally(p)}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then((r=>(r[e]=t,r)))}httpHandlerConfigs(){return this.config??{}}}const De=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 Be={},ze={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();1===t.length&&(t=`0${t}`),Be[e]=t,ze[t]=e}function je(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),We="The stream has already been transformed.",Ke=e=>{if(!Ve(e)&&!He(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(We);return t=!0,await De(e)};return Object.assign(e,{transformToByteArray:r,transformToString:async e=>{const t=await r();if("base64"===e)return Pe(t);if("hex"===e)return qe(t);if(void 0===e||"utf8"===e||"utf-8"===e)return Oe(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(We);if(t=!0,Ve(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(He(e))return e;throw new Error(`Cannot transform payload to web stream, got ${e}`)}})},Ve=e=>"function"==typeof Blob&&e instanceof Blob;const Qe="function"==typeof ReadableStream?ReadableStream:function(){};class Ge extends Qe{}const Je=({expectedChecksum:e,checksum:t,source:r,checksumSourceLocation:n,base64Encoder:i})=>{if(!He(r))throw new Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);const o=i??Pe;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,Ge.prototype),a},Ye=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return Ie.mutate(e);if(!e)return Ie.mutate(new Uint8Array);const r=t.streamCollector(e);return Ie.mutate(await r)};function Xe(e){return encodeURIComponent(e).replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function Ze(e,t){return new et(e,t)}class et{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 K({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=>Xe(e))).join("/"):Xe(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 tt{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 rt=(nt=3e5,e=>it(e)&&e.expiration.getTime()-Date.now()void 0!==e.expiration,ot="X-Amz-Date",st="X-Amz-Signature",at="X-Amz-Security-Token",ct="authorization",dt=ot.toLowerCase(),ut=[ct,dt,"date"],lt=st.toLowerCase(),ht="x-amz-content-sha256",pt=at.toLowerCase(),ft={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},gt=/^proxy-/,mt=/^sec-/,yt="AWS4-HMAC-SHA256",bt="AWS4-HMAC-SHA256-PAYLOAD",vt="aws4_request",wt={},St=[],kt=(e,t,r)=>`${e}/${t}/${r}/${vt}`,Et=(e,t,r)=>{const n=new e(t);return n.update(Re(r)),n.digest()},xt=({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 ft||t?.has(o)||gt.test(o)||mt.test(o))&&(!r||r&&!r.has(o))||(n[o]=e[i].trim().replace(/\s+/g," "))}return n},At=e=>"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(e),Ct=async({headers:e,body:t},r)=>{for(const t of Object.keys(e))if(t.toLowerCase()===ht)return e[t];if(null==t)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if("string"==typeof t||ArrayBuffer.isView(t)||At(t)){const e=new r;return e.update(Re(t)),qe(await e.digest())}return"UNSIGNED-PAYLOAD"};class Tt{format(e){const t=[];for(const r of Object.keys(e)){const n=Te(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=Te(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 d=new Uint8Array(9);return d[0]=8,d.set(Pt.fromNumber(e.value.valueOf()).bytes,1),d;case"uuid":if(!Ot.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const u=new Uint8Array(17);return u[0]=9,u.set(je(e.value.replace(/\-/g,"")),1),u}}}var Rt;!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"}(Rt||(Rt={}));const Ot=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Pt{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&&It(t),new Pt(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&It(e),parseInt(qe(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function It(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}const _t=e=>{e=K.clone(e);for(const t of Object.keys(e.headers))ut.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e},Mt=e=>"number"==typeof e?new Date(1e3*e):"string"==typeof e?Number(e)?new Date(1e3*Number(e)):new Date(e):e;class Nt{constructor({applyChecksum:e,credentials:t,region:r,service:n,sha256:i,uriEscapePath:o=!0}){this.headerFormatter=new Tt,this.service=n,this.sha256=i,this.uriEscapePath=o,this.applyChecksum="boolean"!=typeof e||e,this.regionProvider=pe(r),this.credentialProvider=pe(t)}async presign(e,t={}){const{signingDate:r=new Date,expiresIn:n=3600,unsignableHeaders:i,unhoistableHeaders:o,signableHeaders:s,hoistableHeaders:a,signingRegion:c,signingService:d}=t,u=await this.credentialProvider();this.validateResolvedCredentials(u);const l=c??await this.regionProvider(),{longDate:h,shortDate:p}=$t(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 f=kt(p,l,d??this.service),g=((e,t={})=>{const{headers:r,query:n={}}=K.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}})(_t(e),{unhoistableHeaders:o,hoistableHeaders:a});u.sessionToken&&(g.query[at]=u.sessionToken),g.query["X-Amz-Algorithm"]=yt,g.query["X-Amz-Credential"]=`${u.accessKeyId}/${f}`,g.query[ot]=h,g.query["X-Amz-Expires"]=n.toString(10);const m=xt(g,i,s);return g.query["X-Amz-SignedHeaders"]=Ft(m),g.query[st]=await this.getSignature(h,f,this.getSigningKey(u,l,p,d),this.createCanonicalRequest(g,m,await Ct(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}=$t(r),d=kt(a,s,o??this.service),u=await Ct({headers:{},body:t},this.sha256),l=new this.sha256;l.update(e);const h=qe(await l.digest()),p=[bt,c,d,n,h,u].join("\n");return this.signString(p,{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}=$t(t),a=new this.sha256(await this.getSigningKey(i,o,s,n));return a.update(Re(e)),qe(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=_t(e),{longDate:d,shortDate:u}=$t(t),l=kt(u,a,o??this.service);c.headers[dt]=d,s.sessionToken&&(c.headers[pt]=s.sessionToken);const h=await Ct(c,this.sha256);!((e,t)=>{e=e.toLowerCase();for(const r of Object.keys(t))if(e===r.toLowerCase())return!0;return!1})(ht,c.headers)&&this.applyChecksum&&(c.headers[ht]=h);const p=xt(c,n,r),f=await this.getSignature(d,l,this.getSigningKey(s,a,u,o),this.createCanonicalRequest(c,p,h));return c.headers[ct]=`${yt} Credential=${s.accessKeyId}/${l}, SignedHeaders=${Ft(p)}, Signature=${f}`,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()===lt)continue;const i=Me(n);t.push(i);const o=e[n];"string"==typeof o?r[i]=`${i}=${Me(o)}`:Array.isArray(o)&&(r[i]=o.slice(0).reduce(((e,t)=>e.concat([`${i}=${Me(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(Re(r));const i=await n.digest();return`${yt}\n${e}\n${t}\n${qe(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 Me(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(Re(i)),qe(await o.digest())}getSigningKey(e,t,r,n){return(async(e,t,r,n,i)=>{const o=`${r}:${n}:${i}:${qe(await Et(e,t.secretAccessKey,t.accessKeyId))}:${t.sessionToken}`;if(o in wt)return wt[o];for(St.push(o);St.length>50;)delete wt[St.shift()];let s=`AWS4${t.secretAccessKey}`;for(const t of[r,n,i,vt])s=await Et(e,s,t);return wt[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 $t=e=>{const t=(r=e,Mt(r).toISOString().replace(/\.\d{3}Z$/,"Z")).replace(/[\-:]/g,"");var r;return{longDate:t,shortDate:t.slice(0,8)}},Ft=e=>Object.keys(e).sort().join(";"),Ut=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,rt,it)),t||(t=e.credentialDefaultProvider?Ee(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?Ee(e.signer):e.regionInfoProvider?()=>Ee(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||Nt)(c)})):async r=>{const i=(r=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await Ee(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||Nt)(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}},Lt=(e,t)=>{const r=[];if(e&&r.push(e),t)for(const e of t)r.push(e);return r},Dt=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,Bt=()=>{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 Lt(t.name,t.aliases))s[e]=t;n.push(t)})),t.forEach((e=>{const t={...e,before:[],after:[]};for(const e of Lt(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 ${Dt(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)=>zt[t.step]-zt[e.step]||jt[t.priority||"normal"]-jt[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=Lt(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${Dt(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(`"${Dt(n.name,n.aliases)}" middleware with ${n.priority} priority in ${n.step} step cannot be overridden by "${Dt(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=Lt(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${Dt(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(`"${Dt(n.name,n.aliases)}" middleware ${n.relation} "${n.toMiddleware}" middleware cannot be overridden by "${Dt(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(Bt()),use:e=>{e.applyToStack(a)},remove:r=>"string"==typeof r?(r=>{let i=!1;const o=e=>{const t=Lt(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 Lt(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=Lt(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(Bt());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 Dt(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},zt={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},jt={high:3,normal:2,low:1};class qt{constructor(e){this.config=e,this.middlewareStack=Bt()}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 Ht{constructor(){this.middlewareStack=Bt()}static classBuilder(){return new Wt}resolveMiddlewareWithContext(e,t,r,{middlewareFn:n,clientName:i,commandName:o,inputFilterSensitiveLog:s,outputFilterSensitiveLog:a,smithyContext:c,additionalContext:d,CommandCtor:u}){for(const i of n.bind(this)(u,e,t,r))this.middlewareStack.use(i);const l=e.concat(this.middlewareStack),{logger:h}=t,p={logger:h,clientName:i,commandName:o,inputFilterSensitiveLog:s,outputFilterSensitiveLog:a,[q]:{commandInstance:this,...c},...d},{requestHandler:f}=t;return l.resolve((e=>f.handle(e.request,r||{})),p)}}class Wt{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 Ht{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 Kt="***SensitiveInformation***",Vt=e=>{switch(e){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${e}"`)}},Qt=Math.ceil(2**127*(2-2**-23)),Gt=e=>{const t=(e=>{if(null!=e){if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&lr.warn(ur(`Expected number but observed string: ${e}`)),t}if("number"==typeof e)return e;throw new TypeError(`Expected number, got ${typeof e}: ${e}`)}})(e);if(void 0!==t&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0&&Math.abs(t)>Qt)throw new TypeError(`Expected 32-bit float, got ${e}`);return t},Jt=e=>{if(null!=e){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw new TypeError(`Expected integer, got ${typeof e}: ${e}`)}},Yt=e=>er(e,32),Xt=e=>er(e,16),Zt=e=>er(e,8),er=(e,t)=>{const r=Jt(e);if(void 0!==r&&tr(r,t)!==r)throw new TypeError(`Expected ${t}-bit integer, got ${e}`);return r},tr=(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]}},rr=(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},nr=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}`)},ir=e=>{if(null!=e){if("string"==typeof e)return e;if(["boolean","number","bigint"].includes(typeof e))return lr.warn(ur(`Expected string, got ${typeof e}: ${e}`)),String(e);throw new TypeError(`Expected string, got ${typeof e}: ${e}`)}},or=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,sr=e=>{const t=e.match(or);if(null===t||t[0].length!==e.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(e)},ar=e=>Jt("string"==typeof e?sr(e):e),cr=e=>Yt("string"==typeof e?sr(e):e),dr=e=>Xt("string"==typeof e?sr(e):e),ur=e=>String(new TypeError(e).stack||e).split("\n").slice(0,5).filter((e=>!e.includes("stackTraceWarning"))).join("\n"),lr={warn:console.warn},hr=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],pr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function fr(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}`,d=s<10?`0${s}`:`${s}`,u=a<10?`0${a}`:`${a}`;return`${hr[n]}, ${i<10?`0${i}`:`${i}`} ${pr[r]} ${t} ${c}:${d}:${u} GMT`}const gr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),mr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-3339 date-times must be expressed as strings");const t=gr.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");const[r,n,i,o,s,a,c,d,u]=t,l=dr(Ir(n)),h=Rr(i,"month",1,12),p=Rr(o,"day",1,31),f=Sr(l,h,p,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:d});return"Z"!=u.toUpperCase()&&f.setTime(f.getTime()-Pr(u)),f},yr=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$/),br=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$/),vr=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})$/),wr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-7231 date-times must be expressed as strings");let t=yr.exec(e);if(t){const[e,r,n,i,o,s,a,c]=t;return Sr(dr(Ir(i)),xr(n),Rr(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c})}if(t=br.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return Er(Sr(kr(i),xr(n),Rr(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c}))}if(t=vr.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return Sr(dr(Ir(c)),xr(r),Rr(n.trimLeft(),"day",1,31),{hours:i,minutes:o,seconds:s,fractionalMilliseconds:a})}throw new TypeError("Invalid RFC-7231 date-time value")},Sr=(e,t,r,n)=>{const i=t-1;return Cr(e,i,r),new Date(Date.UTC(e,i,r,Rr(n.hours,"hour",0,23),Rr(n.minutes,"minute",0,59),Rr(n.seconds,"seconds",0,60),Or(n.fractionalMilliseconds)))},kr=e=>{const t=(new Date).getUTCFullYear(),r=100*Math.floor(t/100)+dr(Ir(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,xr=e=>{const t=pr.indexOf(e);if(t<0)throw new TypeError(`Invalid month: ${e}`);return t+1},Ar=[31,28,31,30,31,30,31,31,30,31,30,31],Cr=(e,t,r)=>{let n=Ar[t];if(1===t&&Tr(e)&&(n=29),r>n)throw new TypeError(`Invalid day for ${pr[t]} in ${e}: ${r}`)},Tr=e=>e%4==0&&(e%100!=0||e%400==0),Rr=(e,t,r,n)=>{const i=(e=>Zt("string"==typeof e?sr(e):e))(Ir(e));if(in)throw new TypeError(`${t} must be between ${r} and ${n}, inclusive`);return i},Or=e=>null==e?0:1e3*(e=>Gt("string"==typeof e?sr(e):e))("0."+e),Pr=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},Ir=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},Nr=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"]}),$r=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{}}},Fr=e=>{const t=[];for(const r in z){const n=z[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}}},Ur=e=>{const t={};return e.checksumAlgorithms().forEach((e=>{t[e.algorithmId()]=e.checksumConstructor()})),t},Lr=e=>{let t=e.retryStrategy;return{setRetryStrategy(e){t=e},retryStrategy:()=>t}},Dr=e=>{const t={};return t.retryStrategy=e.retryStrategy(),t},Br=e=>({...Fr(e),...Lr(e)}),zr=e=>({...Ur(e),...Dr(e)}),jr=e=>Array.isArray(e)?e:[e],qr=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]=qr(e[r]));return e},Hr=e=>null!=e,Wr=function(){const e=Object.getPrototypeOf(this).constructor,t=new(Function.bind.apply(String,[null,...arguments]));return Object.setPrototypeOf(t,e.prototype),t};Wr.prototype=Object.create(String.prototype,{constructor:{value:Wr,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(Wr,String);class Kr{trace(){}debug(){}info(){}warn(){}error(){}}function Vr(e,t,r){let n,i,o;if(void 0===t&&void 0===r)n={},o=e;else{if(n=e,"function"==typeof t)return i=t,o=r,Qr(n,i,o);o=t}for(const e of Object.keys(o))Array.isArray(o[e])?Gr(n,null,o,e):n[e]=o[e];return n}const Qr=(e,t,r)=>Vr(e,Object.entries(r).reduce(((e,[r,n])=>(Array.isArray(n)?e[r]=n:e[r]="function"==typeof n?[t,n()]:[t,n],e)),{})),Gr=(e,t,r,n)=>{if(null!==t){let i=r[n];"function"==typeof i&&(i=[,i]);const[o=Jr,s=Yr,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)}},Jr=e=>null!=e,Yr=e=>e;function Xr(e){return(e.includes(",")||e.includes('"'))&&(e=`"${e.replace(/"/g,'\\"')}"`),e}function Zr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var en={},tn={};!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 fn("InvalidXml","XML declaration allowed only at the start of the document.",mn(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}}return t}function an(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}en.validate=function(e,t){t=Object.assign({},nn,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++)d+=e[s];if(d=d.trim(),"/"===d[d.length-1]&&(d=d.substring(0,d.length-1),s--),o=d,!rn.isName(o)){let t;return t=0===d.trim().length?"Invalid space after '<'.":"Tag '"+d+"' is an invalid name.",fn("InvalidTag",t,mn(e,s))}const u=un(e,s);if(!1===u)return fn("InvalidAttr","Attributes for '"+d+"' have open quote.",mn(e,s));let l=u.value;if(s=u.index,"/"===l[l.length-1]){const r=s-l.length;l=l.substring(0,l.length-1);const i=hn(l,t);if(!0!==i)return fn(i.err.code,i.err.msg,mn(e,r+i.err.line));n=!0}else if(c){if(!u.tagClosed)return fn("InvalidTag","Closing tag '"+d+"' doesn't have proper closing.",mn(e,s));if(l.trim().length>0)return fn("InvalidTag","Closing tag '"+d+"' can't have attributes or invalid starting.",mn(e,a));if(0===r.length)return fn("InvalidTag","Closing tag '"+d+"' has not been opened.",mn(e,a));{const t=r.pop();if(d!==t.tagName){let r=mn(e,t.tagStartPos);return fn("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+d+"'.",mn(e,a))}0==r.length&&(i=!0)}}else{const o=hn(l,t);if(!0!==o)return fn(o.err.code,o.err.msg,mn(e,s-l.length+o.err.line));if(!0===i)return fn("InvalidXml","Multiple possible root nodes found.",mn(e,s));-1!==t.unpairedTags.indexOf(d)||r.push({tagName:d,tagStartPos:a}),n=!0}for(s++;s0)||fn("InvalidXml","Invalid '"+JSON.stringify(r.map((e=>e.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):fn("InvalidXml","Start tag expected.",1)};const cn='"',dn="'";function un(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 ln=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function hn(e,t){const r=rn.getAllMatches(e,ln),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}};bn.buildOptions=function(e){return Object.assign({},vn,e)},bn.defaultOptions=vn;const wn=tn;function Sn(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&&En(e,t))t+=7,[entityName,val,t]=Sn(e,t+1),-1===val.indexOf("&")&&(r[Tn(entityName)]={regx:RegExp(`&${entityName};`,"g"),val:val});else if(i&&xn(e,t))t+=8;else if(i&&An(e,t))t+=8;else if(i&&Cn(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 On=/^[-+]?0x[a-fA-F0-9]+$/,Pn=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,In={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};const _n=tn,Mn=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})}},Nn=Rn,$n=function(e,t={}){if(t=Object.assign({},In,t),!e||"string"!=typeof e)return e;let r=e.trim();if(void 0!==t.skipLike&&t.skipLike.test(r))return e;if("0"===e)return 0;if(t.hex&&On.test(r))return function(e,t){if(parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(r,16);if(-1!==r.search(/[eE]/)){const n=r.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);if(n){if(t.leadingZeros)r=(n[1]||"")+n[3];else if("0"!==n[2]||"."!==n[3][0])return e;return t.eNotation?Number(r):e}return e}{const n=Pn.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]);if(!t.leadingZeros&&o.length>0&&i&&"."!==r[2])return e;if(!t.leadingZeros&&o.length>0&&!i&&"."!==r[1])return e;if(t.leadingZeros&&o===e)return 0;{const n=Number(r),a=""+n;return-1!==a.search(/[eE]/)?t.eNotation?n:e:-1!==r.indexOf(".")?"0"===a&&""===s||a===s||i&&a==="-"+s?n:e:o?s===a||i+s===a?n:e:r===a||r===i+a?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 Gn(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?Gn(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function Ln(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 Dn=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,Dn),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=Vn(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 Mn(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=Kn(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=Nn(e,o);this.docTypeEntities=t.entities,o=t.i}else if("!["===e.substr(o+1,2)){const t=Kn(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=Vn(e,o,this.options.removeNSPrefix),a=s.tagName;const c=s.rawTagName;let d=s.tagExp,u=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(d.length>0&&d.lastIndexOf("/")===d.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),i=i.substr(0,i.length-1),d=a):d=d.substr(0,d.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 Mn(a);a!==d&&u&&(n[":@"]=this.buildAttributesMap(d,i,a)),t&&(t=this.parseTextData(t,a,i,!0,u,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),n.add(this.options.textNodeName,t),this.addChild(r,n,i)}else{if(d.length>0&&d.lastIndexOf("/")===d.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),i=i.substr(0,i.length-1),d=a):d=d.substr(0,d.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const e=new Mn(a);a!==d&&u&&(e[":@"]=this.buildAttributesMap(d,i,a)),this.addChild(r,e,i),i=i.substr(0,i.lastIndexOf("."))}else{const e=new Mn(a);this.tagsNodeStack.push(r),a!==d&&u&&(e[":@"]=this.buildAttributesMap(d,i,a)),this.addChild(r,e,i),r=e}n="",o=l}}else n+=e[o]}return t.child};function jn(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 qn=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 Hn(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 Wn(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 Kn(e,t,r,n){const i=e.indexOf(t,r);if(-1===i)throw new Error(n);return i+t.length-1}function Vn(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=Kn(e,"?>",r+1,"StopNode is not closed.")}else if("!--"===e.substr(r+1,3)){r=Kn(e,"--\x3e",r+3,"StopNode is not closed.")}else if("!["===e.substr(r+1,2)){r=Kn(e,"]]>",r,"StopNode is not closed.")-2}else{const n=Vn(e,r,">");if(n){(n&&n.tagName)===t&&"/"!==n.tagExp[n.tagExp.length-1]&&i++,r=n.closeIndex}}}function Gn(e,t,r){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&$n(e,r)}return _n.isExist(e)?e:""}var Jn=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=zn,this.parseTextData=Un,this.resolveNameSpace=Ln,this.buildAttributesMap=Bn,this.isItStopNode=Wn,this.replaceEntitiesValue=qn,this.readStopNodeData=Qn,this.saveTextToParentTag=Hn,this.addChild=jn}},Yn={};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=di(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 u=n;""!==u&&(u+=t.indentBy);const l=n+`<${c}${di(a[":@"],t)}`,h=ai(a[c],t,d,u);-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 ci(e){const t=Object.keys(e);for(let r=0;r0&&t.processEntities)for(let r=0;r0&&(r="\n"),ai(e,t,"",r)},pi={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({},pi,e),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=yi),this.processTextOrObjNode=gi,this.options.format?(this.indentate=mi,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function gi(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 mi(e){return this.options.indentBy.repeat(e)}function yi(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}fi.prototype.build=function(e){return this.options.preserveOrder?hi(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)=>Ye(e,t).then((e=>t.utf8Encoder(e))))(e,t).then((e=>{if(e.length){const t=new bi.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]),qr(o)}return{}})),wi=async(e,t)=>{const r=await vi(e,t);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r},Si=[Z.CRC32,Z.CRC32C,Z.SHA1,Z.SHA256],ki=[Z.SHA256,Z.SHA1,Z.CRC32,Z.CRC32C],Ei=e=>e===Z.MD5?"content-md5":`x-amz-checksum-${e.toLowerCase()}`,xi=e=>void 0!==e&&"string"!=typeof e&&!ArrayBuffer.isView(e)&&!At(e);function Ai(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 Ci(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 Ri(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 Oi(e){return"string"==typeof e?0===e.length:0===e.byteLength}function Pi(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}function Ii(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^Ni[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}(),Ni=Ii([0,4067132163,3778769143,324072436,3348797215,904991772,648144872,3570033899,2329499855,2024987596,1809983544,2575936315,1296289744,3207089363,2893594407,1578318884,274646895,3795141740,4049975192,51262619,3619967088,632279923,922689671,3298075524,2592579488,1760304291,2075979607,2312596564,1562183871,2943781820,3156637768,1313733451,549293790,3537243613,3246849577,871202090,3878099393,357341890,102525238,4101499445,2858735121,1477399826,1264559846,3107202533,1845379342,2677391885,2361733625,2125378298,820201905,3263744690,3520608582,598981189,4151959214,85089709,373468761,3827903834,3124367742,1213305469,1526817161,2842354314,2107672161,2412447074,2627466902,1861252501,1098587580,3004210879,2688576843,1378610760,2262928035,1955203488,1742404180,2511436119,3416409459,969524848,714683780,3639785095,205050476,4266873199,3976438427,526918040,1361435347,2739821008,2954799652,1114974503,2529119692,1691668175,2005155131,2247081528,3690758684,697762079,986182379,3366744552,476452099,3993867776,4250756596,255256311,1640403810,2477592673,2164122517,1922457750,2791048317,1412925310,1197962378,3037525897,3944729517,427051182,170179418,4165941337,746937522,3740196785,3451792453,1070968646,1905808397,2213795598,2426610938,1657317369,3053634322,1147748369,1463399397,2773627110,4215344322,153784257,444234805,3893493558,1021025245,3467647198,3722505002,797665321,2197175160,1889384571,1674398607,2443626636,1164749927,3070701412,2757221520,1446797203,137323447,4198817972,3910406976,461344835,3484808360,1037989803,781091935,3705997148,2460548119,1623424788,1939049696,2180517859,1429367560,2807687179,3020495871,1180866812,410100952,3927582683,4182430767,186734380,3756733383,763408580,1053836080,3434856499,2722870694,1344288421,1131464017,2971354706,1708204729,2545590714,2229949006,1988219213,680717673,3673779818,3383336350,1002577565,4010310262,493091189,238226049,4233660802,2987750089,1082061258,1395524158,2705686845,1972364758,2279892693,2494862625,1725896226,952904198,3399985413,3656866545,731699698,4283874585,222117402,510512622,3959836397,3280807620,837199303,582374963,3504198960,68661723,4135334616,3844915500,390545967,1230274059,3141532936,2825850620,1510247935,2395924756,2091215383,1878366691,2644384480,3553878443,565732008,854102364,3229815391,340358836,3861050807,4117890627,119113024,1493875044,2875275879,3090270611,1247431312,2660249211,1828433272,2141937292,2378227087,3811616794,291187481,34330861,4032846830,615137029,3603020806,3314634738,939183345,1776939221,2609017814,2295496738,2058945313,2926798794,1545135305,1330124605,3173225534,4084100981,17165430,307568514,3762199681,888469610,3332340585,3587147933,665062302,2042050490,2346497209,2559330125,1793573966,3190661285,1279665062,1595330642,2910671697]);function $i(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))}function 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^Di[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}(),Di=Ii([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)=>({[Z.MD5]:t.md5,[Z.CRC32]:Ui,[Z.CRC32C]:_i,[Z.SHA1]:t.sha1,[Z.SHA256]:t.sha256}[e]),zi=(e,t)=>{const r=new e;return r.update(Re(t||"")),r.digest()},ji={name:"flexibleChecksumsMiddleware",step:"build",tags:["BODY_CHECKSUM"],override:!0},qi=(e,t)=>(r,n)=>async i=>{if(!K.isInstance(i.request))return r(i);const{request:o,input:s}=i,{body:a,headers:c}=o,{base64Encoder:d,streamHasher:u}=e,{requestChecksumRequired:l,requestAlgorithmMember:h}=t,p=((e,{requestChecksumRequired:t,requestAlgorithmMember:r},n)=>{const i=n?re:te;if(!r||!e[r])return t?i:void 0;const o=e[r];if(!Si.includes(o))throw new Error(`The checksum algorithm "${o}" is not supported by the client. Select one of ${Si}.`);return o})(s,{requestChecksumRequired:l,requestAlgorithmMember:h},!!n.isS3ExpressBucket);let f=a,g=c;if(p){switch(p){case Z.CRC32:ie(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32","U");break;case Z.CRC32C:ie(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32C","V");break;case Z.SHA1:ie(n,"FLEXIBLE_CHECKSUMS_REQ_SHA1","X");break;case Z.SHA256:ie(n,"FLEXIBLE_CHECKSUMS_REQ_SHA256","Y")}const t=Ei(p),r=Bi(p,e);if(xi(a)){const{getAwsChunkedEncodingStream:n,bodyLengthChecker:i}=e;f=n(a,{base64Encoder:d,bodyLengthChecker:i,checksumLocationName:t,checksumAlgorithmFn:r,streamHasher:u}),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 zi(r,a);g={...c,[t]:d(e)}}}return await r({...i,request:{...o,headers:g,body:f}})},Hi=(e=[])=>{const t=[];for(const r of ki)e.includes(r)&&Si.includes(r)&&t.push(r);return t};function Wi(e){return new Blob([e]).stream()}const Ki=async(e,{checksumAlgorithmFn:t,base64Encoder:r})=>r(await zi(t,e)),Vi={name:"flexibleChecksumsResponseMiddleware",toMiddleware:"deserializerMiddleware",relation:"after",tags:["BODY_CHECKSUM"],override:!0},Qi=(e,t)=>(r,n)=>async i=>{if(!K.isInstance(i.request))return r(i);const o=i.input,s=await r(i),a=s.response;let c;const{requestValidationModeMember:d,responseAlgorithms:u}=t;if(d&&"ENABLED"===o[d]){const{clientName:t,commandName:r}=n;if("S3Client"===t&&"GetObjectCommand"===r&&Hi(u).every((e=>{const t=Ei(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=xi(a.body);i&&(c=await e.streamCollector(a.body),a.body=Wi(c)),await(async(e,{config:t,responseAlgorithms:r})=>{const n=Hi(r),{body:i,headers:o}=e;for(const r of n){const n=Ei(r),s=o[n];if(s){const o=Bi(r,t),{base64Encoder:a}=t;if(xi(i))return void(e.body=Je({expectedChecksum:s,checksumSourceLocation:n,checksum:new o,source:i,base64Encoder:a}));const c=await Ki(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:u}),i&&c&&(a.body=Wi(c))}return s},Gi=(e,t)=>({applyToStack:r=>{r.add(qi(e,t),ji),r.addRelativeTo(Qi(e,t),Vi)}});const Ji={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},Yi=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{if(!K.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),Ji)}}),Xi={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},Zi="X-Amzn-Trace-Id",eo={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},to=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{const{request:n}=r;if(!K.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),eo)}});const ro={step:"finalizeRequest",tags:["CHECK_CONTENT_LENGTH_HEADER"],name:"getCheckContentLengthHeaderPlugin",override:!0},no=e=>({applyToStack:e=>{e.add(((e,t)=>async r=>{const{request:n}=r;if(K.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 Kr?console.warn(e):t.logger.warn(e)}return e({...r})}),ro)}}),io={tags:["REGION_REDIRECT","S3"],name:"regionRedirectEndpointMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};const oo={step:"initialize",tags:["REGION_REDIRECT","S3"],name:"regionRedirectMiddleware",override:!0},so=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),oo),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),io)}}),ao={tags:["S3"],name:"s3ExpiresMiddleware",override:!0,relation:"after",toMiddleware:"deserializerMiddleware"},co=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{const n=await e(r),{response:i}=n;if(V.isInstance(i)&&i.headers.expires){i.headers.expiresstring=i.headers.expires;try{wr(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}),ao)}});class uo{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+uo.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 lo(Promise.resolve(e)))}))),e})):n.set(r,new lo(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 po;ho.REFRESH_WINDOW_MS=6e4,function(e){e.ENV="env",e.CONFIG="shared config entry"}(po||(po={}));const fo="X-Amz-S3session-Token",go=fo.toLowerCase();class mo extends Nt{async signWithCredentials(e,t,r){const n=yo(t);e.headers[go]=t.sessionToken;return bo(this,n),this.signRequest(e,r??{})}async presignWithCredentials(e,t,r){const n=yo(t);delete e.headers[go],e.headers[fo]=t.sessionToken,e.query=e.query??{},e.query[fo]=t.sessionToken;return bo(this,n),this.presign(e,r)}}function yo(e){return{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,expiration:e.expiration}}function bo(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},wo=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)&&(ie(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,K.isInstance(n.request)&&i.sessionToken&&(n.request.headers[go]=i.sessionToken)}}}return t(n)})(e),vo)}}),So=e=>e=>{throw e},ko=(e,t)=>{},Eo=e=>(t,r)=>async n=>{if(!K.isInstance(n.request))return t(n);const i=he(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 d=await t({...n,request:c}).catch((a.errorHandler||So)(o));return(a.successHandler||ko)(d.response,o),d},xo={CopyObjectCommand:!0,UploadPartCopyCommand:!0,CompleteMultipartUploadCommand:!0},Ao=e=>(t,r)=>async n=>{const i=await t(n),{response:o}=i;if(!V.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,d=a;!a||"object"!=typeof a||a instanceof Uint8Array||([c,d]=await async function(e){return"function"==typeof e.stream&&(e=e.stream()),e.tee()}(a)),o.body=d;const u=await Co(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(u.subarray(u.length-16));if(0===u.length&&xo[r.commandName]){const e=new Error("S3 aborted request");throw e.name="InternalError",e}return l&&l.endsWith("")&&(o.statusCode=400),i},Co=(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},Ro=e=>({applyToStack:t=>{t.addRelativeTo(Ao(e),To)}});const Oo={name:"bucketEndpointMiddleware",override:!0,relation:"after",toMiddleware:"endpointV2Middleware"};const Po={step:"initialize",tags:["VALIDATE_BUCKET_NAME"],name:"validateBucketNameMiddleware",override:!0},Io=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),Po),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),Oo)}});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}$"),Mo=e=>_o.test(e)||e.startsWith("[")&&e.endsWith("]"),No=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),$o=(e,t=!1)=>{if(!t)return No.test(e);const r=e.split(".");for(const e of r)if(!$o(e))return!1;return!0},Fo={},Uo="endpoints";function Lo(e){return"object"!=typeof e||null==e?e:"ref"in e?`$${Lo(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(Lo).join(", ")})`:JSON.stringify(e,null,2)}class Do 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 Do(`Path: '${e}' does not end with ']'`);const i=n.slice(t+1,-1);if(Number.isNaN(parseInt(i)))throw new Do(`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 Do(`Index '${n}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(r)?r[parseInt(n)]:r[n]}),e),zo={[B.HTTP]:80,[B.HTTPS]:443},jo={booleanEquals:(e,t)=>e===t,getAttr:Bo,isSet:e=>null!=e,isValidHostLabel:$o,not:e=>!e,parseURL:e=>{const t=(()=>{try{if(e instanceof URL)return e;if("object"==typeof e&&"hostname"in e){const{hostname:t,port:r,protocol:n="",path:i="",query:o={}}=e,s=new URL(`${n}//${t}${r?`:${r}`:""}${i}`);return s.search=Object.entries(o).map((([e,t])=>`${e}=${t}`)).join("&"),s}return new URL(e)}catch(e){return null}})();if(!t)return console.error(`Unable to parse ${JSON.stringify(e)} as a whatwg URL.`),null;const r=t.href,{host:n,hostname:i,pathname:o,protocol:s,search:a}=t;if(a)return null;const c=s.slice(0,-1);if(!Object.values(B).includes(c))return null;const d=Mo(i);return{scheme:c,authority:`${n}${r.includes(`${n}:${zo[c]}`)||"string"==typeof e&&e.includes(`${n}:${zo[c]}`)?`:${zo[c]}`:""}`,path:o,normalizedPath:o.endsWith("/")?o:`${o}/`,isIp:d}},stringEquals:(e,t)=>e===t,substring:(e,t,r,n)=>t>=r||e.lengthencodeURIComponent(e).replace(/[!*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))},qo=(e,t)=>{const r=[],n={...t.endpointParams,...t.referenceRecord};let i=0;for(;i{if("string"==typeof e)return qo(e,r);if(e.fn)return Wo(e,r);if(e.ref)return(({ref:e},t)=>({...t.endpointParams,...t.referenceRecord}[e]))(e,r);throw new Do(`'${t}': ${String(e)} is not a string, function or reference.`)},Wo=({fn:e,argv:t},r)=>{const n=t.map((e=>["boolean","number"].includes(typeof e)?e:Ho(e,"arg",r))),i=e.split(".");return i[0]in Fo&&null!=i[1]?Fo[i[0]][i[1]](...n):jo[e](...n)},Ko=({assign:e,...t},r)=>{if(e&&e in r.referenceRecord)throw new Do(`'${e}' is already defined in Reference Record.`);const n=Wo(t,r);return r.logger?.debug?.(`${Uo} evaluateCondition: ${Lo(t)} = ${Lo(n)}`),{result:""===n||!!n,...null!=e&&{toAssign:{name:e,value:n}}}},Vo=(e=[],t)=>{const r={};for(const n of e){const{result:e,toAssign:i}=Ko(n,{...t,referenceRecord:{...t.referenceRecord,...r}});if(!e)return{result:e};i&&(r[i.name]=i.value,t.logger?.debug?.(`${Uo} assign: ${i.name} := ${Lo(i.value)}`))}return{result:!0,referenceRecord:r}},Qo=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:n.map((e=>{const n=Ho(e,"Header value entry",t);if("string"!=typeof n)throw new Do(`Header '${r}' value '${n}' is not a string`);return n}))})),{}),Go=(e,t)=>{if(Array.isArray(e))return e.map((e=>Go(e,t)));switch(typeof e){case"string":return qo(e,t);case"object":if(null===e)throw new Do(`Unexpected endpoint property: ${e}`);return Jo(e,t);case"boolean":return e;default:throw new Do("Unexpected endpoint property type: "+typeof e)}},Jo=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:Go(n,t)})),{}),Yo=(e,t)=>{const r=Ho(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 Do("Endpoint URL must be a string, got "+typeof r)},Xo=(e,t)=>{const{conditions:r,endpoint:n}=e,{result:i,referenceRecord:o}=Vo(r,t);if(!i)return;const s={...t,referenceRecord:{...t.referenceRecord,...o}},{url:a,properties:c,headers:d}=n;return t.logger?.debug?.(`${Uo} Resolving endpoint from template: ${Lo(n)}`),{...null!=d&&{headers:Qo(d,s)},...null!=c&&{properties:Jo(c,s)},url:Yo(a,s)}},Zo=(e,t)=>{const{conditions:r,error:n}=e,{result:i,referenceRecord:o}=Vo(r,t);if(i)throw new Do(Ho(n,"Error",{...t,referenceRecord:{...t.referenceRecord,...o}}))},es=(e,t)=>{const{conditions:r,rules:n}=e,{result:i,referenceRecord:o}=Vo(r,t);if(i)return ts(n,{...t,referenceRecord:{...t.referenceRecord,...o}})},ts=(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 Do(`Unknown endpoint rule: ${r}`);{const e=es(r,t);if(e)return e}}throw new Do("Rules evaluation failed")},rs=(e,t=!1)=>{if(t){for(const t of e.split("."))if(!rs(t))return!1;return!0}return!!$o(e)&&(!(e.length<3||e.length>63)&&(e===e.toLowerCase()&&!Mo(e)))};let ns={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 is={isVirtualHostableS3Bucket:rs,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}=ns;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=is;const os=/\d{12}\.ddb/;const ss="user-agent",as="x-amz-user-agent",cs=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g,ds=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;const us=e=>(t,r)=>async n=>{const{request:i}=n;if(!K.isInstance(i))return t(n);const{headers:o}=i,s=r?.userAgent?.map(ls)||[],a=(await e.defaultUserAgentProvider()).map(ls);await async function(e,t,r){const n=r.request;if("rpc-v2-cbor"===n?.headers?.["smithy-protocol"]&&ie(e,"PROTOCOL_RPC_V2_CBOR","M"),"function"==typeof t.retryStrategy){const r=await t.retryStrategy();"function"==typeof r.acquireInitialRetryToken?r.constructor?.name?.includes("Adaptive")?ie(e,"RETRY_MODE_ADAPTIVE","F"):ie(e,"RETRY_MODE_STANDARD","E"):ie(e,"RETRY_MODE_LEGACY","D")}if("function"==typeof t.accountIdEndpointMode){const r=e.endpointV2;switch(String(r?.url?.hostname).match(os)&&ie(e,"ACCOUNT_ID_ENDPOINT","O"),await(t.accountIdEndpointMode?.())){case"disabled":ie(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":ie(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":ie(e,"ACCOUNT_ID_MODE_REQUIRED","R")}}const i=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const t=i;t.accountId&&ie(e,"RESOLVED_ACCOUNT_ID","T");for(const[r,n]of Object.entries(t.$source??{}))ie(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 d=e?.customUserAgent?.map(ls)||[],u=await e.userAgentAppId();u&&a.push(ls([`app/${u}`]));const l=[].concat([...a,...s,...d]).join(" "),h=[...a.filter((e=>e.startsWith("aws-sdk-"))),...d].join(" ");return"browser"!==e.runtime?(h&&(o[as]=o[as]?`${o[ss]} ${h}`:h),o[ss]=l):o[as]=l,t({...n,request:i})},ls=e=>{const t=e[0].split("/").map((e=>e.replace(cs,"-"))).join("/"),r=e[1]?.replace(ds,"-"),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}`}}),"")},hs={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},ps=e=>"string"==typeof e&&(e.startsWith("fips-")||e.endsWith("-fips")),fs=e=>ps(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,gs="content-length";const ms={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},ys=e=>({applyToStack:t=>{var r;t.add((r=e.bodyLengthChecker,e=>async t=>{const n=t.request;if(K.isInstance(n)){const{body:e,headers:t}=n;if(e&&-1===Object.keys(t).map((e=>e.toLowerCase())).indexOf(gs))try{const t=r(e);n.headers={...n.headers,[gs]:String(t)}}catch(e){}}return e({...t,request:n})}),ms)}}),bs=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,vs=/(\d+\.){3}\d+/,ws=/\.\./,Ss=e=>bs.test(e)&&!vs.test(e)&&!ws.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},Es=(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},xs=async e=>{};const As=e=>{if("string"==typeof e)return As(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}},Cs=e=>"object"==typeof e?"url"in e?As(e.url):e:As(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 Es(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(!Ss(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},Rs=({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 xs(r.serviceId),e&&(r.endpoint=()=>Promise.resolve(Cs(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=he(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})},Os={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:ye.name},Ps=(e,t)=>({applyToStack:r=>{r.addRelativeTo(Rs({config:e,instructions:t}),Os)}});var Is;!function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"}(Is||(Is={}));const _s=Is.STANDARD,Ms=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Ns=["TimeoutError","RequestTimeout","RequestTimeoutException"],$s=[500,502,503,504],Fs=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],Us=e=>429===e.$metadata?.httpStatusCode||Ms.includes(e.name)||1==e.$retryable?.throttling,Ls=e=>(e=>e.$metadata?.clockSkewCorrected)(e)||Ns.includes(e.name)||Fs.includes(e?.code||"")||$s.includes(e.$metadata?.httpStatusCode||0);class Ds{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=>Ds.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(),Us(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))}}Ds.setTimeoutFn=setTimeout;const Bs=({retryDelay:e,retryCount:t,retryCost:r})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(2e4,e),getRetryCost:()=>r});class zs{constructor(e){this.maxAttempts=e,this.mode=Is.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 js{constructor(e,t){this.maxAttemptsProvider=e,this.mode=Is.ADAPTIVE;const{rateLimiter:r}=t??{};this.rateLimiter=r??new Ds,this.standardRetryStrategy=new zs(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 qs;const Hs=new Uint8Array(16);function Ws(){if(!qs&&(qs="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!qs))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return qs(Hs)}const Ks=[];for(let e=0;e<256;++e)Ks.push((e+256).toString(16).slice(1));var Vs={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Qs(e,t,r){if(Vs.randomUUID&&!t&&!e)return Vs.randomUUID();const n=(e=e||{}).random||(e.rng||Ws)();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 Ks[e[t+0]]+Ks[e[t+1]]+Ks[e[t+2]]+Ks[e[t+3]]+"-"+Ks[e[t+4]]+Ks[e[t+5]]+"-"+Ks[e[t+6]]+Ks[e[t+7]]+"-"+Ks[e[t+8]]+Ks[e[t+9]]+"-"+Ks[e[t+10]]+Ks[e[t+11]]+Ks[e[t+12]]+Ks[e[t+13]]+Ks[e[t+14]]+Ks[e[t+15]]}(n)}const Gs=e=>e?.body instanceof ReadableStream,Js=e=>void 0!==e.acquireInitialRetryToken&&void 0!==e.refreshRetryTokenForRetry&&void 0!==e.recordSuccess,Ys=e=>{const t={error:e,errorType:Xs(e)},r=ta(e.$response);return r&&(t.retryAfterHint=r),t},Xs=e=>Us(e)?"THROTTLING":Ls(e)?"TRANSIENT":(e=>{if(void 0!==e.$metadata?.httpStatusCode){const t=e.$metadata.httpStatusCode;return 500<=t&&t<=599&&!Ls(e)}return!1})(e)?"SERVER_ERROR":"CLIENT_ERROR",Zs={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},ea=e=>({applyToStack:t=>{t.add((e=>(t,r)=>async n=>{let i=await e.retryStrategy();const o=await e.maxAttempts();if(!Js(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,d=0;const{request:u}=n,l=K.isInstance(u);for(l&&(u.headers["amz-sdk-invocation-id"]=Qs());;)try{l&&(u.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=d,{response:r,output:s}}catch(t){const n=Ys(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&&Gs(u))throw(r.logger instanceof Kr?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=d,a}c=e.getRetryCount();const o=e.getRetryDelay();d+=o,await new Promise((e=>setTimeout(e,o)))}}var s})(e),Zs)}}),ta=e=>{if(!V.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)},ra=null;class na{constructor(e){this.sigv4Signer=new mo(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=ra,"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 ia="required",oa="type",sa="conditions",aa="fn",ca="argv",da="ref",ua="assign",la="url",ha="properties",pa="backend",fa="authSchemes",ga="disableDoubleEncoding",ma="signingName",ya="signingRegion",ba="headers",va="signingRegionSet",wa=!0,Sa="isSet",ka="booleanEquals",Ea="error",xa="aws.partition",Aa="stringEquals",Ca="getAttr",Ta="name",Ra="substring",Oa="bucketSuffix",Pa="parseURL",Ia="{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",_a="endpoint",Ma="tree",Na="aws.isVirtualHostableS3Bucket",$a="{url#scheme}://{Bucket}.{url#authority}{url#path}",Fa="not",Ua="{url#scheme}://{url#authority}{url#path}",La="hardwareType",Da="regionPrefix",Ba="bucketAliasSuffix",za="outpostId",ja="isValidHostLabel",qa="sigv4a",Ha="s3-outposts",Wa="s3",Ka="{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}",Va="https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}",Qa="https://{Bucket}.s3.{partitionResult#dnsSuffix}",Ga="aws.parseArn",Ja="bucketArn",Ya="arnType",Xa="s3-object-lambda",Za="accesspoint",ec="accessPointName",tc="{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}",rc="mrapPartition",nc="outpostType",ic="arnPrefix",oc="{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}",sc="https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",ac="https://s3.{partitionResult#dnsSuffix}",cc={[ia]:!1,[oa]:"String"},dc={[ia]:!0,default:!1,[oa]:"Boolean"},uc={[ia]:!1,[oa]:"Boolean"},lc={[aa]:ka,[ca]:[{[da]:"Accelerate"},!0]},hc={[aa]:ka,[ca]:[{[da]:"UseFIPS"},!0]},pc={[aa]:ka,[ca]:[{[da]:"UseDualStack"},!0]},fc={[aa]:Sa,[ca]:[{[da]:"Endpoint"}]},gc={[aa]:xa,[ca]:[{[da]:"Region"}],[ua]:"partitionResult"},mc={[aa]:Aa,[ca]:[{[aa]:Ca,[ca]:[{[da]:"partitionResult"},Ta]},"aws-cn"]},yc={[aa]:Sa,[ca]:[{[da]:"Bucket"}]},bc={[da]:"Bucket"},vc={[aa]:Pa,[ca]:[{[da]:"Endpoint"}],[ua]:"url"},wc={[aa]:ka,[ca]:[{[aa]:Ca,[ca]:[{[da]:"url"},"isIp"]},!0]},Sc={[da]:"url"},kc={[aa]:"uriEncode",[ca]:[bc],[ua]:"uri_encoded_bucket"},Ec={[pa]:"S3Express",[fa]:[{[ga]:!0,[Ta]:"sigv4",[ma]:"s3express",[ya]:"{Region}"}]},xc={},Ac={[aa]:Na,[ca]:[bc,!1]},Cc={[Ea]:"S3Express bucket name is not a valid virtual hostable name.",[oa]:Ea},Tc={[pa]:"S3Express",[fa]:[{[ga]:!0,[Ta]:"sigv4-s3express",[ma]:"s3express",[ya]:"{Region}"}]},Rc={[aa]:Sa,[ca]:[{[da]:"UseS3ExpressControlEndpoint"}]},Oc={[aa]:ka,[ca]:[{[da]:"UseS3ExpressControlEndpoint"},!0]},Pc={[aa]:Fa,[ca]:[fc]},Ic={[Ea]:"Unrecognized S3Express bucket name format.",[oa]:Ea},_c={[aa]:Fa,[ca]:[yc]},Mc={[da]:La},Nc={[sa]:[Pc],[Ea]:"Expected a endpoint to be specified but no endpoint was found",[oa]:Ea},$c={[fa]:[{[ga]:!0,[Ta]:qa,[ma]:Ha,[va]:["*"]},{[ga]:!0,[Ta]:"sigv4",[ma]:Ha,[ya]:"{Region}"}]},Fc={[aa]:ka,[ca]:[{[da]:"ForcePathStyle"},!1]},Uc={[da]:"ForcePathStyle"},Lc={[aa]:ka,[ca]:[{[da]:"Accelerate"},!1]},Dc={[aa]:Aa,[ca]:[{[da]:"Region"},"aws-global"]},Bc={[fa]:[{[ga]:!0,[Ta]:"sigv4",[ma]:Wa,[ya]:"us-east-1"}]},zc={[aa]:Fa,[ca]:[Dc]},jc={[aa]:ka,[ca]:[{[da]:"UseGlobalEndpoint"},!0]},qc={[la]:"https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[ha]:{[fa]:[{[ga]:!0,[Ta]:"sigv4",[ma]:Wa,[ya]:"{Region}"}]},[ba]:{}},Hc={[fa]:[{[ga]:!0,[Ta]:"sigv4",[ma]:Wa,[ya]:"{Region}"}]},Wc={[aa]:ka,[ca]:[{[da]:"UseGlobalEndpoint"},!1]},Kc={[aa]:ka,[ca]:[{[da]:"UseDualStack"},!1]},Vc={[la]:"https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",[ha]:Hc,[ba]:{}},Qc={[aa]:ka,[ca]:[{[da]:"UseFIPS"},!1]},Gc={[la]:"https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",[ha]:Hc,[ba]:{}},Jc={[la]:"https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[ha]:Hc,[ba]:{}},Yc={[aa]:ka,[ca]:[{[aa]:Ca,[ca]:[Sc,"isIp"]},!1]},Xc={[la]:Ka,[ha]:Hc,[ba]:{}},Zc={[la]:$a,[ha]:Hc,[ba]:{}},ed={[_a]:Zc,[oa]:_a},td={[la]:Va,[ha]:Hc,[ba]:{}},rd={[la]:"https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",[ha]:Hc,[ba]:{}},nd={[Ea]:"Invalid region: region was not a valid DNS name.",[oa]:Ea},id={[da]:Ja},od={[da]:Ya},sd={[aa]:Ca,[ca]:[id,"service"]},ad={[da]:ec},cd={[sa]:[pc],[Ea]:"S3 Object Lambda does not support Dual-stack",[oa]:Ea},dd={[sa]:[lc],[Ea]:"S3 Object Lambda does not support S3 Accelerate",[oa]:Ea},ud={[sa]:[{[aa]:Sa,[ca]:[{[da]:"DisableAccessPoints"}]},{[aa]:ka,[ca]:[{[da]:"DisableAccessPoints"},!0]}],[Ea]:"Access points are not supported for this operation",[oa]:Ea},ld={[sa]:[{[aa]:Sa,[ca]:[{[da]:"UseArnRegion"}]},{[aa]:ka,[ca]:[{[da]:"UseArnRegion"},!1]},{[aa]:Fa,[ca]:[{[aa]:Aa,[ca]:[{[aa]:Ca,[ca]:[id,"region"]},"{Region}"]}]}],[Ea]:"Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",[oa]:Ea},hd={[aa]:Ca,[ca]:[{[da]:"bucketPartition"},Ta]},pd={[aa]:Ca,[ca]:[id,"accountId"]},fd={[fa]:[{[ga]:!0,[Ta]:"sigv4",[ma]:Xa,[ya]:"{bucketArn#region}"}]},gd={[Ea]:"Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",[oa]:Ea},md={[Ea]:"Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",[oa]:Ea},yd={[Ea]:"Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",[oa]:Ea},bd={[Ea]:"Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",[oa]:Ea},vd={[Ea]:"Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",[oa]:Ea},wd={[Ea]:"Invalid ARN: Expected a resource of the format `accesspoint:` but no name was provided",[oa]:Ea},Sd={[fa]:[{[ga]:!0,[Ta]:"sigv4",[ma]:Wa,[ya]:"{bucketArn#region}"}]},kd={[fa]:[{[ga]:!0,[Ta]:qa,[ma]:Ha,[va]:["*"]},{[ga]:!0,[Ta]:"sigv4",[ma]:Ha,[ya]:"{bucketArn#region}"}]},Ed={[aa]:Ga,[ca]:[bc]},xd={[la]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ha]:Hc,[ba]:{}},Ad={[la]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ha]:Hc,[ba]:{}},Cd={[la]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ha]:Hc,[ba]:{}},Td={[la]:oc,[ha]:Hc,[ba]:{}},Rd={[la]:"https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ha]:Hc,[ba]:{}},Od={[da]:"UseObjectLambdaEndpoint"},Pd={[fa]:[{[ga]:!0,[Ta]:"sigv4",[ma]:Xa,[ya]:"{Region}"}]},Id={[la]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[ha]:Hc,[ba]:{}},_d={[la]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}",[ha]:Hc,[ba]:{}},Md={[la]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[ha]:Hc,[ba]:{}},Nd={[la]:Ua,[ha]:Hc,[ba]:{}},$d={[la]:"https://s3.{Region}.{partitionResult#dnsSuffix}",[ha]:Hc,[ba]:{}},Fd=[{[da]:"Region"}],Ud=[{[da]:"Endpoint"}],Ld=[bc],Dd=[pc],Bd=[lc],zd=[fc,vc],jd=[{[aa]:Sa,[ca]:[{[da]:"DisableS3ExpressSessionAuth"}]},{[aa]:ka,[ca]:[{[da]:"DisableS3ExpressSessionAuth"},!0]}],qd=[wc],Hd=[kc],Wd=[Ac],Kd=[hc],Vd=[{[aa]:Ra,[ca]:[bc,6,14,!0],[ua]:"s3expressAvailabilityZoneId"},{[aa]:Ra,[ca]:[bc,14,16,!0],[ua]:"s3expressAvailabilityZoneDelim"},{[aa]:Aa,[ca]:[{[da]:"s3expressAvailabilityZoneDelim"},"--"]}],Qd=[{[sa]:[hc],[_a]:{[la]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ha]:Ec,[ba]:{}},[oa]:_a},{[_a]:{[la]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ha]:Ec,[ba]:{}},[oa]:_a}],Gd=[{[aa]:Ra,[ca]:[bc,6,15,!0],[ua]:"s3expressAvailabilityZoneId"},{[aa]:Ra,[ca]:[bc,15,17,!0],[ua]:"s3expressAvailabilityZoneDelim"},{[aa]:Aa,[ca]:[{[da]:"s3expressAvailabilityZoneDelim"},"--"]}],Jd=[{[sa]:[hc],[_a]:{[la]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ha]:Tc,[ba]:{}},[oa]:_a},{[_a]:{[la]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ha]:Tc,[ba]:{}},[oa]:_a}],Yd=[yc],Xd=[{[aa]:ja,[ca]:[{[da]:za},!1]}],Zd=[{[aa]:Aa,[ca]:[{[da]:Da},"beta"]}],eu=[gc],tu=[{[aa]:ja,[ca]:[{[da]:"Region"},!1]}],ru=[{[aa]:Aa,[ca]:[{[da]:"Region"},"us-east-1"]}],nu=[{[aa]:Aa,[ca]:[od,Za]}],iu=[{[aa]:Ca,[ca]:[id,"resourceId[1]"],[ua]:ec},{[aa]:Fa,[ca]:[{[aa]:Aa,[ca]:[ad,""]}]}],ou=[id,"resourceId[1]"],su=[{[aa]:Fa,[ca]:[{[aa]:Aa,[ca]:[{[aa]:Ca,[ca]:[id,"region"]},""]}]}],au=[{[aa]:Fa,[ca]:[{[aa]:Sa,[ca]:[{[aa]:Ca,[ca]:[id,"resourceId[2]"]}]}]}],cu=[id,"resourceId[2]"],du=[{[aa]:xa,[ca]:[{[aa]:Ca,[ca]:[id,"region"]}],[ua]:"bucketPartition"}],uu=[{[aa]:Aa,[ca]:[hd,{[aa]:Ca,[ca]:[{[da]:"partitionResult"},Ta]}]}],lu=[{[aa]:ja,[ca]:[{[aa]:Ca,[ca]:[id,"region"]},!0]}],hu=[{[aa]:ja,[ca]:[pd,!1]}],pu=[{[aa]:ja,[ca]:[ad,!1]}],fu=[{[aa]:ja,[ca]:[{[da]:"Region"},!0]}],gu={version:"1.0",parameters:{Bucket:cc,Region:cc,UseFIPS:dc,UseDualStack:dc,Endpoint:cc,ForcePathStyle:dc,Accelerate:dc,UseGlobalEndpoint:dc,UseObjectLambdaEndpoint:uc,Key:cc,Prefix:cc,CopySource:cc,DisableAccessPoints:uc,DisableMultiRegionAccessPoints:dc,UseArnRegion:uc,UseS3ExpressControlEndpoint:uc,DisableS3ExpressSessionAuth:uc},rules:[{[sa]:[{[aa]:Sa,[ca]:Fd}],rules:[{[sa]:[lc,hc],error:"Accelerate cannot be used with FIPS",[oa]:Ea},{[sa]:[pc,fc],error:"Cannot set dual-stack in combination with a custom endpoint.",[oa]:Ea},{[sa]:[fc,hc],error:"A custom endpoint cannot be combined with FIPS",[oa]:Ea},{[sa]:[fc,lc],error:"A custom endpoint cannot be combined with S3 Accelerate",[oa]:Ea},{[sa]:[hc,gc,mc],error:"Partition does not support FIPS",[oa]:Ea},{[sa]:[yc,{[aa]:Ra,[ca]:[bc,0,6,wa],[ua]:Oa},{[aa]:Aa,[ca]:[{[da]:Oa},"--x-s3"]}],rules:[{[sa]:Dd,error:"S3Express does not support Dual-stack.",[oa]:Ea},{[sa]:Bd,error:"S3Express does not support S3 Accelerate.",[oa]:Ea},{[sa]:zd,rules:[{[sa]:jd,rules:[{[sa]:qd,rules:[{[sa]:Hd,rules:[{endpoint:{[la]:Ia,[ha]:Ec,[ba]:xc},[oa]:_a}],[oa]:Ma}],[oa]:Ma},{[sa]:Wd,rules:[{endpoint:{[la]:$a,[ha]:Ec,[ba]:xc},[oa]:_a}],[oa]:Ma},Cc],[oa]:Ma},{[sa]:qd,rules:[{[sa]:Hd,rules:[{endpoint:{[la]:Ia,[ha]:Tc,[ba]:xc},[oa]:_a}],[oa]:Ma}],[oa]:Ma},{[sa]:Wd,rules:[{endpoint:{[la]:$a,[ha]:Tc,[ba]:xc},[oa]:_a}],[oa]:Ma},Cc],[oa]:Ma},{[sa]:[Rc,Oc],rules:[{[sa]:[kc,Pc],rules:[{[sa]:Kd,endpoint:{[la]:"https://s3express-control-fips.{Region}.amazonaws.com/{uri_encoded_bucket}",[ha]:Ec,[ba]:xc},[oa]:_a},{endpoint:{[la]:"https://s3express-control.{Region}.amazonaws.com/{uri_encoded_bucket}",[ha]:Ec,[ba]:xc},[oa]:_a}],[oa]:Ma}],[oa]:Ma},{[sa]:Wd,rules:[{[sa]:jd,rules:[{[sa]:Vd,rules:Qd,[oa]:Ma},{[sa]:Gd,rules:Qd,[oa]:Ma},Ic],[oa]:Ma},{[sa]:Vd,rules:Jd,[oa]:Ma},{[sa]:Gd,rules:Jd,[oa]:Ma},Ic],[oa]:Ma},Cc],[oa]:Ma},{[sa]:[_c,Rc,Oc],rules:[{[sa]:zd,endpoint:{[la]:Ua,[ha]:Ec,[ba]:xc},[oa]:_a},{[sa]:Kd,endpoint:{[la]:"https://s3express-control-fips.{Region}.amazonaws.com",[ha]:Ec,[ba]:xc},[oa]:_a},{endpoint:{[la]:"https://s3express-control.{Region}.amazonaws.com",[ha]:Ec,[ba]:xc},[oa]:_a}],[oa]:Ma},{[sa]:[yc,{[aa]:Ra,[ca]:[bc,49,50,wa],[ua]:La},{[aa]:Ra,[ca]:[bc,8,12,wa],[ua]:Da},{[aa]:Ra,[ca]:[bc,0,7,wa],[ua]:Ba},{[aa]:Ra,[ca]:[bc,32,49,wa],[ua]:za},{[aa]:xa,[ca]:Fd,[ua]:"regionPartition"},{[aa]:Aa,[ca]:[{[da]:Ba},"--op-s3"]}],rules:[{[sa]:Xd,rules:[{[sa]:[{[aa]:Aa,[ca]:[Mc,"e"]}],rules:[{[sa]:Zd,rules:[Nc,{[sa]:zd,endpoint:{[la]:"https://{Bucket}.ec2.{url#authority}",[ha]:$c,[ba]:xc},[oa]:_a}],[oa]:Ma},{endpoint:{[la]:"https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[ha]:$c,[ba]:xc},[oa]:_a}],[oa]:Ma},{[sa]:[{[aa]:Aa,[ca]:[Mc,"o"]}],rules:[{[sa]:Zd,rules:[Nc,{[sa]:zd,endpoint:{[la]:"https://{Bucket}.op-{outpostId}.{url#authority}",[ha]:$c,[ba]:xc},[oa]:_a}],[oa]:Ma},{endpoint:{[la]:"https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[ha]:$c,[ba]:xc},[oa]:_a}],[oa]:Ma},{error:'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',[oa]:Ea}],[oa]:Ma},{error:"Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",[oa]:Ea}],[oa]:Ma},{[sa]:Yd,rules:[{[sa]:[fc,{[aa]:Fa,[ca]:[{[aa]:Sa,[ca]:[{[aa]:Pa,[ca]:Ud}]}]}],error:"Custom endpoint `{Endpoint}` was not a valid URI",[oa]:Ea},{[sa]:[Fc,Ac],rules:[{[sa]:eu,rules:[{[sa]:tu,rules:[{[sa]:[lc,mc],error:"S3 Accelerate cannot be used in this region",[oa]:Ea},{[sa]:[pc,hc,Lc,Pc,Dc],endpoint:{[la]:"https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[pc,hc,Lc,Pc,zc,jc],rules:[{endpoint:qc,[oa]:_a}],[oa]:Ma},{[sa]:[pc,hc,Lc,Pc,zc,Wc],endpoint:qc,[oa]:_a},{[sa]:[Kc,hc,Lc,Pc,Dc],endpoint:{[la]:"https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[Kc,hc,Lc,Pc,zc,jc],rules:[{endpoint:Vc,[oa]:_a}],[oa]:Ma},{[sa]:[Kc,hc,Lc,Pc,zc,Wc],endpoint:Vc,[oa]:_a},{[sa]:[pc,Qc,lc,Pc,Dc],endpoint:{[la]:"https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[pc,Qc,lc,Pc,zc,jc],rules:[{endpoint:Gc,[oa]:_a}],[oa]:Ma},{[sa]:[pc,Qc,lc,Pc,zc,Wc],endpoint:Gc,[oa]:_a},{[sa]:[pc,Qc,Lc,Pc,Dc],endpoint:{[la]:"https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[pc,Qc,Lc,Pc,zc,jc],rules:[{endpoint:Jc,[oa]:_a}],[oa]:Ma},{[sa]:[pc,Qc,Lc,Pc,zc,Wc],endpoint:Jc,[oa]:_a},{[sa]:[Kc,Qc,Lc,fc,vc,wc,Dc],endpoint:{[la]:Ka,[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[Kc,Qc,Lc,fc,vc,Yc,Dc],endpoint:{[la]:$a,[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[Kc,Qc,Lc,fc,vc,wc,zc,jc],rules:[{[sa]:ru,endpoint:Xc,[oa]:_a},{endpoint:Xc,[oa]:_a}],[oa]:Ma},{[sa]:[Kc,Qc,Lc,fc,vc,Yc,zc,jc],rules:[{[sa]:ru,endpoint:Zc,[oa]:_a},ed],[oa]:Ma},{[sa]:[Kc,Qc,Lc,fc,vc,wc,zc,Wc],endpoint:Xc,[oa]:_a},{[sa]:[Kc,Qc,Lc,fc,vc,Yc,zc,Wc],endpoint:Zc,[oa]:_a},{[sa]:[Kc,Qc,lc,Pc,Dc],endpoint:{[la]:Va,[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[Kc,Qc,lc,Pc,zc,jc],rules:[{[sa]:ru,endpoint:td,[oa]:_a},{endpoint:td,[oa]:_a}],[oa]:Ma},{[sa]:[Kc,Qc,lc,Pc,zc,Wc],endpoint:td,[oa]:_a},{[sa]:[Kc,Qc,Lc,Pc,Dc],endpoint:{[la]:Qa,[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[Kc,Qc,Lc,Pc,zc,jc],rules:[{[sa]:ru,endpoint:{[la]:Qa,[ha]:Hc,[ba]:xc},[oa]:_a},{endpoint:rd,[oa]:_a}],[oa]:Ma},{[sa]:[Kc,Qc,Lc,Pc,zc,Wc],endpoint:rd,[oa]:_a}],[oa]:Ma},nd],[oa]:Ma}],[oa]:Ma},{[sa]:[fc,vc,{[aa]:Aa,[ca]:[{[aa]:Ca,[ca]:[Sc,"scheme"]},"http"]},{[aa]:Na,[ca]:[bc,wa]},Fc,Qc,Kc,Lc],rules:[{[sa]:eu,rules:[{[sa]:tu,rules:[ed],[oa]:Ma},nd],[oa]:Ma}],[oa]:Ma},{[sa]:[Fc,{[aa]:Ga,[ca]:Ld,[ua]:Ja}],rules:[{[sa]:[{[aa]:Ca,[ca]:[id,"resourceId[0]"],[ua]:Ya},{[aa]:Fa,[ca]:[{[aa]:Aa,[ca]:[od,""]}]}],rules:[{[sa]:[{[aa]:Aa,[ca]:[sd,Xa]}],rules:[{[sa]:nu,rules:[{[sa]:iu,rules:[cd,dd,{[sa]:su,rules:[ud,{[sa]:au,rules:[ld,{[sa]:du,rules:[{[sa]:eu,rules:[{[sa]:uu,rules:[{[sa]:lu,rules:[{[sa]:[{[aa]:Aa,[ca]:[pd,""]}],error:"Invalid ARN: Missing account id",[oa]:Ea},{[sa]:hu,rules:[{[sa]:pu,rules:[{[sa]:zd,endpoint:{[la]:tc,[ha]:fd,[ba]:xc},[oa]:_a},{[sa]:Kd,endpoint:{[la]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ha]:fd,[ba]:xc},[oa]:_a},{endpoint:{[la]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ha]:fd,[ba]:xc},[oa]:_a}],[oa]:Ma},gd],[oa]:Ma},md],[oa]:Ma},yd],[oa]:Ma},bd],[oa]:Ma}],[oa]:Ma}],[oa]:Ma},vd],[oa]:Ma},{error:"Invalid ARN: bucket ARN is missing a region",[oa]:Ea}],[oa]:Ma},wd],[oa]:Ma},{error:"Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",[oa]:Ea}],[oa]:Ma},{[sa]:nu,rules:[{[sa]:iu,rules:[{[sa]:su,rules:[{[sa]:nu,rules:[{[sa]:su,rules:[ud,{[sa]:au,rules:[ld,{[sa]:du,rules:[{[sa]:eu,rules:[{[sa]:[{[aa]:Aa,[ca]:[hd,"{partitionResult#name}"]}],rules:[{[sa]:lu,rules:[{[sa]:[{[aa]:Aa,[ca]:[sd,Wa]}],rules:[{[sa]:hu,rules:[{[sa]:pu,rules:[{[sa]:Bd,error:"Access Points do not support S3 Accelerate",[oa]:Ea},{[sa]:[hc,pc],endpoint:{[la]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ha]:Sd,[ba]:xc},[oa]:_a},{[sa]:[hc,Kc],endpoint:{[la]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ha]:Sd,[ba]:xc},[oa]:_a},{[sa]:[Qc,pc],endpoint:{[la]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ha]:Sd,[ba]:xc},[oa]:_a},{[sa]:[Qc,Kc,fc,vc],endpoint:{[la]:tc,[ha]:Sd,[ba]:xc},[oa]:_a},{[sa]:[Qc,Kc],endpoint:{[la]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ha]:Sd,[ba]:xc},[oa]:_a}],[oa]:Ma},gd],[oa]:Ma},md],[oa]:Ma},{error:"Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",[oa]:Ea}],[oa]:Ma},yd],[oa]:Ma},bd],[oa]:Ma}],[oa]:Ma}],[oa]:Ma},vd],[oa]:Ma}],[oa]:Ma}],[oa]:Ma},{[sa]:[{[aa]:ja,[ca]:[ad,wa]}],rules:[{[sa]:Dd,error:"S3 MRAP does not support dual-stack",[oa]:Ea},{[sa]:Kd,error:"S3 MRAP does not support FIPS",[oa]:Ea},{[sa]:Bd,error:"S3 MRAP does not support S3 Accelerate",[oa]:Ea},{[sa]:[{[aa]:ka,[ca]:[{[da]:"DisableMultiRegionAccessPoints"},wa]}],error:"Invalid configuration: Multi-Region Access Point ARNs are disabled.",[oa]:Ea},{[sa]:[{[aa]:xa,[ca]:Fd,[ua]:rc}],rules:[{[sa]:[{[aa]:Aa,[ca]:[{[aa]:Ca,[ca]:[{[da]:rc},Ta]},{[aa]:Ca,[ca]:[id,"partition"]}]}],rules:[{endpoint:{[la]:"https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",[ha]:{[fa]:[{[ga]:wa,name:qa,[ma]:Wa,[va]:["*"]}]},[ba]:xc},[oa]:_a}],[oa]:Ma},{error:"Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",[oa]:Ea}],[oa]:Ma}],[oa]:Ma},{error:"Invalid Access Point Name",[oa]:Ea}],[oa]:Ma},wd],[oa]:Ma},{[sa]:[{[aa]:Aa,[ca]:[sd,Ha]}],rules:[{[sa]:Dd,error:"S3 Outposts does not support Dual-stack",[oa]:Ea},{[sa]:Kd,error:"S3 Outposts does not support FIPS",[oa]:Ea},{[sa]:Bd,error:"S3 Outposts does not support S3 Accelerate",[oa]:Ea},{[sa]:[{[aa]:Sa,[ca]:[{[aa]:Ca,[ca]:[id,"resourceId[4]"]}]}],error:"Invalid Arn: Outpost Access Point ARN contains sub resources",[oa]:Ea},{[sa]:[{[aa]:Ca,[ca]:ou,[ua]:za}],rules:[{[sa]:Xd,rules:[ld,{[sa]:du,rules:[{[sa]:eu,rules:[{[sa]:uu,rules:[{[sa]:lu,rules:[{[sa]:hu,rules:[{[sa]:[{[aa]:Ca,[ca]:cu,[ua]:nc}],rules:[{[sa]:[{[aa]:Ca,[ca]:[id,"resourceId[3]"],[ua]:ec}],rules:[{[sa]:[{[aa]:Aa,[ca]:[{[da]:nc},Za]}],rules:[{[sa]:zd,endpoint:{[la]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",[ha]:kd,[ba]:xc},[oa]:_a},{endpoint:{[la]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ha]:kd,[ba]:xc},[oa]:_a}],[oa]:Ma},{error:"Expected an outpost type `accesspoint`, found {outpostType}",[oa]:Ea}],[oa]:Ma},{error:"Invalid ARN: expected an access point name",[oa]:Ea}],[oa]:Ma},{error:"Invalid ARN: Expected a 4-component resource",[oa]:Ea}],[oa]:Ma},md],[oa]:Ma},yd],[oa]:Ma},bd],[oa]:Ma}],[oa]:Ma}],[oa]:Ma},{error:"Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",[oa]:Ea}],[oa]:Ma},{error:"Invalid ARN: The Outpost Id was not set",[oa]:Ea}],[oa]:Ma},{error:"Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",[oa]:Ea}],[oa]:Ma},{error:"Invalid ARN: No ARN type specified",[oa]:Ea}],[oa]:Ma},{[sa]:[{[aa]:Ra,[ca]:[bc,0,4,!1],[ua]:ic},{[aa]:Aa,[ca]:[{[da]:ic},"arn:"]},{[aa]:Fa,[ca]:[{[aa]:Sa,[ca]:[Ed]}]}],error:"Invalid ARN: `{Bucket}` was not a valid ARN",[oa]:Ea},{[sa]:[{[aa]:ka,[ca]:[Uc,wa]},Ed],error:"Path-style addressing cannot be used with ARN buckets",[oa]:Ea},{[sa]:Hd,rules:[{[sa]:eu,rules:[{[sa]:[Lc],rules:[{[sa]:[pc,Pc,hc,Dc],endpoint:{[la]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[pc,Pc,hc,zc,jc],rules:[{endpoint:xd,[oa]:_a}],[oa]:Ma},{[sa]:[pc,Pc,hc,zc,Wc],endpoint:xd,[oa]:_a},{[sa]:[Kc,Pc,hc,Dc],endpoint:{[la]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[Kc,Pc,hc,zc,jc],rules:[{endpoint:Ad,[oa]:_a}],[oa]:Ma},{[sa]:[Kc,Pc,hc,zc,Wc],endpoint:Ad,[oa]:_a},{[sa]:[pc,Pc,Qc,Dc],endpoint:{[la]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[pc,Pc,Qc,zc,jc],rules:[{endpoint:Cd,[oa]:_a}],[oa]:Ma},{[sa]:[pc,Pc,Qc,zc,Wc],endpoint:Cd,[oa]:_a},{[sa]:[Kc,fc,vc,Qc,Dc],endpoint:{[la]:oc,[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[Kc,fc,vc,Qc,zc,jc],rules:[{[sa]:ru,endpoint:Td,[oa]:_a},{endpoint:Td,[oa]:_a}],[oa]:Ma},{[sa]:[Kc,fc,vc,Qc,zc,Wc],endpoint:Td,[oa]:_a},{[sa]:[Kc,Pc,Qc,Dc],endpoint:{[la]:sc,[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[Kc,Pc,Qc,zc,jc],rules:[{[sa]:ru,endpoint:{[la]:sc,[ha]:Hc,[ba]:xc},[oa]:_a},{endpoint:Rd,[oa]:_a}],[oa]:Ma},{[sa]:[Kc,Pc,Qc,zc,Wc],endpoint:Rd,[oa]:_a}],[oa]:Ma},{error:"Path-style addressing cannot be used with S3 Accelerate",[oa]:Ea}],[oa]:Ma}],[oa]:Ma}],[oa]:Ma},{[sa]:[{[aa]:Sa,[ca]:[Od]},{[aa]:ka,[ca]:[Od,wa]}],rules:[{[sa]:eu,rules:[{[sa]:fu,rules:[cd,dd,{[sa]:zd,endpoint:{[la]:Ua,[ha]:Pd,[ba]:xc},[oa]:_a},{[sa]:Kd,endpoint:{[la]:"https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",[ha]:Pd,[ba]:xc},[oa]:_a},{endpoint:{[la]:"https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",[ha]:Pd,[ba]:xc},[oa]:_a}],[oa]:Ma},nd],[oa]:Ma}],[oa]:Ma},{[sa]:[_c],rules:[{[sa]:eu,rules:[{[sa]:fu,rules:[{[sa]:[hc,pc,Pc,Dc],endpoint:{[la]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[hc,pc,Pc,zc,jc],rules:[{endpoint:Id,[oa]:_a}],[oa]:Ma},{[sa]:[hc,pc,Pc,zc,Wc],endpoint:Id,[oa]:_a},{[sa]:[hc,Kc,Pc,Dc],endpoint:{[la]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[hc,Kc,Pc,zc,jc],rules:[{endpoint:_d,[oa]:_a}],[oa]:Ma},{[sa]:[hc,Kc,Pc,zc,Wc],endpoint:_d,[oa]:_a},{[sa]:[Qc,pc,Pc,Dc],endpoint:{[la]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[Qc,pc,Pc,zc,jc],rules:[{endpoint:Md,[oa]:_a}],[oa]:Ma},{[sa]:[Qc,pc,Pc,zc,Wc],endpoint:Md,[oa]:_a},{[sa]:[Qc,Kc,fc,vc,Dc],endpoint:{[la]:Ua,[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[Qc,Kc,fc,vc,zc,jc],rules:[{[sa]:ru,endpoint:Nd,[oa]:_a},{endpoint:Nd,[oa]:_a}],[oa]:Ma},{[sa]:[Qc,Kc,fc,vc,zc,Wc],endpoint:Nd,[oa]:_a},{[sa]:[Qc,Kc,Pc,Dc],endpoint:{[la]:ac,[ha]:Bc,[ba]:xc},[oa]:_a},{[sa]:[Qc,Kc,Pc,zc,jc],rules:[{[sa]:ru,endpoint:{[la]:ac,[ha]:Hc,[ba]:xc},[oa]:_a},{endpoint:$d,[oa]:_a}],[oa]:Ma},{[sa]:[Qc,Kc,Pc,zc,Wc],endpoint:$d,[oa]:_a}],[oa]:Ma},nd],[oa]:Ma}],[oa]:Ma}],[oa]:Ma},{error:"A region must be set when sending requests to S3.",[oa]:Ea}]},mu=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"]}),yu=(e,t={})=>mu.get(e,(()=>((e,t)=>{const{endpointParams:r,logger:n}=t,{parameters:i,rules:o}=e;t.logger?.debug?.(`${Uo} Initial EndpointParams: ${Lo(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 Do(`Missing required parameter: '${e}'`);const c=ts(o,{endpointParams:r,logger:n,referenceRecord:{}});return t.logger?.debug?.(`${Uo} Resolved endpoint: ${Lo(c)}`),c})(gu,{endpointParams:e,logger:t.logger})));Fo.aws=is;const bu=(vu=async(e,t,r)=>({operation:he(t).operation,region:await pe(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 vu(e,t,r),i=he(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 vu;function wu(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function Su(e){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}const ku=((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 d;if(t!==c&&console.warn(`HttpAuthScheme has been normalized with lowercasing: \`${t}\` to \`${c}\``),"sigv4a"===c){d="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}\``);d="aws.auth#sigv4"}const u=r[d];if(!u)throw new Error(`Could not find HttpAuthOption create function for \`${d}\``);const l=u(n);l.schemeId=d,l.signingProperties={...l.signingProperties||{},...a,...i},s.push(l)}return s})(yu,(e=>{const t=[];return e.operation,t.push(wu(e)),t.push(Su(e)),t}),{"aws.auth#sigv4":wu,"aws.auth#sigv4a":Su}),Eu=e=>{const t=(e=>(e.sigv4aSigningRegionSet=Ee(e.sigv4aSigningRegionSet),e))(Ut(e));return{...t}},xu={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 Au extends _r{constructor(e){super(e),Object.setPrototypeOf(this,Au.prototype)}}class Cu extends Au{constructor(e){super({name:"NoSuchUpload",$fault:"client",...e}),this.name="NoSuchUpload",this.$fault="client",Object.setPrototypeOf(this,Cu.prototype)}}class Tu extends Au{constructor(e){super({name:"ObjectNotInActiveTierError",$fault:"client",...e}),this.name="ObjectNotInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,Tu.prototype)}}class Ru extends Au{constructor(e){super({name:"BucketAlreadyExists",$fault:"client",...e}),this.name="BucketAlreadyExists",this.$fault="client",Object.setPrototypeOf(this,Ru.prototype)}}class Ou extends Au{constructor(e){super({name:"BucketAlreadyOwnedByYou",$fault:"client",...e}),this.name="BucketAlreadyOwnedByYou",this.$fault="client",Object.setPrototypeOf(this,Ou.prototype)}}class Pu extends Au{constructor(e){super({name:"NoSuchBucket",$fault:"client",...e}),this.name="NoSuchBucket",this.$fault="client",Object.setPrototypeOf(this,Pu.prototype)}}var Iu,_u;!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])}(Iu||(Iu={})),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])}(_u||(_u={}));class Mu extends Au{constructor(e){super({name:"InvalidObjectState",$fault:"client",...e}),this.name="InvalidObjectState",this.$fault="client",Object.setPrototypeOf(this,Mu.prototype),this.StorageClass=e.StorageClass,this.AccessTier=e.AccessTier}}class Nu extends Au{constructor(e){super({name:"NoSuchKey",$fault:"client",...e}),this.name="NoSuchKey",this.$fault="client",Object.setPrototypeOf(this,Nu.prototype)}}class $u extends Au{constructor(e){super({name:"NotFound",$fault:"client",...e}),this.name="NotFound",this.$fault="client",Object.setPrototypeOf(this,$u.prototype)}}const Fu=e=>({...e,...e.SecretAccessKey&&{SecretAccessKey:Kt},...e.SessionToken&&{SessionToken:Kt}}),Uu=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Kt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Kt},...e.Credentials&&{Credentials:Fu(e.Credentials)}}),Lu=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Kt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Kt}}),Du=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Kt}}),Bu=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:Kt}});class zu extends Au{constructor(e){super({name:"EncryptionTypeMismatch",$fault:"client",...e}),this.name="EncryptionTypeMismatch",this.$fault="client",Object.setPrototypeOf(this,zu.prototype)}}class ju extends Au{constructor(e){super({name:"InvalidRequest",$fault:"client",...e}),this.name="InvalidRequest",this.$fault="client",Object.setPrototypeOf(this,ju.prototype)}}class qu extends Au{constructor(e){super({name:"InvalidWriteOffset",$fault:"client",...e}),this.name="InvalidWriteOffset",this.$fault="client",Object.setPrototypeOf(this,qu.prototype)}}class Hu extends Au{constructor(e){super({name:"TooManyParts",$fault:"client",...e}),this.name="TooManyParts",this.$fault="client",Object.setPrototypeOf(this,Hu.prototype)}}class Wu extends Au{constructor(e){super({name:"ObjectAlreadyInActiveTierError",$fault:"client",...e}),this.name="ObjectAlreadyInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,Wu.prototype)}}var Ku;!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])}(Ku||(Ku={}));const Vu=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Kt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Kt}}),Qu=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:Kt},...e.SSEKMSKeyId&&{SSEKMSKeyId:Kt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Kt}}),Gu=async(e,t)=>{const r=Ze(e,t),n=Vr({},Hr,{[tf]:e[Zh],[Cf]:e[ep],[Tf]:e[op],[Of]:e[ip],[Rf]:[()=>Hr(e[Ml]),()=>e[Ml].toString()]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=Vr({[Wp]:[,""]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Ju=async(e,t)=>{const r=Ze(e,t),n=Vr({},Hr,{[hf]:e[xh],[kf]:e[Kh],[Gp]:[()=>Hr(e[_l]),()=>e[_l].toString()],[of]:e[rh],[Op]:e[ph],[uf]:[()=>Hr(e[fh]),()=>fr(e[fh]).toString()],[lf]:[()=>Hr(e[gh]),()=>e[gh].toString()]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=Vr({[Lf]:[,"DeleteObject"],[Vp]:[,e[up]]});return r.m("DELETE").h(n).q(i).b(undefined),r.build()},Yu=async(e,t)=>{const r=Ze(e,t),n=Vr({},Hr,{[Op]:e[ph],[Pp]:[()=>Hr(e[mh]),()=>fr(e[mh]).toString()],[Ip]:e[yh],[_p]:[()=>Hr(e[wh]),()=>fr(e[wh]).toString()],[Lp]:e[Uh],[Pf]:e[tp],[If]:e[rp],[_f]:e[np],[kf]:e[Kh],[of]:e[rh],[Xp]:e[ql]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=Vr({[Lf]:[,"GetObject"],[Dp]:[,e[Dh]],[Bp]:[,e[Bh]],[zp]:[,e[zh]],[jp]:[,e[jh]],[qp]:[,e[qh]],[Hp]:[()=>void 0!==e.ResponseExpires,()=>fr(e[Hh]).toString()],[Vp]:[,e[up]],[Fp]:[()=>void 0!==e.PartNumber,()=>e[Fh].toString()]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Xu=async(e,t)=>{const r=Ze(e,t),n=Vr({},Hr,{[kf]:e[Kh],[of]:e[rh],[bf]:[()=>Hr(e[Mh]),()=>(e[Mh]||[]).map(Xr).join(", ")]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=Vr({[Np]:[,"2"],[Ep]:[,e[Xl]],[Ap]:[,e[ih]],[$p]:[()=>void 0!==e.MaxKeys,()=>e[Ah].toString()],[Up]:[,e[Nh]],[kp]:[,e[Jl]],[Rp]:[()=>void 0!==e.FetchOwner,()=>e[ah].toString()],[Kp]:[,e[Jh]]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Zu=async(e,t)=>{const r=Ze(e,t),n=Vr({},Hr,{[Sp]:e[Gl]||"application/octet-stream",[Qp]:e[Rl],[fp]:e[Fl],[gp]:e[Dl],[mp]:e[Bl],[yp]:e[zl],[bp]:[()=>Hr(e[jl]),()=>e[jl].toString()],[vp]:e[Hl],[Af]:e[$l],[Jp]:e[Ul],[Yp]:e[Ll],[Zp]:e[Vl],[ef]:e[Ql],[xp]:[()=>Hr(e[th]),()=>fr(e[th]).toString()],[Op]:e[ph],[Ip]:e[yh],[sf]:e[ch],[af]:e[dh],[cf]:e[uh],[df]:e[lh],[Ff]:[()=>Hr(e[lp]),()=>e[lp].toString()],[Cf]:e[ep],[xf]:e[Xh],[Uf]:e[hp],[Pf]:e[tp],[If]:e[rp],[_f]:e[np],[Tf]:e[op],[Of]:e[ip],[Rf]:[()=>Hr(e[Ml]),()=>e[Ml].toString()],[kf]:e[Kh],[Mf]:e[cp],[mf]:e[Ih],[yf]:[()=>Hr(e[_h]),()=>{return(t=e[_h],t.toISOString().replace(".000Z","Z")).toString();var t}],[gf]:e[Ph],[of]:e[rh],...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=Vr({[Lf]:[,"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()},el=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return ol(e,t);const r=Vr({$metadata:Tl(e),[ep]:[,e.headers[Cf]],[op]:[,e.headers[Tf]],[ip]:[,e.headers[Of]],[Ml]:[()=>void 0!==e.headers[Rf],()=>Vt(e.headers[Rf])]}),n=rr(nr(await vi(e.body,t)),"body");return null!=n[Nl]&&(r[Nl]=Cl(n[Nl])),r},tl=async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return ol(e,t);const r=Vr({$metadata:Tl(e),[Zl]:[()=>void 0!==e.headers[rf],()=>Vt(e.headers[rf])],[up]:[,e.headers[$f]],[Lh]:[,e.headers[Sf]]});return await Ye(e.body,t),r},rl=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return ol(e,t);const r=Vr({$metadata:Tl(e),[Zl]:[()=>void 0!==e.headers[rf],()=>Vt(e.headers[rf])],[Pl]:[,e.headers[pp]],[sh]:[,e.headers[nf]],[Gh]:[,e.headers[wf]],[Eh]:[()=>void 0!==e.headers[Mp],()=>rr(wr(e.headers[Mp]))],[jl]:[()=>void 0!==e.headers[bp],()=>ar(e.headers[bp])],[oh]:[,e.headers[Cp]],[Ul]:[,e.headers[Jp]],[Ll]:[,e.headers[Yp]],[Vl]:[,e.headers[Zp]],[Ql]:[,e.headers[ef]],[Ch]:[()=>void 0!==e.headers[pf],()=>cr(e.headers[pf])],[up]:[,e.headers[$f]],[Fl]:[,e.headers[fp]],[Dl]:[,e.headers[gp]],[Bl]:[,e.headers[mp]],[zl]:[,e.headers[yp]],[Kl]:[,e.headers[wp]],[Gl]:[,e.headers[Sp]],[th]:[()=>void 0!==e.headers[xp],()=>rr(wr(e.headers[xp]))],[nh]:[,e.headers[Tp]],[hp]:[,e.headers[Uf]],[ep]:[,e.headers[Cf]],[tp]:[,e.headers[Pf]],[np]:[,e.headers[_f]],[op]:[,e.headers[Tf]],[Ml]:[()=>void 0!==e.headers[Rf],()=>Vt(e.headers[Rf])],[Xh]:[,e.headers[xf]],[Lh]:[,e.headers[Sf]],[Vh]:[,e.headers[Ef]],[$h]:[()=>void 0!==e.headers[ff],()=>cr(e.headers[ff])],[dp]:[()=>void 0!==e.headers[Nf],()=>cr(e.headers[Nf])],[Ih]:[,e.headers[mf]],[_h]:[()=>void 0!==e.headers[yf],()=>rr(mr(e.headers[yf]))],[Ph]:[,e.headers[gf]],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},nl=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return ol(e,t);const r=Vr({$metadata:Tl(e),[Lh]:[,e.headers[Sf]]}),n=rr(nr(await vi(e.body,t)),"body");return""===n.CommonPrefixes?r[Wl]=[]:null!=n[Wl]&&(r[Wl]=Sl(jr(n[Wl]))),""===n.Contents?r[Yl]=[]:null!=n[Yl]&&(r[Yl]=El(jr(n[Yl]))),null!=n[Jl]&&(r[Jl]=ir(n[Jl])),null!=n[Xl]&&(r[Xl]=ir(n[Xl])),null!=n[ih]&&(r[ih]=ir(n[ih])),null!=n[vh]&&(r[vh]=Vt(n[vh])),null!=n[kh]&&(r[kh]=cr(n[kh])),null!=n[Ah]&&(r[Ah]=cr(n[Ah])),null!=n[Th]&&(r[Th]=ir(n[Th])),null!=n[Rh]&&(r[Rh]=ir(n[Rh])),null!=n[Nh]&&(r[Nh]=ir(n[Nh])),null!=n[Jh]&&(r[Jh]=ir(n[Jh])),r},il=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return ol(e,t);const r=Vr({$metadata:Tl(e),[sh]:[,e.headers[nf]],[oh]:[,e.headers[Cp]],[Ul]:[,e.headers[Jp]],[Ll]:[,e.headers[Yp]],[Vl]:[,e.headers[Zp]],[Ql]:[,e.headers[ef]],[ep]:[,e.headers[Cf]],[up]:[,e.headers[$f]],[tp]:[,e.headers[Pf]],[np]:[,e.headers[_f]],[op]:[,e.headers[Tf]],[ip]:[,e.headers[Of]],[Ml]:[()=>void 0!==e.headers[Rf],()=>Vt(e.headers[Rf])],[ap]:[()=>void 0!==e.headers[vf],()=>ar(e.headers[vf])],[Lh]:[,e.headers[Sf]]});return await Ye(e.body,t),r},ol=async(e,t)=>{const r={...e,body:await wi(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 ml(r,t);case"ObjectNotInActiveTierError":case"com.amazonaws.s3#ObjectNotInActiveTierError":throw await vl(r,t);case"BucketAlreadyExists":case"com.amazonaws.s3#BucketAlreadyExists":throw await cl(r,t);case"BucketAlreadyOwnedByYou":case"com.amazonaws.s3#BucketAlreadyOwnedByYou":throw await dl(r,t);case"NoSuchBucket":case"com.amazonaws.s3#NoSuchBucket":throw await fl(r,t);case"InvalidObjectState":case"com.amazonaws.s3#InvalidObjectState":throw await ll(r,t);case"NoSuchKey":case"com.amazonaws.s3#NoSuchKey":throw await gl(r,t);case"NotFound":case"com.amazonaws.s3#NotFound":throw await yl(r,t);case"EncryptionTypeMismatch":case"com.amazonaws.s3#EncryptionTypeMismatch":throw await ul(r,t);case"InvalidRequest":case"com.amazonaws.s3#InvalidRequest":throw await hl(r,t);case"InvalidWriteOffset":case"com.amazonaws.s3#InvalidWriteOffset":throw await pl(r,t);case"TooManyParts":case"com.amazonaws.s3#TooManyParts":throw await wl(r,t);case"ObjectAlreadyInActiveTierError":case"com.amazonaws.s3#ObjectAlreadyInActiveTierError":throw await bl(r,t);default:const i=r.body;return sl({output:e,parsedBody:i,errorCode:n})}},sl=(al=Au,({output:e,parsedBody:t,errorCode:r})=>{(({output:e,parsedBody:t,exceptionCtor:r,errorCode:n})=>{const i=Nr(e),o=i.httpStatusCode?i.httpStatusCode+"":void 0,s=new r({name:t?.code||t?.Code||n||o||"UnknownError",$fault:"client",$metadata:i});throw Mr(s,t)})({output:e,parsedBody:t,exceptionCtor:al,errorCode:r})});var al;const cl=async(e,t)=>{const r=Vr({});e.body;const n=new Ru({$metadata:Tl(e),...r});return Mr(n,e.body)},dl=async(e,t)=>{const r=Vr({});e.body;const n=new Ou({$metadata:Tl(e),...r});return Mr(n,e.body)},ul=async(e,t)=>{const r=Vr({});e.body;const n=new zu({$metadata:Tl(e),...r});return Mr(n,e.body)},ll=async(e,t)=>{const r=Vr({}),n=e.body;null!=n[Il]&&(r[Il]=ir(n[Il])),null!=n[Xh]&&(r[Xh]=ir(n[Xh]));const i=new Mu({$metadata:Tl(e),...r});return Mr(i,e.body)},hl=async(e,t)=>{const r=Vr({});e.body;const n=new ju({$metadata:Tl(e),...r});return Mr(n,e.body)},pl=async(e,t)=>{const r=Vr({});e.body;const n=new qu({$metadata:Tl(e),...r});return Mr(n,e.body)},fl=async(e,t)=>{const r=Vr({});e.body;const n=new Pu({$metadata:Tl(e),...r});return Mr(n,e.body)},gl=async(e,t)=>{const r=Vr({});e.body;const n=new Nu({$metadata:Tl(e),...r});return Mr(n,e.body)},ml=async(e,t)=>{const r=Vr({});e.body;const n=new Cu({$metadata:Tl(e),...r});return Mr(n,e.body)},yl=async(e,t)=>{const r=Vr({});e.body;const n=new $u({$metadata:Tl(e),...r});return Mr(n,e.body)},bl=async(e,t)=>{const r=Vr({});e.body;const n=new Wu({$metadata:Tl(e),...r});return Mr(n,e.body)},vl=async(e,t)=>{const r=Vr({});e.body;const n=new Tu({$metadata:Tl(e),...r});return Mr(n,e.body)},wl=async(e,t)=>{const r=Vr({});e.body;const n=new Hu({$metadata:Tl(e),...r});return Mr(n,e.body)},Sl=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>(e=>{const t={};return null!=e[Nh]&&(t[Nh]=ir(e[Nh])),t})(e))),kl=(e,t)=>{const r={};return null!=e[Sh]&&(r[Sh]=ir(e[Sh])),null!=e[Eh]&&(r[Eh]=rr(mr(e[Eh]))),null!=e[oh]&&(r[oh]=ir(e[oh])),""===e.ChecksumAlgorithm?r[$l]=[]:null!=e[$l]&&(r[$l]=(e=>(e||[]).filter((e=>null!=e)).map((e=>ir(e))))(jr(e[$l]))),null!=e[ap]&&(r[ap]=ar(e[ap])),null!=e[Xh]&&(r[Xh]=ir(e[Xh])),null!=e[Oh]&&(r[Oh]=xl(e[Oh])),null!=e[Qh]&&(r[Qh]=Al(e[Qh])),r},El=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>kl(e))),xl=(e,t)=>{const r={};return null!=e[eh]&&(r[eh]=ir(e[eh])),null!=e[hh]&&(r[hh]=ir(e[hh])),r},Al=(e,t)=>{const r={};return null!=e[bh]&&(r[bh]=Vt(e[bh])),null!=e[Wh]&&(r[Wh]=rr(mr(e[Wh]))),r},Cl=(e,t)=>{const r={};return null!=e[Ol]&&(r[Ol]=ir(e[Ol])),null!=e[Yh]&&(r[Yh]=ir(e[Yh])),null!=e[sp]&&(r[sp]=ir(e[sp])),null!=e[sh]&&(r[sh]=rr(mr(e[sh]))),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"]}),Rl="ACL",Ol="AccessKeyId",Pl="AcceptRanges",Il="AccessTier",_l="BypassGovernanceRetention",Ml="BucketKeyEnabled",Nl="Credentials",$l="ChecksumAlgorithm",Fl="CacheControl",Ul="ChecksumCRC32",Ll="ChecksumCRC32C",Dl="ContentDisposition",Bl="ContentEncoding",zl="ContentLanguage",jl="ContentLength",ql="ChecksumMode",Hl="ContentMD5",Wl="CommonPrefixes",Kl="ContentRange",Vl="ChecksumSHA1",Ql="ChecksumSHA256",Gl="ContentType",Jl="ContinuationToken",Yl="Contents",Xl="Delimiter",Zl="DeleteMarker",eh="DisplayName",th="Expires",rh="ExpectedBucketOwner",nh="ExpiresString",ih="EncodingType",oh="ETag",sh="Expiration",ah="FetchOwner",ch="GrantFullControl",dh="GrantRead",uh="GrantReadACP",lh="GrantWriteACP",hh="ID",ph="IfMatch",fh="IfMatchLastModifiedTime",gh="IfMatchSize",mh="IfModifiedSince",yh="IfNoneMatch",bh="IsRestoreInProgress",vh="IsTruncated",wh="IfUnmodifiedSince",Sh="Key",kh="KeyCount",Eh="LastModified",xh="MFA",Ah="MaxKeys",Ch="MissingMeta",Th="Name",Rh="NextContinuationToken",Oh="Owner",Ph="ObjectLockLegalHoldStatus",Ih="ObjectLockMode",_h="ObjectLockRetainUntilDate",Mh="OptionalObjectAttributes",Nh="Prefix",$h="PartsCount",Fh="PartNumber",Uh="Range",Lh="RequestCharged",Dh="ResponseCacheControl",Bh="ResponseContentDisposition",zh="ResponseContentEncoding",jh="ResponseContentLanguage",qh="ResponseContentType",Hh="ResponseExpires",Wh="RestoreExpiryDate",Kh="RequestPayer",Vh="ReplicationStatus",Qh="RestoreStatus",Gh="Restore",Jh="StartAfter",Yh="SecretAccessKey",Xh="StorageClass",Zh="SessionMode",ep="ServerSideEncryption",tp="SSECustomerAlgorithm",rp="SSECustomerKey",np="SSECustomerKeyMD5",ip="SSEKMSEncryptionContext",op="SSEKMSKeyId",sp="SessionToken",ap="Size",cp="Tagging",dp="TagCount",up="VersionId",lp="WriteOffsetBytes",hp="WebsiteRedirectLocation",pp="accept-ranges",fp="cache-control",gp="content-disposition",mp="content-encoding",yp="content-language",bp="content-length",vp="content-md5",wp="content-range",Sp="content-type",kp="continuation-token",Ep="delimiter",xp="expires",Ap="encoding-type",Cp="etag",Tp="expiresstring",Rp="fetch-owner",Op="if-match",Pp="if-modified-since",Ip="if-none-match",_p="if-unmodified-since",Mp="last-modified",Np="list-type",$p="max-keys",Fp="partNumber",Up="prefix",Lp="range",Dp="response-cache-control",Bp="response-content-disposition",zp="response-content-encoding",jp="response-content-language",qp="response-content-type",Hp="response-expires",Wp="session",Kp="start-after",Vp="versionId",Qp="x-amz-acl",Gp="x-amz-bypass-governance-retention",Jp="x-amz-checksum-crc32",Yp="x-amz-checksum-crc32c",Xp="x-amz-checksum-mode",Zp="x-amz-checksum-sha1",ef="x-amz-checksum-sha256",tf="x-amz-create-session-mode",rf="x-amz-delete-marker",nf="x-amz-expiration",of="x-amz-expected-bucket-owner",sf="x-amz-grant-full-control",af="x-amz-grant-read",cf="x-amz-grant-read-acp",df="x-amz-grant-write-acp",uf="x-amz-if-match-last-modified-time",lf="x-amz-if-match-size",hf="x-amz-mfa",pf="x-amz-missing-meta",ff="x-amz-mp-parts-count",gf="x-amz-object-lock-legal-hold",mf="x-amz-object-lock-mode",yf="x-amz-object-lock-retain-until-date",bf="x-amz-optional-object-attributes",vf="x-amz-object-size",wf="x-amz-restore",Sf="x-amz-request-charged",kf="x-amz-request-payer",Ef="x-amz-replication-status",xf="x-amz-storage-class",Af="x-amz-sdk-checksum-algorithm",Cf="x-amz-server-side-encryption",Tf="x-amz-server-side-encryption-aws-kms-key-id",Rf="x-amz-server-side-encryption-bucket-key-enabled",Of="x-amz-server-side-encryption-context",Pf="x-amz-server-side-encryption-customer-algorithm",If="x-amz-server-side-encryption-customer-key",_f="x-amz-server-side-encryption-customer-key-md5",Mf="x-amz-tagging",Nf="x-amz-tagging-count",$f="x-amz-version-id",Ff="x-amz-write-offset-bytes",Uf="x-amz-website-redirect-location",Lf="x-id";class Df extends(Ht.classBuilder().ep({...xu,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(e,t,r,n){return[be(r,this.serialize,this.deserialize),Ps(r,e.getEndpointParameterInstructions()),Ro(r)]})).s("AmazonS3","CreateSession",{}).n("S3Client","CreateSessionCommand").f(Lu,Uu).ser(Gu).de(el).build()){}var Bf="3.701.0";function zf(e){return"string"==typeof e?0===e.length:0===e.byteLength}var jf={name:"SHA-1"},qf={name:"HMAC",hash:jf},Hf=new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]);const Wf={};function Kf(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:Wf}var Vf=function(){function e(e){this.toHash=new Uint8Array(0),void 0!==e&&(this.key=new Promise((function(t,r){Kf().crypto.subtle.importKey("raw",Qf(e),qf,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))}return e.prototype.update=function(e){if(!zf(e)){var t=Qf(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 Kf().crypto.subtle.sign(qf,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):zf(this.toHash)?Promise.resolve(Hf):Promise.resolve().then((function(){return Kf().crypto.subtle.digest(jf,e.toHash)})).then((function(e){return Promise.resolve(new Uint8Array(e))}))},e.prototype.reset=function(){this.toHash=new Uint8Array(0)},e}();function Qf(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 Gf=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function Jf(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&&Gf.every((function(t){return"function"==typeof e[t]}))}(e.crypto.subtle)}var Yf=function(){function e(e){if(!Jf(Kf()))throw new Error("SHA1 not supported");this.hash=new Vf(e)}return e.prototype.update=function(e,t){this.hash.update(Ri(e))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e}(),Xf={name:"SHA-256"},Zf={name:"HMAC",hash:Xf},eg=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]),tg=function(){function e(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return e.prototype.update=function(e){if(!Oi(e)){var t=Ri(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 Kf().crypto.subtle.sign(Zf,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):Oi(this.toHash)?Promise.resolve(eg):Promise.resolve().then((function(){return Kf().crypto.subtle.digest(Xf,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){Kf().crypto.subtle.importKey("raw",Ri(e.secret),Zf,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))},e}();function rg(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 ng(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]ag)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;r>0;)this.buffer[this.bufferLength++]=e[t++],r--,this.bufferLength===ig&&(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%ig>=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],d=t[7],u=0;u>>17|l<<15)^(l>>>19|l<<13)^l>>>10,p=((l=this.temp[u-15])>>>7|l<<25)^(l>>>18|l<<14)^l>>>3;this.temp[u]=(h+this.temp[u-7]|0)+(p+this.temp[u-16]|0)}var f=(((s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7))+(s&a^~s&c)|0)+(d+(og[u]+this.temp[u]|0)|0)|0,g=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&n^r&i^n&i)|0;d=c,c=a,a=s,s=o+f|0,o=i,i=n,n=r,r=f+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]+=d},e}(),dg=function(){function e(e){this.secret=e,this.hash=new cg,this.reset()}return e.prototype.update=function(e){if(!Oi(e)&&!this.error)try{this.hash.update(Ri(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 rg(this,void 0,void 0,(function(){return ng(this,(function(e){return[2,this.digestSync()]}))}))},e.prototype.reset=function(){if(this.hash=new cg,this.secret){this.outer=new cg;var e=function(e){var t=Ri(e);if(t.byteLength>ig){var r=new cg;r.update(t),t=r.digest()}var n=new Uint8Array(ig);return n.set(t),n}(this.secret),t=new Uint8Array(ig);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 d=this.satisfies(r[c]);if(void 0!==d)return d}var u=a.default.find(s,(function(e){return t.isPlatform(e)}));if(u){var l=this.satisfies(r[u]);if(void 0!==l)return l}}if(o>0){var h=Object.keys(i),p=a.default.find(h,(function(e){return t.isBrowser(e,!0)}));if(void 0!==p)return this.compareVersion(i[p])}},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=d,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 hg=Zr(lg.exports);const pg=({serviceId:e,clientVersion:t})=>async r=>{const n="undefined"!=typeof window&&window?.navigator?.userAgent?hg.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&&gg(t),new fg(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&gg(e),parseInt(qe(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function gg(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}class mg{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 d=new Uint8Array(9);return d[0]=8,d.set(fg.fromNumber(e.value.valueOf()).bytes,1),d;case"uuid":if(!Tg.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const u=new Uint8Array(17);return u[0]=9,u.set(je(e.value.replace(/\-/g,"")),1),u}}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 Li;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 Li).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 Og{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 Pg{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 Ig{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 Mg(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 Ng{constructor({utf8Encoder:e,utf8Decoder:t}){this.eventStreamCodec=new Rg(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 d=0;for(;d{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,Ug=e=>new $g(e);const Lg=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()},Dg=64,Bg=[1732584193,4023233417,2562383102,271733878];class zg{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 Te(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===Dg&&(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%Dg>=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=qg(r,n,i,o,e.getUint32(0,!0),7,3614090360),o=qg(o,r,n,i,e.getUint32(4,!0),12,3905402710),i=qg(i,o,r,n,e.getUint32(8,!0),17,606105819),n=qg(n,i,o,r,e.getUint32(12,!0),22,3250441966),r=qg(r,n,i,o,e.getUint32(16,!0),7,4118548399),o=qg(o,r,n,i,e.getUint32(20,!0),12,1200080426),i=qg(i,o,r,n,e.getUint32(24,!0),17,2821735955),n=qg(n,i,o,r,e.getUint32(28,!0),22,4249261313),r=qg(r,n,i,o,e.getUint32(32,!0),7,1770035416),o=qg(o,r,n,i,e.getUint32(36,!0),12,2336552879),i=qg(i,o,r,n,e.getUint32(40,!0),17,4294925233),n=qg(n,i,o,r,e.getUint32(44,!0),22,2304563134),r=qg(r,n,i,o,e.getUint32(48,!0),7,1804603682),o=qg(o,r,n,i,e.getUint32(52,!0),12,4254626195),i=qg(i,o,r,n,e.getUint32(56,!0),17,2792965006),n=qg(n,i,o,r,e.getUint32(60,!0),22,1236535329),r=Hg(r,n,i,o,e.getUint32(4,!0),5,4129170786),o=Hg(o,r,n,i,e.getUint32(24,!0),9,3225465664),i=Hg(i,o,r,n,e.getUint32(44,!0),14,643717713),n=Hg(n,i,o,r,e.getUint32(0,!0),20,3921069994),r=Hg(r,n,i,o,e.getUint32(20,!0),5,3593408605),o=Hg(o,r,n,i,e.getUint32(40,!0),9,38016083),i=Hg(i,o,r,n,e.getUint32(60,!0),14,3634488961),n=Hg(n,i,o,r,e.getUint32(16,!0),20,3889429448),r=Hg(r,n,i,o,e.getUint32(36,!0),5,568446438),o=Hg(o,r,n,i,e.getUint32(56,!0),9,3275163606),i=Hg(i,o,r,n,e.getUint32(12,!0),14,4107603335),n=Hg(n,i,o,r,e.getUint32(32,!0),20,1163531501),r=Hg(r,n,i,o,e.getUint32(52,!0),5,2850285829),o=Hg(o,r,n,i,e.getUint32(8,!0),9,4243563512),i=Hg(i,o,r,n,e.getUint32(28,!0),14,1735328473),n=Hg(n,i,o,r,e.getUint32(48,!0),20,2368359562),r=Wg(r,n,i,o,e.getUint32(20,!0),4,4294588738),o=Wg(o,r,n,i,e.getUint32(32,!0),11,2272392833),i=Wg(i,o,r,n,e.getUint32(44,!0),16,1839030562),n=Wg(n,i,o,r,e.getUint32(56,!0),23,4259657740),r=Wg(r,n,i,o,e.getUint32(4,!0),4,2763975236),o=Wg(o,r,n,i,e.getUint32(16,!0),11,1272893353),i=Wg(i,o,r,n,e.getUint32(28,!0),16,4139469664),n=Wg(n,i,o,r,e.getUint32(40,!0),23,3200236656),r=Wg(r,n,i,o,e.getUint32(52,!0),4,681279174),o=Wg(o,r,n,i,e.getUint32(0,!0),11,3936430074),i=Wg(i,o,r,n,e.getUint32(12,!0),16,3572445317),n=Wg(n,i,o,r,e.getUint32(24,!0),23,76029189),r=Wg(r,n,i,o,e.getUint32(36,!0),4,3654602809),o=Wg(o,r,n,i,e.getUint32(48,!0),11,3873151461),i=Wg(i,o,r,n,e.getUint32(60,!0),16,530742520),n=Wg(n,i,o,r,e.getUint32(8,!0),23,3299628645),r=Kg(r,n,i,o,e.getUint32(0,!0),6,4096336452),o=Kg(o,r,n,i,e.getUint32(28,!0),10,1126891415),i=Kg(i,o,r,n,e.getUint32(56,!0),15,2878612391),n=Kg(n,i,o,r,e.getUint32(20,!0),21,4237533241),r=Kg(r,n,i,o,e.getUint32(48,!0),6,1700485571),o=Kg(o,r,n,i,e.getUint32(12,!0),10,2399980690),i=Kg(i,o,r,n,e.getUint32(40,!0),15,4293915773),n=Kg(n,i,o,r,e.getUint32(4,!0),21,2240044497),r=Kg(r,n,i,o,e.getUint32(32,!0),6,1873313359),o=Kg(o,r,n,i,e.getUint32(60,!0),10,4264355552),i=Kg(i,o,r,n,e.getUint32(24,!0),15,2734768916),n=Kg(n,i,o,r,e.getUint32(52,!0),21,1309151649),r=Kg(r,n,i,o,e.getUint32(16,!0),6,4149444226),o=Kg(o,r,n,i,e.getUint32(44,!0),10,3174756917),i=Kg(i,o,r,n,e.getUint32(8,!0),15,718787259),n=Kg(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(Dg)),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}}function jg(e,t,r,n,i,o){return((t=(t+e&4294967295)+(n+o&4294967295)&4294967295)<>>32-i)+r&4294967295}function qg(e,t,r,n,i,o,s){return jg(t&r|~t&n,e,t,i,o,s)}function Hg(e,t,r,n,i,o,s){return jg(t&n|r&~n,e,t,i,o,s)}function Wg(e,t,r,n,i,o,s){return jg(t^r^n,e,t,i,o,s)}function Kg(e,t,r,n,i,o,s){return jg(r^(t|~n),e,t,i,o,s)}const Vg="function"==typeof TextEncoder?new TextEncoder:null,Qg=e=>{if("string"==typeof e){if(Vg)return Vg.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}`)},Gg=["in-region","cross-region","mobile","standard","legacy"],Jg=()=>{const e="undefined"!=typeof window&&window?.navigator?.userAgent?hg.parse(window.navigator.userAgent):void 0,t=e?.platform?.type;return"tablet"===t||"mobile"===t},Yg=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(Jg()?"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 ${Gg.join(", ")}, got ${t}`)}})))(e),r=()=>t().then($r),n=(e=>({apiVersion:"2006-03-01",base64Decoder:e?.base64Decoder??Ce,base64Encoder:e?.base64Encoder??Pe,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??yu,extensions:e?.extensions??[],getAwsChunkedEncodingStream:e?.getAwsChunkedEncodingStream??_e,httpAuthSchemeProvider:e?.httpAuthSchemeProvider??ku,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new ue},{schemeId:"aws.auth#sigv4a",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4a"),signer:new le}],logger:e?.logger??new Kr,sdkStreamMixin:e?.sdkStreamMixin??Ke,serviceId:e?.serviceId??"S3",signerConstructor:e?.signerConstructor??na,signingEscapePath:e?.signingEscapePath??!1,urlParser:e?.urlParser??As,useArnRegion:e?.useArnRegion??!1,utf8Decoder:e?.utf8Decoder??Te,utf8Encoder:e?.utf8Encoder??Oe}))(e);return{...n,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??Qg,credentialDefaultProvider:e?.credentialDefaultProvider??(e=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??pg({serviceId:n.serviceId,clientVersion:Bf}),eventStreamSerdeProvider:e?.eventStreamSerdeProvider??Ug,maxAttempts:e?.maxAttempts??3,md5:e?.md5??zg,region:e?.region??(i="Region is missing",()=>Promise.reject(i)),requestHandler:Le.create(e?.requestHandler??r),retryMode:e?.retryMode??(async()=>(await r()).retryMode||_s),sha1:e?.sha1??Yf,sha256:e?.sha256??ug,streamCollector:e?.streamCollector??De,streamHasher:e?.streamHasher??Lg,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}},em=e=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()});class tm extends qt{constructor(...[e]){const t=Yg(e||{});var r;const n=function(e){const t=Ee(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()=>Cs(await pe(r)()):void 0,i=!!r,o={...e,endpoint:n,tls:t,isCustomEndpoint:i,useDualstackEndpoint:pe(e.useDualstackEndpoint??!1),useFipsEndpoint:pe(e.useFipsEndpoint??!1)};let s;return o.serviceConfiguredEndpoint=async()=>(e.serviceId&&!s&&(s=xs(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!!ps(e)||("function"!=typeof r?Promise.resolve(!!r):r())}}})((e=>{const{retryStrategy:t}=e,r=pe(e.maxAttempts??3);return{...e,maxAttempts:r,retryStrategy:async()=>t||(await pe(e.retryMode)()===Is.ADAPTIVE?new js(r):new zs(r))}})((i=n,{...i,requestChecksumCalculation:pe(i.requestChecksumCalculation??Y),responseChecksumValidation:pe(i.responseChecksumValidation??X)}))))),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 ho((async e=>r().send(new n({Bucket:e,SessionMode:"ReadWrite"})))),bucketEndpoint:e.bucketEndpoint??!1}})(Eu(o),{session:[()=>this,Df]}),a=((e,t)=>{const r={...Xg(e),...Br(e),...U(e),...Zg(e)};return t.forEach((e=>e.configure(r))),{...e,...(i=r,{region:i.region()}),...zr(r),...(n=r,{httpHandler:n.httpHandler()}),...em(r)};var n,i})(s,e?.extensions||[]);super(a),this.config=a,this.middlewareStack.use((e=>({applyToStack:t=>{t.add(us(e),hs)}}))(this.config)),this.middlewareStack.use(ea(this.config)),this.middlewareStack.use(ys(this.config)),this.middlewareStack.use(Yi(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:d}=a,u=c??t.inputFilterSensitiveLog,l=d??t.outputFilterSensitiveLog,{$metadata:h,...p}=n.output;return s?.info?.({clientName:i,commandName:o,input:u(r.input),output:l(p),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(to(this.config)),this.middlewareStack.use(((e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(fe(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r}),ge)}}))(this.config,{httpAuthSchemeParametersProvider:bu,identityProviderConfigProvider:async e=>new tt({"aws.auth#sigv4":e.credentials,"aws.auth#sigv4a":e.credentials})})),this.middlewareStack.use(ke(this.config)),this.middlewareStack.use(Io(this.config)),this.middlewareStack.use(G(this.config)),this.middlewareStack.use(so(this.config)),this.middlewareStack.use(wo(this.config)),this.middlewareStack.use((e=>({applyToStack:t=>{t.addRelativeTo(Eo(e),Se)}}))(this.config))}destroy(){super.destroy()}}const rm={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0},nm=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?im(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})}),rm)}});function im(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 om extends(Ht.classBuilder().ep({...xu,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[be(r,this.serialize,this.deserialize),Ps(r,e.getEndpointParameterInstructions()),Ro(r)]})).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").f(void 0,void 0).ser(Ju).de(tl).build()){}class sm extends(Ht.classBuilder().ep({...xu,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[be(r,this.serialize,this.deserialize),Ps(r,e.getEndpointParameterInstructions()),Gi(r,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC32","CRC32C","SHA256","SHA1"]}),nm(r),co()]})).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").f(Bu,Du).ser(Yu).de(rl).build()){}class am extends(Ht.classBuilder().ep({...xu,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(e,t,r,n){return[be(r,this.serialize,this.deserialize),Ps(r,e.getEndpointParameterInstructions()),Ro(r)]})).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").f(void 0,void 0).ser(Xu).de(nl).build()){}class cm extends(Ht.classBuilder().ep({...xu,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[be(r,this.serialize,this.deserialize),Ps(r,e.getEndpointParameterInstructions()),Gi(r,{requestAlgorithmMember:"ChecksumAlgorithm",requestAlgorithmMemberHttpHeader:"x-amz-sdk-checksum-algorithm",requestChecksumRequired:!1}),no(),Ro(r),nm(r)]})).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").f(Qu,Vu).ser(Zu).de(il).build()){}class dm{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)))}}))}shouldUsePathStyle(){try{if(this.config.forcePathStyle&&"no"!==this.config.forcePathStyle)return!0;let e=this.config.endpoint;const t=new URL(e),r=t.hostname,n=/^(\d{1,3}\.){3}\d{1,3}$/.test(r),i=""!==t.port;return!n&&i}catch(e){return!0}}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 tm({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o},forcePathStyle:this.shouldUsePathStyle()});try{let e,t=[],r=[],i=!0;for(;i;){const o=yield c.send(new am({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:""})})),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 tm({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o},forcePathStyle:this.shouldUsePathStyle()});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield a.send(new om({Bucket:n,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class um extends dm{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 tm({endpoint:r,region:n,credentials:{accessKeyId:o,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle()});a=a&&"KoodoReader"===this.baseFolder?a:this.baseFolder;let d=a+"/"+t;for(;d.startsWith("/");)d=d.substring(1);try{let t=yield c.send(new cm({Bucket:i,Key:d,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 tm({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o},forcePathStyle:this.shouldUsePathStyle()});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{const e=yield a.send(new sm({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 lm{constructor(e){this.config=e,this.taskQueue=new f(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=1){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=this.config.access_token;let n=this.baseFolder;t&&""!==t.trim()&&(n=n+"/"+t),n=n.replace(/\/+/g,"/"),n.startsWith("/")&&(n=n.substring(1));let i=[],o=0;const s=1e3;for(;;){const t=yield e.get("https://pan.baidu.com/rest/2.0/xpan/file",{params:{method:"list",access_token:r,dir:"/"+n,start:o,limit:s,order:"name",desc:0,web:1,folder:0},headers:{"User-Agent":"pan.baidu.com"}});if(t.status>=300||0!==t.data.errno){console.error("百度网盘API错误:",t.data);break}const a=t.data.list||[];if(0===a.length)break;if(i=i.concat(a),a.length({name:e.server_filename,size:e.size||0,type:e.isdir?"folder":"file",modified:new Date(1e3*e.server_mtime).toISOString(),path:e.path,fs_id:e.fs_id})))}catch(e){return console.error("获取百度网盘文件列表时发生错误:",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=this.config.access_token;let n=this.baseFolder+"/"+t;n=n.replace(/\/+/g,"/"),n.startsWith("/")&&(n=n.substring(1));const i=new URLSearchParams({async:"0",filelist:JSON.stringify(["/"+n])}),o=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=${r}&opera=delete`,i.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==o.data.errno)return console.error("百度网盘删除文件API错误:",o.data),-9===o.data.errno?console.error("文件不存在"):111===o.data.errno?console.error("有其他异步任务正在执行"):-7===o.data.errno&&console.error("文件名非法"),!1;const s=o.data.info||[];for(const e of s)if(0!==e.errno)return console.error(`文件删除失败: ${e.path}, 错误码: ${e.errno}`),!1;return!0}catch(e){return console.error("删除文件时发生错误:",e),!1}}))}getAuthUrl(e){return`https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=${y.duboxClientId}&redirect_uri=${e}&scope=basic,netdisk&device_id=119827642&display=page&qrcode=1`}}class hm extends lm{constructor(e){super(e)}uploadFile(e,t){return a(this,void 0,void 0,(function*(){return!0}))}downloadFile(e){return a(this,void 0,void 0,(function*(){return!1}))}}class pm{constructor(e){this.baseUrl="https://proapi.115.com",this.config=e,this.taskQueue=new f(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=1){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)))}}))}getUploadCredentials(t){return a(this,void 0,void 0,(function*(){try{const r=yield e.get(`${this.baseUrl}/open/upload/get_token`,{headers:{Authorization:`Bearer ${t}`}});return r.status>=300||!r.data.state?(console.error("Error getting upload credentials:",r.data),null):r.data.data}catch(e){return console.error("Error occurred during get upload credentials:",e),null}}))}generateOSSPolicy(e,t,r=new Date(Date.now()+36e5)){const n={expiration:r.toISOString(),conditions:[{bucket:e},{key:t},["starts-with","$success_action_status","2"],["content-length-range",0,1073741824]]};return JSON.stringify(n)}getAuthUrl(e){return`https://passportapi.115.com/open/authorize?client_id=${y.yiyiwuClientId}&response_type=code&redirect_uri=${e}`}}class fm extends pm{constructor(e){super(e)}uploadFile(e,t){return a(this,void 0,void 0,(function*(){return!0}))}downloadFile(e){return a(this,void 0,void 0,(function*(){return!1}))}}class gm{constructor(e){let{username:t,password:r,url:n,dir:i,AuthType:o,createClient:s}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,i=i&&"KoodoReader"===this.baseFolder?i:this.baseFolder,this.username=t,this.password=r,this.url=n,this.dir=i,this.taskQueue=new f(5),this.AuthType=o,this.createClient=s}getClient(){return a(this,void 0,void 0,(function*(){return this.webdavClient||(this.url=yield this.handleUrlRedirection(this.url),this.webdavClient=this.createClient(this.url,{authType:this.AuthType.Password,username:this.username,password:this.password})),this.webdavClient}))}handleUrlRedirection(t){return a(this,void 0,void 0,(function*(){try{const r=yield e.head(t,{maxRedirects:0,validateStatus:()=>!0});return r.request&&r.request.responseURL&&r.request.responseURL!==t?r.request.responseURL:r.status>=300&&r.status<400&&r.headers.location?r.headers.location:t}catch(e){return console.info("Error handling URL redirection:",e),t}}))}retryOperation(e,t=1){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*(){const t=yield this.getClient();try{return(yield t.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(r){return r.response&&404===r.response.status&&(yield t.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",r),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){const t=yield this.getClient();try{return yield t.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(e){return a(this,void 0,void 0,(function*(){let t=yield this.getClient();try{const r=e.replace(/^\/+|\/+$/g,"").split("/").filter((e=>e.length>0));let n="";for(const e of r)n=n?`${n}/${e}`:e,(yield t.exists(`/${n}`))||(yield t.createDirectory(`/${n}`));return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}}class mm extends gm{constructor(e){super(Object.assign(Object.assign({},e),{AuthType:n,createClient:i}))}retryOperation(e,t=1){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{let n=this.dir+"/"+r,i=yield this.getClient();const o=i.exists(n.substring(0,n.lastIndexOf("/"))),s=new Promise(((e,t)=>{setTimeout((()=>t(new Error("WebDAV exists check timeout"))),5e3)}));!1===(yield Promise.race([o,s]))&&(yield this.ensureDirectoryExists(n.substring(0,n.lastIndexOf("/"))));let a=r.split("/").pop()||"",c=new File([t],a,{lastModified:(new Date).getTime(),type:t.type}),d=i.getFileUploadLink(this.dir+"/"+r);const u=new URL(d);u.search="",d=u.toString();const l=btoa(this.username+":"+this.password),h=yield e.put(d,c,{headers:{Authorization:"Basic "+l},maxContentLength:1/0,maxBodyLength:1/0});return!(h.status>=300)||(console.error("Error occurred during file upload:",h),!1)}catch(e){return console.error("Error 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}}))))))}))}}class ym{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.taskQueue=new f(3)}retryOperation(e,t=1){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 bm extends ym{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=this.listFiles("");const s=new Promise(((e,t)=>{setTimeout((()=>t(new Error("Docker connection timeout"))),5e3)}));yield Promise.race([o,s]);let a=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const c=new FormData;c.append("file",a);const d=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(i)}`,c,{headers:{Authorization:this.getAuthHeader(),"Content-Type":"multipart/form-data"},maxContentLength:1/0,maxBodyLength:1/0});return!(d.status>=300)||(console.error("Error occurred during file upload:",d),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return 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 vm=["book","config","cover","font"];class wm{constructor(e,t){this.type=e,this.remote="dropbox"===e?new A(t):"microsoft"===e?new M(t):"google"===e?new O(t):"microsoft_exp"===e?new M(Object.assign(Object.assign({},t),{isExp:!0})):"google_exp"===e?new O(Object.assign(Object.assign({},t),{isExp:!0})):"s3compatible"===e?new um(t):"webdav"===e?new mm(t):"docker"===e?new bm(t):"boxnet"===e?new E(t):"mega"===e?new I(t):"adrive"===e?new S(t):"pcloud"===e?new F(t):"dubox"===e?new hm(t):"yandex"===e?new T(t):"yiyiwu"===e?new fm(t):new N}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 0===r.size||(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 vm){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,e)}}))}getAuthUrl(e){return this.remote.getAuthUrl?this.remote.getAuthUrl(e):""}getStats(){return this.remote.taskQueue.getStats()}clearQueue(){return this.remote.taskQueue.clearQueue()}resetCounters(){this.remote.taskQueue.resetCounters()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const Sm={words:['ALTER TABLE words ADD COLUMN "sentence" text']},km={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 = ?"},Em={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},xm={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"},Am={createTableStatement:Cm({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 "sentence" text,\n "chapter" text\n );\n '}),migrateStatement:Cm(Sm),getAllStatement:Cm({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),getPagedStatement:Cm({notes:"SELECT * FROM notes LIMIT ? OFFSET ?",bookmarks:"SELECT * FROM bookmarks LIMIT ? OFFSET ?",books:"SELECT * FROM books LIMIT ? OFFSET ?",plugins:"SELECT * FROM plugins LIMIT ? OFFSET ?",words:"SELECT * FROM words LIMIT ? OFFSET ?"}),getCountStatement:Cm({notes:"SELECT COUNT(*) as count FROM notes",bookmarks:"SELECT COUNT(*) as count FROM bookmarks",books:"SELECT COUNT(*) as count FROM books",plugins:"SELECT COUNT(*) as count FROM plugins",words:"SELECT COUNT(*) as count FROM words"}),saveStatement:Cm({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, sentence, chapter) VALUES (@key, @bookKey, @date, @word, @sentence, @chapter)"}),deleteAllStatement:Cm({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:Cm({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, sentence = @sentence, chapter = @chapter WHERE key = @key"}),deleteStatement:Cm({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:Cm({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:Cm(km),getByBookKeyStatement:Cm(Em),getByBookKeysStatement:Cm({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(",")})`}),getKeysStatement:Cm({notes:"SELECT key FROM notes",bookmarks:"SELECT key FROM bookmarks",books:"SELECT key FROM books",plugins:"SELECT key FROM plugins",words:"SELECT key FROM words"}),getWithSortAndPageStatement:Cm({notes:(e,t,r,n)=>`SELECT * FROM notes ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${n}`,bookmarks:(e,t,r,n)=>`SELECT * FROM bookmarks ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${n}`,books:(e,t,r,n)=>`SELECT * FROM books ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${n}`,plugins:(e,t,r,n)=>`SELECT * FROM plugins ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${n}`,words:(e,t,r,n)=>`SELECT * FROM words ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${n}`}),getByKeysStatement:Cm({notes:e=>`SELECT * FROM notes WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,bookmarks:e=>`SELECT * FROM bookmarks WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,plugins:e=>`SELECT * FROM plugins WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,words:e=>`SELECT * FROM words WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`}),deleteByBookKeyStatement:Cm(xm)};function Cm(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const Tm={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),void 0===t.sentence&&(t.sentence=""),t}};var Rm={sqlStatement:Am,jsonToSqlite:Cm({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),void 0===t.sentence&&(t.sentence=""),t}}),sqliteToJson:Cm(Tm)};const Om=m.cloudUrl,Pm=m.cloudCNUrl;class Im{constructor(e,t,r){this.TokenService=e,this.ConfigService=t,this.baseUrl="china"===r?Pm:Om,this.serverRegion=r,this.refreshToken="",this.accessToken="",this.streamPromise=null,this.expiresAt=0}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),yield this.TokenService.setToken("expires_at",(1e3*t.data.expires_at).toString()),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token,this.expiresAt=1e3*t.data.expires_at),t}))}requestWithRetry(e){return a(this,void 0,void 0,(function*(){return Im.requestQueue||(Im.requestQueue=[]),new Promise(((t,r)=>{Im.requestQueue.push({config:e,resolve:t,reject:r}),Im.processingQueue||this.processQueue()}))}))}isTokenValid(){return a(this,void 0,void 0,(function*(){if(this.accessToken||(this.accessToken=(yield this.TokenService.getToken("access_token"))||""),!this.expiresAt){const e=yield this.TokenService.getToken("expires_at");this.expiresAt=e?parseInt(e):(new Date).getTime()+31536e9}return""!==this.accessToken&&this.expiresAt>(new Date).getTime()+6e4}))}processQueue(){return a(this,void 0,void 0,(function*(){if(!Im.processingQueue){Im.processingQueue=!0;try{for(;Im.requestQueue.length>0;){const e=Im.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{Im.processingQueue=!1}}}))}executeRequest(t){return a(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());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&&console.error("Request error:",n),n}catch(e){return console.error("Request execution error:",e),"Network Error"===e.message?{code:503,message:"network error",data:null,msg:"Network error, please try again later. 网络错误,请稍后再试。"}:{code:500,message:e.message||"Unknown error",msg:e.message||"Unknown 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{(yield this.isTokenValid())||(yield this.refreshUserToken());let n=this.accessToken||"",i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((o,s)=>{let c=this.ConfigService.getItem("appVersion"),d=this.ConfigService.getItem("appPlatform");const u=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":d||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});u.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),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(),o(r)):t(r.data)})))),u.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);o(t),u.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{(yield this.isTokenValid())||(yield this.refreshUserToken());let r=this.accessToken||"",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 d=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"});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(),i(r)):t(r.data)})))),d.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),d.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const t=JSON.parse(e.data);i(t),d.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}Im.processingQueue=!1,Im.requestQueue=[];class _m extends Im{constructor(e,t,r){super(e,t,r)}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)}))}getBatchTrans(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_batch_trans",data:e};return yield this.requestWithRetry(t)}))}getSplitSentence(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_split_sentence",data:e};return yield this.requestWithRetry(t)}))}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)}))}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)}))}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)}))}getDictionaryStream(e,t,r){return a(this,void 0,void 0,(function*(){const n={method:"post",url:"/api/v1/pro/reader/get_llm_dict_stream",data:e};return yield this.requestWithStream(n,t,r)}))}getDictionaryFetch(e,t){return a(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_dict_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)}))}detectLanguage(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/detect_language",data:e};return yield this.requestWithRetry(t)}))}getTTSAudio(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_tts_audio",data:e};return yield this.executeRequest(t)}))}getOcrResult(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_ocr_result",data:e};return yield this.requestWithRetry(t)}))}analyzeText(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/analyze_text",data:e};return yield this.requestWithRetry(t)}))}}class Mm extends Im{constructor(e,t,r){super(e,t,r),this.serverRegion=r}encryptToken(e){return a(this,void 0,void 0,(function*(){let t=e.token,r=p.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&&n.data&&n.data.token){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 n="";if("github"===e?n=`https://github.com/login/oauth/authorize?client_id=${y.githubClientId}&redirect_uri=${r}&scope=${b.github.scopes.join(" ")}&response_type=code`:"google"===e?n=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${r}&prompt=consent&response_type=code&client_id=${y.googleClientId}&scope=${b.google.scopes.join(" ")}&access_type=offline`:"facebook"===e?n=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${y.facebookClientId}&redirect_uri=${r}&scope=&response_type=code`:"microsoft"===e&&(n=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${y.microsoftClientId}&scope=${b.microsoft.scopes.join(" ")}&response_type=code&redirect_uri=${r}`),"manual"===t)return n;let i=JSON.stringify({deeplink:"desktop"===t?"koodo-reader://callback":"browser"===t?`${y.callbackUrl}#/login`:"",service:e});return`${n}&state=${"state|"+encodeURIComponent(i)}`}};class Fm{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"))),d=Object.keys(t).filter((e=>e.startsWith("database.sqlite.notes"))),u=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"))),p={books:Array.from(new Set(n.concat(c))),notes:Array.from(new Set(i.concat(d))),bookmarks:Array.from(new Set(o.concat(u))),plugins:Array.from(new Set(s.concat(l))),words:Array.from(new Set(a.concat(h)))},f={books:{save:[],update:[],delete:[],conflict:[],upload:[]},notes:{save:[],update:[],delete:[],conflict:[],upload:[]},bookmarks:{save:[],update:[],delete:[],conflict:[],upload:[]},plugins:{save:[],update:[],delete:[],conflict:[],upload:[]},words:{save:[],update:[],delete:[],conflict:[],upload:[]}},g=["books","notes","bookmarks","plugins","words"];for(let n of g)for(let i of p[n]){let o=i.split(".")[3],s=e[i],a=t[i];s?a?("save"===a.operation&&("update"!==s.operation&&"delete"!==s.operation||f[n].upload.push(o)),"delete"===a.operation&&("save"===s.operation&&(f[n].delete.push(o),e[i]=a),"update"===s.operation&&(s.timea.time&&(f[n].conflict.push(o),"cloud"===r?(f[n].delete.push(o),e[i]=a):f[n].upload.push(o))),s.operation),"update"===a.operation&&("save"===s.operation&&(f[n].update.push(o),e[i]=a),"update"===s.operation&&(s.timea.time&&f[n].upload.push(o)),"delete"===s.operation&&(s.timea.time&&f[n].upload.push(o)))):f[n].upload.push(o):(f[n].save.push(o),e[i]=a)}return{compareResult:f,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"))),d=Object.keys(t).filter((e=>e.startsWith("config.objectConfig"))),u=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(d))),mapConfig:Array.from(new Set(s.concat(u)))},h={readerConfig:{update:[],upload:[]},listConfig:{update:[],upload:[]},objectConfig:{update:[],delete:[],conflict:[],save:[],upload:[]},mapConfig:{update:[],delete:[],conflict:[],save:[],upload:[]}},p=["readerConfig","listConfig"];for(let r of p)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):h[r].upload.push(i):(h[r].update.push(i),e[n]=s)}let f=["objectConfig","mapConfig"];for(let n of f)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))),s.operation),"update"===a.operation&&("update"===s.operation&&(s.timea.time&&h[n].upload.push(o)),"delete"===s.operation&&(s.timea.time&&h[n].upload.push(o)))):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:d}=yield this.CompareConfig(a,t,o),u=Object.assign(Object.assign({},s),c);return r.setAllSyncRecord(d),"local"===o&&(u.books.conflict.length>0||u.notes.conflict.length>0||u.bookmarks.conflict.length>0||u.plugins.conflict.length>0||u.words.conflict.length>0||u.objectConfig.conflict.length>0||u.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"),u}))}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,o,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,o){return a(this,void 0,void 0,(function*(){let s=[];for(let t of d){if(e[t].save.length+e[t].update.length>0){let n=yield o.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 o of e[t].delete)"books"===t&&(yield n.deleteOfflineBook(o),yield i.deleteOfflineCover(o)),yield r.deleteRecord(o,t);yield r.dumpDatabase(t,!0)}if(e.readerConfig.update.length>0||e.listConfig.update.length>0||e.objectConfig.update.length>0||e.mapConfig.update.length>0){let r=yield o.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 d)e[t].upload.length>0&&s.push((()=>o.uploadDatabase(t)));return s.push((()=>o.uploadConfig("config"))),s.push((()=>o.uploadConfig("sync"))),s}))}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()}))}}class Um{constructor(e,t){this.bookKey="",this.sessionStart=0,this.unregisterUnload=null,this.configService=e,this.platform=t}getDailySeconds(e,t){const r=((this.configService.getAllMapConfig("readingStats")||{})[t]||[]).find((t=>t.startsWith(e+"-")));if(!r)return 0;const n=r.split("-");return parseInt(n[n.length-1],10)||0}setDailySeconds(e,t,r){const n=(this.configService.getAllMapConfig("readingStats")||{})[t]||[],i=`${e}-${r}`,o=n.filter((t=>!t.startsWith(e+"-")));this.configService.setOneMapConfig(t,[...o,i],"readingStats")}start(e){this.bookKey=e,this.sessionStart=Date.now(),this.unregisterUnload=this.platform.registerUnloadHandler((()=>{var e,t;this.commit(),null===(t=(e=this.platform).onBeforeClose)||void 0===t||t.call(e)}))}stop(){var e;this.commit(),null===(e=this.unregisterUnload)||void 0===e||e.call(this),this.unregisterUnload=null,this.bookKey="",this.sessionStart=0}commit(){if(!this.bookKey||!this.sessionStart)return;const e=Date.now()-this.sessionStart;if(e<1e3)return void(this.sessionStart=0);const t=Math.round(e/1e3);this.sessionStart=0;const r=this.configService.getObjectConfig(this.bookKey,"readingTime",0);this.configService.setObjectConfig(this.bookKey,r+t,"readingTime");const n=function(){const e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}(),i=this.getDailySeconds(this.bookKey,n);this.setDailySeconds(this.bookKey,n,i+t)}getTotalSeconds(e){return this.configService.getObjectConfig(e,"readingTime",0)}getDailySecondsForBook(e,t){return this.getDailySeconds(e,t)}getDayStats(e){return((this.configService.getAllMapConfig("readingStats")||{})[e]||[]).map((e=>{const t=e.lastIndexOf("-");return{bookKey:e.substring(0,t),seconds:parseInt(e.substring(t+1),10)||0}}))}getAllDates(){const e=this.configService.getAllMapConfig("readingStats");return Object.keys(e||{})}}const Lm=(Dm=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,t){localStorage.setItem(e,t)}static removeItem(e){localStorage.removeItem(e)}},Bm="browser",(zm=class extends Dm{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:Bm,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 flushSyncRecords(){if(0===Object.keys(this.pendingSyncRecords).length)return;let e=JSON.parse(this.getItem("syncRecord")||"{}");Object.assign(e,this.pendingSyncRecords),this.setItem("syncRecord",JSON.stringify(e)),this.pendingSyncRecords={},this.syncRecordTimer=null}static setSyncRecord(e,t){const r=e.type+"."+e.catergory+"."+e.name+"."+e.key;this.pendingSyncRecords[r]=t,null!==this.syncRecordTimer&&clearTimeout(this.syncRecordTimer),this.syncRecordTimer=setTimeout((()=>{this.flushSyncRecords()}),this.DEBOUNCE_DELAY)}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}}).pendingSyncRecords={},zm.syncRecordTimer=null,zm.DEBOUNCE_DELAY=1e3,zm);var Dm,Bm,zm;class jm{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 Wm(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=qm((new TextEncoder).encode(JSON.stringify(r))),i=qm((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}.${qm(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"child_database"===e.type));if(!n)throw new Error(`No child database found in page ${t}. Please provide a Database ID directly.`);return n.id}))}findOrCreatePage(e,t,r){return a(this,void 0,void 0,(function*(){const n=`${r}`,i=yield fetch(`https://api.notion.com/v1/databases/${t}/query`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({filter:{property:"title",title:{equals:n}}})});if(!i.ok){const n=yield i.json().catch((()=>({})));if(400===i.status&&"validation_error"===(null==n?void 0:n.code)&&"string"==typeof(null==n?void 0:n.message)&&n.message.includes("is a page, not a database")){const n=yield this.resolveDatabaseId(e,t);return this.findOrCreatePage(e,n,r)}throw new Error(`Notion API error: ${i.status} ${i.statusText}`)}const o=yield i.json();if(o.results&&o.results.length>0)return o.results[0].id;const s=yield fetch("https://api.notion.com/v1/pages",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({parent:{database_id:t},properties:{title:{title:[{text:{content:n}}]}}})});if(!s.ok)throw new Error(`Notion create page error: ${s.status} ${s.statusText}`);return(yield s.json()).id}))}appendBlocks(e,t,r,n){return a(this,void 0,void 0,(function*(){const i=!r.notes||0===r.notes.length,o=[];o.push({object:"block",type:"divider",divider:{}}),n&&o.push({object:"block",type:"heading_3",heading_3:{rich_text:[{type:"text",text:{content:n}}]}}),o.push({object:"block",type:"quote",quote:{rich_text:[{type:"text",text:{content:r.text||""}}]}}),!i&&r.notes&&o.push({object:"block",type:"paragraph",paragraph:{rich_text:[{type:"text",text:{content:`📝 ${r.notes}`}}]}});const s=`${r.date.year}-${String(r.date.month).padStart(2,"0")}-${String(r.date.day).padStart(2,"0")}`;o.push({object:"block",type:"paragraph",paragraph:{rich_text:[{type:"text",text:{content:`Added on ${s}`},annotations:{italic:!0,color:"gray"}}]}});const a=yield fetch(`https://api.notion.com/v1/blocks/${t}/children`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({children:o})});if(!a.ok)throw new Error(`Notion append blocks error: ${a.status} ${a.statusText}`)}))}syncNote(e,t){return a(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const r=this.getConfig();if(!r)return!1;try{const n=yield this.findOrCreatePage(r.token,r.databaseId,t);return yield this.appendBlocks(r.token,n,e,e.chapter||""),!0}catch(e){return console.error("Notion sync failed:",e),!1}}))}}class Vm{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("yuqueSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?null:e}catch(e){return null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableYuqueSync")}findOrCreateDoc(e,t,r){return a(this,void 0,void 0,(function*(){const n=`${r}`,i=`koodo-reader-${r.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g,"-").replace(/-+/g,"-").toLowerCase().substring(0,50)}`;try{const r=yield fetch(`${Vm.API_BASE}/repos/${t}/docs/${i}`,{method:"GET",headers:{"X-Auth-Token":e,"Content-Type":"application/json"}});if(r.ok){const e=yield r.json();return{id:e.data.id,slug:e.data.slug,body:e.data.body||""}}}catch(e){}const o=yield fetch(`${Vm.API_BASE}/repos/${t}/docs`,{method:"POST",headers:{"X-Auth-Token":e,"Content-Type":"application/json"},body:JSON.stringify({title:n,slug:i,body:`# ${n}\n\n`,format:"markdown"})});if(!o.ok)throw new Error(`Yuque create doc error: ${o.status} ${o.statusText}`);const s=yield o.json();return{id:s.data.id,slug:s.data.slug,body:s.data.body||""}}))}formatNoteMarkdown(e){const t=!e.notes||0===e.notes.length,r=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let n="\n---\n\n";return e.chapter&&(n+=`### ${e.chapter}\n\n`),n+=`> ${e.text||""}\n\n`,!t&&e.notes&&(n+=`📝 ${e.notes}\n\n`),n+=`*Added on ${r}*\n\n`,n}updateDoc(e,t,r,n){return a(this,void 0,void 0,(function*(){const i=yield fetch(`${Vm.API_BASE}/repos/${t}/docs/${r}`,{method:"PUT",headers:{"X-Auth-Token":e,"Content-Type":"application/json"},body:JSON.stringify({body:n,format:"markdown"})});if(!i.ok)throw new Error(`Yuque update doc error: ${i.status} ${i.statusText}`)}))}syncNote(e,t){return a(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const r=this.getConfig();if(!r)return!1;try{const n=yield this.findOrCreateDoc(r.token,r.namespace,t),i=this.formatNoteMarkdown(e),o=n.body+i;return yield this.updateDoc(r.token,r.namespace,n.id,o),!0}catch(e){return console.error("Yuque sync failed:",e),!1}}))}}Vm.API_BASE="https://www.yuque.com/api/v2";class Qm{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("readwiseSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?null:e}catch(e){return null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableReadwiseSync")}syncNote(e,t,r){return a(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const n=this.getConfig();if(!n)return!1;const i=`${t}`,o=!e.notes||0===e.notes.length,s={text:e.text||"",title:i,author:r||"Unknown",source_type:"koodo-reader",category:"books",highlighted_at:`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`};if(!o&&e.notes&&(s.note=e.notes),e.chapter){const t=parseInt(e.chapter,10);isNaN(t)||(s.location_type="order",s.location=t)}try{const e=yield fetch(`${Qm.API_BASE}/highlights/`,{method:"POST",headers:{Authorization:`Token ${n.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({highlights:[s]})});if(!e.ok)throw new Error(`Readwise API error: ${e.status} ${e.statusText}`);return!0}catch(e){return console.error("Readwise sync failed:",e),!1}}))}}Qm.API_BASE="https://readwise.io/api/v2";class Gm{constructor(e,t){this.databaseService=e,this.notionSync=new Km(t),this.yuqueSync=new Vm(t),this.readwiseSync=new Qm(t)}getExtraServices(){return[]}getEnabledServices(){const e=[];return this.notionSync.isEnabled()&&e.push({name:"Notion",sync:this.notionSync.syncNote.bind(this.notionSync)}),this.yuqueSync.isEnabled()&&e.push({name:"Yuque",sync:this.yuqueSync.syncNote.bind(this.yuqueSync)}),this.readwiseSync.isEnabled()&&e.push({name:"Readwise",sync:this.readwiseSync.syncNote.bind(this.readwiseSync)}),[...e,...this.getExtraServices()]}syncNote(e,t){return a(this,void 0,void 0,(function*(){const r=this.getEnabledServices();if(0===r.length)return;let n="Unknown Book",i="";if(t||e.bookKey)try{const r=yield this.databaseService.getRecord(t||e.bookKey,"books");r&&r.name&&(n=r.name),r&&r.author&&(i=r.author)}catch(r){console.warn(`Failed to resolve book info for key: ${t||e.bookKey}`)}const o=(yield Promise.allSettled(r.map((t=>a(this,void 0,void 0,(function*(){try{const r=yield t.sync(e,n,i);return{name:t.name,success:r}}catch(e){return console.error(`${t.name} sync error:`,e),{name:t.name,success:!1}}})))))).filter((e=>"rejected"===e.status||"fulfilled"===e.status&&!e.value.success)).map((e=>"fulfilled"===e.status?e.value.name:"Unknown"));o.length>0&&console.error(`Note sync failed for: ${o.join(", ")}`)}))}}class Jm{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("markdownSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?null:e}catch(e){return null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableMarkdownSync")}formatNoteMarkdown(e){const t=!e.notes||0===e.notes.length,r=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let n="\n---\n\n";return e.chapter&&(n+=`### ${e.chapter}\n\n`),n+=`> ${e.text||""}\n\n`,!t&&e.notes&&(n+=`📝 ${e.notes}\n\n`),n+=`*Added on ${r}*\n\n`,n}sanitizeFileName(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()}syncNote(e,t,r){return a(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const n=window.require("fs"),i=window.require("path"),o=this.getConfig();if(!o)return!1;const s=o.folder;if(!s)return!1;try{const o=this.sanitizeFileName(t),a=i.join(s,`${o}.md`);if(!n.existsSync(a)){const e=`# ${t}\n`,i=r?`**Author:** ${r}\n\n`:"\n";n.writeFileSync(a,e+i,"utf-8")}const c=this.formatNoteMarkdown(e);return n.appendFileSync(a,c,"utf-8"),!0}catch(e){return console.error("Markdown sync failed:",e),!1}}))}}class Ym extends Gm{constructor(e,t){super(e,t),this.markdownSync=new Jm(t)}getExtraServices(){return this.markdownSync.isEnabled()?[{name:"Markdown",sync:this.markdownSync.syncNote.bind(this.markdownSync)}]:[]}}export{g as CommonTool,Lm as ConfigService,v as KookitConfig,$m as LoginHelper,Ym as NoteSyncManager,_m as ReaderRequest,Um as ReadingTimeUtil,Rm as SqlStatement,Fm as SyncHelper,wm as SyncUtil,Mm as ThirdpartyRequest,jm as TokenService,Nm as UserRequest}; +import e from"axios";import{Storage as t}from"megajs";import{Buffer as r}from"buffer";import{AuthType as n,createClient 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,d=["books","notes","bookmarks","plugins","words"],u=e=>{const t=atob(e),r=t.length,n=new Uint8Array(r);for(let e=0;e{let t="";const r=new Uint8Array(e),n=r.byteLength;for(let e=0;ee>>>t|e<<32-t,n=(e,t,r)=>e&t^~e&r,i=(e,t,r)=>e&t^e&r^t&r,o=e=>r(e,2)^r(e,13)^r(e,22),s=e=>r(e,6)^r(e,11)^r(e,25),a=e=>r(e,7)^r(e,18)^e>>>3,c=e=>r(e,17)^r(e,19)^e>>>10,d=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],u=8*e.length,l=(960-(8*e.length+1)%512)%512,h=e.length+Math.ceil((l+1)/8)+8,p=new Uint8Array(h);p.set(e),p[e.length]=128;new DataView(p.buffer,p.byteLength-8).setBigUint64(0,BigInt(u),!1);for(let e=0;e>>0;let[l,h,f,g,m,y,b,v]=d;for(let e=0;e<64;e++){const r=v+s(m)+n(m,y,b)+t[e]+u[e]>>>0,a=o(l)+i(l,h,f)>>>0;v=b,b=y,y=m,m=g+r>>>0,g=f,f=h,h=l,l=r+a>>>0}d[0]=d[0]+l>>>0,d[1]=d[1]+h>>>0,d[2]=d[2]+f>>>0,d[3]=d[3]+g>>>0,d[4]=d[4]+m>>>0,d[5]=d[5]+y>>>0,d[6]=d[6]+b>>>0,d[7]=d[7]+v>>>0}const f=new ArrayBuffer(32),g=new DataView(f);return d.forEach(((e,t)=>{g.setUint32(4*t,e,!1)})),f}const p={_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,d=(15&o)<<2|s>>6,u=63&s;t+=this._chars.charAt(a),t+=this._chars.charAt(c),t+=r-2>=i?"=":this._chars.charAt(d),t+=r-1>=i?"=":this._chars.charAt(u)}return t},decode(e){if("string"!=typeof e)throw new Error("Input must be a string");for(e=e.replace(/[^A-Za-z0-9+/]/g,"");e.length%4!=0;)e+="=";const t=[];let r=0;const n=e.length;for(;r>4,c=(15&i)<<4|o>>2,d=(3&o)<<6|s;t.push(a),-1!==o&&t.push(c),-1!==s&&t.push(d)}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 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)=>{if(this.hasFailedTasks)return void t(void 0);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:d,configList:["themeColors","readingTime","appVersion","cloudSyncTime","lastSyncTime","recentBooks","recentAdd","deletedBooks","favoriteBooks","shelfList","txtParsers","noteTags","recordLocation","thirdpartyToken","sortedShelfList","kindleDeviceList","thirdpartyToken","opdsCatalogs","opdsCatalogList"],copyArrayBuffer:e=>{var t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t},base64ToArrayBuffer:u,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}))},getDisableThinkingParams:e=>{const t=new Set(["anthropic","zhipu","doubao","moonshot","deepseek"]),r=new Set(["qwen","hunyuan","siliconflow","infini"]);return e&&"custom"!==e?t.has(e)?{thinking:{type:"disabled"}}:r.has(e)?{enable_thinking:!1}:{}:{}},EmailProviders:["gmail.com","qq.com","163.com","yahoo.com","sina.com","sina.cn","126.com","outlook.com","yeah.net","foxmail.com","hotmail.com","protonmail.com","proton.me","icloud.com","mail.com","live.com","aliyun.com","sohu.com","yandex.com","naver.com","mail.ru","yahoo.co.jp","139.com","189.com","yandex.ru","189.cn"],Base64:p};const m={cloudUrl:"https://cloud.koodoreader.com",cloudCNUrl:"https://cloud.koodoreader.cn",testUrl:"https://cloudtest.960960.xyz",devUrl:"http://192.168.28.159:8000"},y={callbackUrl:"https://web.koodoreader.com/",cnCallbackUrl:"https://web.koodoreader.cn/",dropboxClientId:"vnc67byrssocvy1",yandexClientId:"e5305b62f53844b1994f77a840fd0a37",pcloudClientId:"pg8ten0B3vH",boxClientId:"ltimecqanmpxoaicn9qw3es6l3sdl1ya",duboxClientId:"kc0Ls6xLZugGgLLVhZ8yhUU1cRkRoKNU",yiyiwuClientId:"100197197",microsoftClientId:"506df58a-29ab-4020-afc5-6f423dc80f35",googleClientId:"1051055003225-ph1f5fvh328dhv7bco5jitlnfhg6ks2t.apps.googleusercontent.com",appleClientId:"com.koodoreader.auth",facebookClientId:"2845583825559500",githubClientId:"Ov23liJVzfvJMMEEZ8v2",adriveClientId:"a128ae7b9c094545af623de61dc0a1ef"},b={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"}},apple:{clientId:y.appleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{scope:""}}},v={dropbox:{clientId:y.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{token_access_type:"offline"}},yandex:{clientId:y.yandexClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{response_type:"code",force_confirm:"true"}},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"}},dubox:{clientId:y.duboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{response_type:"code",scope:"basic,netdisk",device_id:"119827642",qrcode:"1"}},yiyiwu:{clientId:y.yiyiwuClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:y.callbackUrl,extraParams:{response_type:"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"}}};var w={CloudMode:"production",CloudConfig:m,ConvertLangMap:{zhCN:"Chinese",zhTW:"Chinese",zhMO:"Chinese",ja:"Japanese",uk:"Ukrainian",ko:"Korean",vi:"Vietnamese",th:"Thai",ru:"Russian",ar:"Arabic",fr:"French",de:"German",es:"Spanish",it:"Italian",pt:"Portuguese",ptBR:"Portuguese",nl:"Dutch",id:"Indonesian",tr:"Turkish",pl:"Polish",cs:"Czech",sv:"Swedish",bn:"Bengali",tl:"Tagalog",ga:"Irish",bg:"Bulgarian",fa:"Persian"},ContentRegxConfig:[{label:"Default parser",value:"Default parser",subtitle:"Suitable for most txt files",regex:""},{label:"Chinese novel parser",value:"Chinese novel parser",subtitle:"Suitable for most Chinese novels, eg. 第一章,第2回",regex:"^s*(第[0-9一二三四五六七八九十百千万零]+[章回])s*(.*?)$"},{label:"English novel parser",value:"English novel parser",subtitle:"Suitable for most English novels, eg. Chapter 1, Part II",regex:"^(Chapter|Part|Book|CHAPTER|PART|BOOK)\\b.*$"},{label:"Number parser",value:"Number parser",subtitle:"Suitable for novels with number chapter titles, eg. 1, 2, 3",regex:String.raw`^\s*([1-9][、.: :·\s]|[一二三四五六七八九十百千万零][、.: :·\s]).+$`}],ThirdpartyConfig:y,LoginAuthRequest:b,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"},apple:{authorizationEndpoint:"https://appleid.apple.com/auth/authorize",tokenEndpoint:"https://appleid.apple.com/auth/token"},email:{authorizationEndpoint:"",tokenEndpoint:""}},DriveAuthRequest:v,DriveDiscovery:{dropbox:{authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",tokenEndpoint:"https://www.dropbox.com/oauth2/token"},yandex:{authorizationEndpoint:"https://oauth.yandex.com/authorize",tokenEndpoint:"https://oauth.yandex.com/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"},dubox:{authorizationEndpoint:"https://openapi.baidu.com/oauth/2.0/authorize",tokenEndpoint:"https://openapi.baidu.com/oauth/2.0/token"},yiyiwu:{authorizationEndpoint:"https://passportapi.115.com/open/authorize",tokenEndpoint:"https://passportapi.115.com/open/authorize"},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"}},AiProviderList:[{id:"custom",name:"Custom model",defaultEndpoint:"",modelsEndpoint:""},{id:"openai",name:"OpenAI",defaultEndpoint:"https://api.openai.com/v1",modelsEndpoint:"https://api.openai.com/v1/models"},{id:"anthropic",name:"Anthropic",defaultEndpoint:"https://api.anthropic.com/v1",modelsEndpoint:"https://api.anthropic.com/v1/models"},{id:"google",name:"Google Gemini",defaultEndpoint:"https://generativelanguage.googleapis.com/v1beta/openai",modelsEndpoint:"https://generativelanguage.googleapis.com/v1beta/openai/models"},{id:"deepseek",name:"DeepSeek",defaultEndpoint:"https://api.deepseek.com/v1",modelsEndpoint:"https://api.deepseek.com/v1/models"},{id:"mistral",name:"Mistral AI",defaultEndpoint:"https://api.mistral.ai/v1",modelsEndpoint:"https://api.mistral.ai/v1/models"},{id:"cohere",name:"Cohere",defaultEndpoint:"https://api.cohere.ai/compatibility/v1",modelsEndpoint:"https://api.cohere.ai/compatibility/v1/models"},{id:"groq",name:"Groq",defaultEndpoint:"https://api.groq.com/openai/v1",modelsEndpoint:"https://api.groq.com/openai/v1/models"},{id:"together",name:"Together AI",defaultEndpoint:"https://api.together.xyz/v1",modelsEndpoint:"https://api.together.xyz/v1/models"},{id:"fireworks",name:"Fireworks AI",defaultEndpoint:"https://api.fireworks.ai/inference/v1",modelsEndpoint:"https://api.fireworks.ai/inference/v1/models"},{id:"perplexity",name:"Perplexity",defaultEndpoint:"https://api.perplexity.ai",modelsEndpoint:"https://api.perplexity.ai/v1/models"},{id:"openrouter",name:"OpenRouter",defaultEndpoint:"https://openrouter.ai/api/v1",modelsEndpoint:"https://openrouter.ai/api/v1/models"},{id:"ai21",name:"AI21 Labs",defaultEndpoint:"https://api.ai21.com/studio/v1",modelsEndpoint:"https://api.ai21.com/studio/v1/models"},{id:"xai",name:"xAI (Grok)",defaultEndpoint:"https://api.x.ai/v1",modelsEndpoint:"https://api.x.ai/v1/models"},{id:"sambanova",name:"SambaNova",defaultEndpoint:"https://api.sambanova.ai/v1",modelsEndpoint:"https://api.sambanova.ai/v1/models"},{id:"cerebras",name:"Cerebras",defaultEndpoint:"https://api.cerebras.ai/v1",modelsEndpoint:"https://api.cerebras.ai/v1/models"},{id:"hyperbolic",name:"Hyperbolic",defaultEndpoint:"https://api.hyperbolic.xyz/v1",modelsEndpoint:"https://api.hyperbolic.xyz/v1/models"},{id:"novita",name:"Novita AI",defaultEndpoint:"https://api.novita.ai/openai",modelsEndpoint:"https://api.novita.ai/openai/models"},{id:"lepton",name:"Lepton AI",defaultEndpoint:"https://llm.lepton.run/api/v1",modelsEndpoint:"https://llm.lepton.run/api/v1/models"},{id:"deepinfra",name:"DeepInfra",defaultEndpoint:"https://api.deepinfra.com/v1/openai",modelsEndpoint:"https://api.deepinfra.com/v1/openai/models"},{id:"replicate",name:"Replicate",defaultEndpoint:"https://api.replicate.com/v1",modelsEndpoint:"https://api.replicate.com/v1/models"},{id:"zhipu",name:"Zhipu AI (智谱)",defaultEndpoint:"https://open.bigmodel.cn/api/paas/v4",modelsEndpoint:"https://open.bigmodel.cn/api/paas/v4/models"},{id:"qwen",name:"Alibaba Qwen (通义千问)",defaultEndpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1",modelsEndpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1/models"},{id:"moonshot",name:"Moonshot (月之暗面)",defaultEndpoint:"https://api.moonshot.cn/v1",modelsEndpoint:"https://api.moonshot.cn/v1/models"},{id:"baidu",name:"Baidu ERNIE (文心一言)",defaultEndpoint:"https://qianfan.baidubce.com/v2",modelsEndpoint:"https://qianfan.baidubce.com/v2/models"},{id:"doubao",name:"Volcengine Doubao (豆包)",defaultEndpoint:"https://ark.cn-beijing.volces.com/api/v3",modelsEndpoint:"https://ark.cn-beijing.volces.com/api/v3/models"},{id:"spark",name:"iFlytek Spark (讯飞星火)",defaultEndpoint:"https://spark-api-open.xf-yun.com/v1",modelsEndpoint:"https://spark-api-open.xf-yun.com/v1/models"},{id:"hunyuan",name:"Tencent Hunyuan (腾讯混元)",defaultEndpoint:"https://api.hunyuan.cloud.tencent.com/v1",modelsEndpoint:"https://api.hunyuan.cloud.tencent.com/v1/models"},{id:"minimax",name:"MiniMax",defaultEndpoint:"https://api.minimax.chat/v1",modelsEndpoint:"https://api.minimax.chat/v1/models"},{id:"baichuan",name:"Baichuan (百川)",defaultEndpoint:"https://api.baichuan-ai.com/v1",modelsEndpoint:"https://api.baichuan-ai.com/v1/models"},{id:"stepfun",name:"StepFun (阶跃星辰)",defaultEndpoint:"https://api.stepfun.com/v1",modelsEndpoint:"https://api.stepfun.com/v1/models"},{id:"lingyi",name:"Lingyiwanwu (零一万物)",defaultEndpoint:"https://api.lingyiwanwu.com/v1",modelsEndpoint:"https://api.lingyiwanwu.com/v1/models"},{id:"siliconflow",name:"SiliconFlow (硅基流动)",defaultEndpoint:"https://api.siliconflow.cn/v1",modelsEndpoint:"https://api.siliconflow.cn/v1/models"},{id:"infini",name:"Infini AI (无问芯穹)",defaultEndpoint:"https://cloud.infini-ai.com/maas/v1",modelsEndpoint:"https://cloud.infini-ai.com/maas/v1/models"},{id:"ollama",name:"Ollama (Local)",defaultEndpoint:"http://localhost:11434/v1",modelsEndpoint:"http://localhost:11434/v1/models"},{id:"lmstudio",name:"LM Studio (Local)",defaultEndpoint:"http://localhost:1234/v1",modelsEndpoint:"http://localhost:1234/v1/models"},{id:"vllm",name:"vLLM (Local)",defaultEndpoint:"http://localhost:8000/v1",modelsEndpoint:"http://localhost:8000/v1/models"},{id:"azure",name:"Azure OpenAI",defaultEndpoint:"",modelsEndpoint:""},{id:"aws_bedrock",name:"AWS Bedrock",defaultEndpoint:"",modelsEndpoint:""}],DefaultPrompts:{aiTranslate:"You are a professional translator. Translate the following text from {from} to {to}. Only return the translated text, no explanations.\n\nText: {text}",aiDict:"You are a professional dictionary assistant. Analyze the word or phrase: {word}\nProvide a comprehensive explanation including pronunciation, definitions, example sentences, and usage notes using {to} as the target language. ",aiAssistance:"You are a helpful reading assistant. The user is reading a book. Here is the context:\n{text}\n\nAnswer the user's question concisely and helpfully, and reply with the same language."},SpeechList:[{label:"English",code:"en",example:"To be, or not to be, that is the question."},{label:"Simplified Chinese",code:"zh",example:"千里之行,始于足下。"},{label:"Japanese",code:"ja",example:"猿も木から落ちる。"},{label:"Korean",code:"ko",example:"가는 날이 장날이다."},{label:"French",code:"fr",example:"Liberté, égalité, fraternité."},{label:"German",code:"de",example:"Der Weg ist das Ziel."},{label:"Spanish",code:"es",example:"La vida es un sueño."},{label:"Italian",code:"it",example:"Dolce far niente."},{label:"Russian",code:"ru",example:"Век живи, век учись."},{label:"Portuguese",code:"pt",example:"Saudade é um sentimento profundo."},{label:"Hindi",code:"hi",example:"सपने वो नहीं जो हम सोते वक्त देखते हैं।"},{label:"Afrikaans",code:"af",example:"Die lewe is 'n geskenk."},{label:"Amharic",code:"am",example:"ዕውቀት ብርሃን ነው።"},{label:"Arabic",code:"ar",example:"العلم نور والجهل ظلام."},{label:"Azerbaijani",code:"az",example:"Elm işıqdır, cəhalət zülmət."},{label:"Bulgarian",code:"bg",example:"Знанието е сила."},{label:"Bengali",code:"bn",example:"জ্ঞানই শক্তি।"},{label:"Bosnian",code:"bs",example:"Znanje je moć."},{label:"Catalan",code:"ca",example:"El saber no ocupa lloc."},{label:"Czech",code:"cs",example:"Bez práce nejsou koláče."},{label:"Welsh",code:"cy",example:"Nid aur popeth melyn."},{label:"Danish",code:"da",example:"Lykken er ikke et sted, men en retning."},{label:"Greek",code:"el",example:"Η γνώση είναι δύναμη."},{label:"Estonian",code:"et",example:"Teadmine on jõud."},{label:"Basque",code:"eu",example:"Jakitea boterea da."},{label:"Persian",code:"fa",example:"دانش قدرت است."},{label:"Finnish",code:"fi",example:"Tieto on valtaa."},{label:"Filipino",code:"fil",example:"Ang kaalaman ay kapangyarihan."},{label:"Irish",code:"ga",example:"Is fearr Gaeilge briste ná Béarla cliste."},{label:"Galician",code:"gl",example:"O saber non ocupa lugar."},{label:"Gujarati",code:"gu",example:"જ્ઞાન શક્તિ છે."},{label:"Hebrew",code:"he",example:"ידע הוא כוח."},{label:"Croatian",code:"hr",example:"Znanje je moć."},{label:"Hungarian",code:"hu",example:"A tudás hatalom."},{label:"Armenian",code:"hy",example:"Գիտելիքը ուժ է."},{label:"Indonesian",code:"id",example:"Pengetahuan adalah kekuatan."},{label:"Icelandic",code:"is",example:"Þekking er máttur."},{label:"Inuktitut",code:"iu",example:"ᐃᓕᓐᓂᐊᕐᓂᖅ ᐱᒻᒪᕆᐅᕗᖅ."},{label:"Javanese",code:"jv",example:"Ilmu iku kelakone kanthi laku."},{label:"Georgian",code:"ka",example:"ცოდნა ძალაა."},{label:"Kazakh",code:"kk",example:"Білім — күш."},{label:"Khmer",code:"km",example:"ចំណេះដឹងគឺជាអំណាច។"},{label:"Kannada",code:"kn",example:"ಜ್ಞಾನವೇ ಶಕ್ತಿ."},{label:"Lao",code:"lo",example:"ຄວາມຮູ້ຄືພະລັງ."},{label:"Lithuanian",code:"lt",example:"Žinios yra jėga."},{label:"Latvian",code:"lv",example:"Zināšanas ir spēks."},{label:"Macedonian",code:"mk",example:"Знаењето е моќ."},{label:"Malayalam",code:"ml",example:"അറിവ് ശക്തിയാണ്."},{label:"Mongolian",code:"mn",example:"Мэдлэг бол хүч."},{label:"Marathi",code:"mr",example:"ज्ञान हीच शक्ती आहे."},{label:"Malay",code:"ms",example:"Ilmu itu cahaya."},{label:"Maltese",code:"mt",example:"L-għarfien huwa l-poter."},{label:"Burmese",code:"my",example:"ဗဟုသုတသည် အားဖြစ်သည်။"},{label:"Norwegian",code:"nb",example:"Kunnskap er makt."},{label:"Nepali",code:"ne",example:"ज्ञान नै शक्ति हो।"},{label:"Dutch",code:"nl",example:"Kennis is macht."},{label:"Odia",code:"or",example:"ଜ୍ଞାନ ହିଁ ଶକ୍ତି।"},{label:"Punjabi",code:"pa",example:"ਗਿਆਨ ਹੀ ਸ਼ਕਤੀ ਹੈ।"},{label:"Polish",code:"pl",example:"Wiedza to potęga."},{label:"Pashto",code:"ps",example:"د پوهې ډیوه روښانه ده."},{label:"Romanian",code:"ro",example:"Cartea este o comoară."},{label:"Sinhala",code:"si",example:"දැනුම බලයකි."},{label:"Slovak",code:"sk",example:"Vedomosti sú sila."},{label:"Slovenian",code:"sl",example:"Znanje je moč."},{label:"Somali",code:"so",example:"Aqoontu waa iftiin."},{label:"Albanian",code:"sq",example:"Dija është fuqi."},{label:"Serbian",code:"sr",example:"Знање је моћ."},{label:"Sundanese",code:"su",example:"Élmu éta cahaya."},{label:"Swedish",code:"sv",example:"Kunskap är makt."},{label:"Swahili",code:"sw",example:"Maarifa ni nguvu."},{label:"Tamil",code:"ta",example:"அறிவே ஆற்றல்."},{label:"Telugu",code:"te",example:"జ్ఞానమే శక్తి."},{label:"Thai",code:"th",example:"ความรู้คือพลัง."},{label:"Turkish",code:"tr",example:"Bilgi güçtür."},{label:"Ukrainian",code:"uk",example:"Знання — сила."},{label:"Urdu",code:"ur",example:"علم ہی طاقت ہے۔"},{label:"Uzbek",code:"uz",example:"Bilim – kuch."},{label:"Vietnamese",code:"vi",example:"Học vấn là sức mạnh."},{label:"Wu Chinese",code:"wuu",example:"学问是力量。"},{label:"Cantonese",code:"yue",example:"知識就係力量。"},{label:"Zulu",code:"zu",example:"Ulwazi lungamandla."}]};class S{constructor(e){this.config=e,this.driveId="",this.taskQueue=new f(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)))}}))}getDriveId(){return a(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const t=this.config.access_token,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=this.config.access_token,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=this.config.access_token,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.filter((e=>!e.punish_flag||2!==e.punish_flag))||[];o=o.concat(c),s=t.data.next_marker,a=!!s&&100===c.length}return[...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=this.config.access_token,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=this.config.access_token,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){}}))}getAuthUrl(e){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:y.adriveClientId,redirect_uri:e,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class k extends S{constructor(e){super(e)}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=this.config.access_token,o=yield this.getDriveId(),s=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1),c=yield this.getFolderIdByPath(this.baseFolder+"/"+s),d=yield t.arrayBuffer(),u=d.byteLength,l=yield crypto.subtle.digest("SHA-1",d),h=Array.from(new Uint8Array(l)).map((e=>e.toString(16).padStart(2,"0"))).join(""),p=function(e){function t(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function r(e,r,n,i,o,s){return t((a=t(t(r,e),t(i,s)))<<(c=o)|a>>>32-c,n);var a,c}function n(e,t,n,i,o,s,a){return r(t&n|~t&i,e,t,o,s,a)}function i(e,t,n,i,o,s,a){return r(t&i|n&~i,e,t,o,s,a)}function o(e,t,n,i,o,s,a){return r(t^n^i,e,t,o,s,a)}function s(e,t,n,i,o,s,a){return r(n^(t|~i),e,t,o,s,a)}const a=function(e){const t=e.length,r=1+(t+8>>6),n=new Array(16*r).fill(0);for(let r=0;r>2]|=e.charCodeAt(r)<>2]|=128<{let t="";for(let r=0;r<4;r++)t+=("0"+(e>>8*r&255).toString(16)).slice(-2);return t})).join("")}(i),f=Number(BigInt("0x"+p.slice(0,16))%BigInt(u||1)),g=new Uint8Array(d.slice(f,Math.min(f+8,u))),m=btoa(String.fromCharCode(...g)),y=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",size:u,content_hash:h,content_hash_name:"sha1",proof_code:m,proof_version:"v1",part_info_list:[{part_number:1}]},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),{file_id:b,upload_id:v,rapid_upload:w,part_info_list:S}=y.data;if(w)return console.info("阿里云盘秒传成功"),void n(!0);yield e.put(S[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:b,upload_id:v},{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=this.config.access_token,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 E{constructor(e){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)))}}))}getFolderIdByPath(t){return a(this,void 0,void 0,(function*(){if(""==t)return"0";const r=this.config.access_token,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=this.config.access_token;let n=this.baseFolder+"/"+t;for(;n.startsWith("/");)n=n.substring(1);let i=yield this.getFolderIdByPath(n),o=[],s=0,a=!0;const c=1e3;for(;a;){const t=yield e.get(`https://api.box.com/2.0/folders/${i}/items`,{params:{limit:c,offset:s},headers:{Authorization:`Bearer ${r}`}}),n=t.data.entries||[];o=o.concat(n),s+=n.length,a=n.length===c&&t.data.total_count>s}return[...new Set(o.map((e=>({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=this.config.access_token,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}}))}getAuthUrl(e){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:y.boxClientId,redirect_uri:e,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class x extends E{constructor(e){super(e)}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=this.config.access_token,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 d=new File([t],o,{lastModified:(new Date).getTime(),type:t.type});const u=new FormData;u.append("file",d),u.append("parent_id",a);const l=yield e.post("https://upload.box.com/api/2.0/files/content",u,{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=this.config.access_token,n=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1);let o=this.baseFolder+"/"+n;for(;o.startsWith("/");)o=o.substring(1);const s=yield this.getFolderIdByPath(o);if(!s)return console.error("Folder not found"),!0;const a=`https://api.box.com/2.0/folders/${s}/items?fields=id,name&type=file&limit=1000`,c=(yield e.get(a,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));if(!c)return console.error("File not found:",i),!0;const d=yield e({url:`https://api.box.com/2.0/files/${c.id}/content`,method:"get",headers:{Authorization:`Bearer ${r}`},responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return d.status>=300?(console.error("Error occurred during file download:",d),!1):d.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class A{constructor(e){this.config=e,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=this.config.access_token;let n=[],i=!0,o=null;for(;i;){let s;s=o?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:o},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t,limit:2e3},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});const a=s.data.entries||[];n=n.concat(a),i=s.data.has_more,o=s.data.cursor}return[...new Set(n.map((e=>({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=this.config.access_token;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}}))}getAuthUrl(e){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${y.dropboxClientId}&redirect_uri=${e}`}}class C extends A{constructor(e){super(e)}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=this.config.access_token;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=this.config.access_token,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){this.folderExistsCache=new Set,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)))}}))}listFiles(e){return a(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){var r,n;return a(this,void 0,void 0,(function*(){try{const i=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let o=[],s=0;const a=1e3;let c=!0;for(;c;){const d=yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",limit:a,offset:s,fields:"_embedded.items.name,_embedded.items.size,_embedded.items.type,_embedded.items.modified,_embedded.total"}}),u=(null===(r=d.data._embedded)||void 0===r?void 0:r.items)||[];o=o.concat(u);const l=(null===(n=d.data._embedded)||void 0===n?void 0:n.total)||0;s+=u.length,c=s({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.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=this.config.access_token;for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const n=yield e.delete("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${r}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",permanently:!1}});return 202===n.status||204===n.status}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(t){var r,n;return a(this,void 0,void 0,(function*(){try{const i=this.config.access_token,o=t.split("/").filter((e=>e.length>0));let s="";for(const t of o)if(s+="/"+t,!this.folderExistsCache.has(s))try{yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:s}}),this.folderExistsCache.add(s)}catch(t){if(404!==(null===(r=t.response)||void 0===r?void 0:r.status))return console.error("Error checking directory:",t),!1;try{yield e.put(`https://cloud-api.yandex.net/v1/disk/resources?path=${encodeURIComponent(s)}`,null,{headers:{Authorization:`OAuth ${i}`}}),this.folderExistsCache.add(s)}catch(e){if(409!==(null===(n=e.response)||void 0===n?void 0:n.status))return console.error("Error creating directory:",e),!1;this.folderExistsCache.add(s)}}return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}getAuthUrl(e){return`https://oauth.yandex.com/authorize?response_type=code&client_id=${y.yandexClientId}&redirect_uri=${e}&force_confirm=true`}}class R extends T{constructor(e){super(e)}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=this.config.access_token;let i=this.baseFolder+"/"+r;for(;i.startsWith("/");)i=i.substring(1);const o=i.substring(0,i.lastIndexOf("/"));if(o){if(!(yield this.ensureDirectoryExists(o)))return console.error("Failed to create directory:",o),!1}const s=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/upload",{headers:{Authorization:`OAuth ${n}`,"Content-Type":"application/json"},params:{path:`/${i}`,overwrite:!0}});if(200!==s.status)return console.error("Error getting upload URL:",s),!1;const a=s.data.href;let c=r.split("/").pop()||"",d=new File([t],c,{lastModified:(new Date).getTime(),type:t.type});const u=yield e.put(a,d,{headers:{"Content-Type":t.type||"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file upload:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(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=this.config.access_token;let n=this.baseFolder+"/"+t;for(;n.startsWith("/");)n=n.substring(1);const i=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/download",{headers:{Authorization:`OAuth ${r}`,"Content-Type":"application/json"},params:{path:`/${n}`}});if(200!==i.status)return console.error("Error getting download URL:",i),!1;const o=i.data.href,s=yield e({url:o,method:"get",maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer",onDownloadProgress:e=>{this.taskQueue.setDownloadedSize(e.loaded)}});return s.status>=300?(console.error("Error occurred during file download:",s),!1):s.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class O{constructor(e){this.isExp=!1,this.folderIdCache=new Map,this.config=e,this.taskQueue=new f(3),this.isExp=this.config.isExp||!1,this.baseFolder="KoodoReader"}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=this.config.access_token,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=this.config.access_token;if(""===t)return"root";if(this.folderIdCache.has(t))return this.folderIdCache.get(t);const n=t.split("/").filter((e=>""!==e.trim()));let i="root",o="";for(const t of n){if(o=o?o+"/"+t:t,this.folderIdCache.has(o)){i=this.folderIdCache.get(o);continue}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}}this.folderIdCache.set(o,n),i=n}return i}))}getFolderId(t,r){return a(this,void 0,void 0,(function*(){const n=this.config.access_token,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=this.config.access_token;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[...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("/").pop()||"",n=t.split("/").slice(0,-1).join("/"),i=yield this.checkFolder(n),o=this.config.access_token,s=yield this.getFileId(r,i);if(""===s)return console.error("File not found:",r),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${s}`,{headers:{Authorization:`Bearer ${o}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}getAuthUrl(e){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${e}&prompt=consent&response_type=code&client_id=${y.googleClientId}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class P extends O{constructor(e){super(e)}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=this.config.access_token;let i=r.split("/").pop()||"",o=new File([t],i,{lastModified:(new Date).getTime(),type:t.type}),s=r.split(".").pop(),a=c(s||""),d=r.split("/")[0],u=yield this.checkFolder(d),l=yield this.getFileId(i||"",u);const h={mimeType:a,name:i,parents:[u]},p=l?`https://www.googleapis.com/upload/drive/v3/files/${l}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:l?"PATCH":"POST",url:p,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(f,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=this.config.access_token;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 I{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=2){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,userAgent:"KoodoReader/1.0"}).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 _ extends I{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),d=r.from(c),u=n.children.find((e=>e.name===o&&!e.directory));return u&&(yield u.delete()),yield n.upload({name:o,size:s.size},d).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 M{constructor(e){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,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=this.config.access_token;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[...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=this.config.access_token;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}}))}getAuthUrl(e){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=${e}`}}class N extends M{constructor(e){super(e)}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=this.config.access_token;let i=r.split("/").pop()||"",o=new File([t],i,{lastModified:(new Date).getTime(),type:t.type}),s=this.baseFolder+"/"+r;for(;s.startsWith("/");)s=s.substring(1);const a=this.baseUrl+":/"+s+":/createUploadSession",c=yield e.post(a,null,{headers:{Authorization:"Bearer "+n,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0});let d=o.size;const u=o.type,l=c.data.uploadUrl,h=yield e.put(l,o,{headers:{"Content-Type":u,"Content-Range":`bytes 0-${d-1}/${d}`},maxContentLength:1/0,maxBodyLength:1/0});return!(h.status>=300)||(console.error("Error occurred during file download:",h),!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=this.config.access_token;let n=this.baseFolder+"/"+t;for(;n.startsWith("/");)n=n.substring(1);const i=`${this.baseUrl}:/${n}:/content`,o=yield e.get(i,{responseType:"arraybuffer",headers:{Authorization:"Bearer "+r},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}}))))))}))}}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([])}))}))}getAuthUrl(){return""}}class F{constructor(e){this.baseUrl="https://api.pcloud.com",this.config=e,this.taskQueue=new f(3),this.baseUrl="2"===e.region?"https://eapi.pcloud.com":"https://api.pcloud.com"}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)))}}))}checkFolderExists(t,r){return a(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/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(`${this.baseUrl}/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=this.config.refresh_token,n=yield e.get(`${this.baseUrl}/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=this.config.refresh_token,n=yield e.get(`${this.baseUrl}/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}}))}getAuthUrl(e){return`https://my.pcloud.com/oauth2/authorize?client_id=${y.pcloudClientId}&response_type=code&redirect_uri=${e}`}}class U extends F{constructor(e){super(e)}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=this.config.refresh_token,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(`${this.baseUrl}/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=this.config.refresh_token,n=yield e.get(`${this.baseUrl}/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 L=e=>{let t=e.httpHandler;return{setHttpHandler(e){t=e},httpHandler:()=>t,updateHttpClientConfig(e,r){t.updateHttpClientConfig(e,r)},httpHandlerConfigs:()=>t.httpHandlerConfigs()}};var D,B,z,j,q;!function(e){e.HEADER="header",e.QUERY="query"}(D||(D={})),function(e){e.HEADER="header",e.QUERY="query"}(B||(B={})),function(e){e.HTTP="http",e.HTTPS="https"}(z||(z={})),function(e){e.MD5="md5",e.CRC32="crc32",e.CRC32C="crc32c",e.SHA1="sha1",e.SHA256="sha256"}(j||(j={})),function(e){e[e.HEADER=0]="HEADER",e[e.TRAILER=1]="TRAILER"}(q||(q={}));const H="__smithy_context";var W,K;!function(e){e.PROFILE="profile",e.SSO_SESSION="sso-session",e.SERVICES="services"}(W||(W={})),function(e){e.HTTP_0_9="http/0.9",e.HTTP_1_0="http/1.0",e.TDS_8_0="tds/8.0"}(K||(K={}));class V{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 V({...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 V.clone(this)}}class Q{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 G={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0},J=e=>({applyToStack:t=>{t.add(function(e){return t=>async r=>{const{request:n}=r;return V.isInstance(n)&&n.body&&"node"===e.runtime&&"FetchHttpHandler"!==e.requestHandler?.constructor?.name&&(n.headers={...n.headers,Expect:"100-continue"}),t({...r,request:n})}}(e),G)}}),Y="WHEN_SUPPORTED",X=Y,Z=Y;var ee,te;!function(e){e.MD5="MD5",e.CRC32="CRC32",e.CRC32C="CRC32C",e.SHA1="SHA1",e.SHA256="SHA256"}(ee||(ee={})),function(e){e.HEADER="header",e.TRAILER="trailer"}(te||(te={}));const re=ee.MD5,ne=ee.CRC32;var ie;function oe(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"}(ie||(ie={}));const se=e=>Q.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,ae=e=>new Date(Date.now()+e),ce=(e,t)=>{const r=Date.parse(e);return((e,t)=>Math.abs(ae(t).getTime()-e)>=3e5)(r,t)?r-Date.now():t},de=(e,t)=>{if(!t)throw new Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},ue=async e=>{const t=de("context",e.context),r=de("config",e.config),n=t.endpointV2?.properties?.authSchemes?.[0],i=de("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 le{async sign(e,t,r){if(!V.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const n=await ue(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:ae(i.systemClockOffset),signingRegion:s,signingService:a})}errorHandler(e){return t=>{const r=t.ServerTime??se(t.$response);if(r){const n=de("config",e.config),i=n.systemClockOffset;n.systemClockOffset=ce(r,n.systemClockOffset);n.systemClockOffset!==i&&t.$metadata&&(t.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const r=se(e);if(r){const e=de("config",t.config);e.systemClockOffset=ce(r,e.systemClockOffset)}}}class he extends le{async sign(e,t,r){if(!V.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 ue(r),c=(await(n.sigv4aSigningRegionSet?.())??s??[o]).join(",");return await i.sign(e,{signingDate:ae(n.systemClockOffset),signingRegion:c,signingService:a})}}const pe=e=>e[H]||(e[H]={}),fe=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t};const ge=(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=pe(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:d={},signingProperties:u={}}=r.propertiesExtractor?.(e,n)||{};r.identityProperties=Object.assign(r.identityProperties||{},d),r.signingProperties=Object.assign(r.signingProperties||{},u),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)},me={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},ye={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},be={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function ve(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),ye),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),be)}}}const we=e=>e=>{throw e},Se=(e,t)=>{},ke={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},Ee=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{if(!V.isInstance(r.request))return e(r);const n=pe(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||we)(i));return(s.successHandler||Se)(a.response,i),a}),ke)}}),xe=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t},Ae={},Ce=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);Ae[r]=e,Ce[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;Ae[r]=n,Ce[n]=r}for(let e=0;e<10;e++){Ae[e.toString(10)]=e+52;const t=e.toString(10),r=e+52;Ae[t]=r,Ce[r]=t}Ae["+"]=62,Ce[62]="+",Ae["/"]=63,Ce[63]="/";const Te=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)},Re=e=>(new TextEncoder).encode(e),Oe=e=>"string"==typeof e?Re(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e),Pe=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 Ie(e){let t;t="string"==typeof e?Re(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 _e extends Uint8Array{static fromString(e,t="utf-8"){if("string"==typeof e)return function(e,t){return"base64"===t?_e.mutate(Te(e)):_e.mutate(Re(e))}(e,t);throw new Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,_e.prototype),e}transformToString(e="utf-8"){return function(e,t="utf-8"){return"base64"===t?Ie(e):Pe(e)}(this,e)}}const Me=(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,d=e.getReader();return new ReadableStream({async pull(e){const{value:t,done:i}=await d.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`)}})},Ne=e=>encodeURIComponent(e).replace(/[!'()*]/g,$e),$e=e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`;function Fe(e,t){return new Request(e,t)}function Ue(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 Le={supported:void 0};class De{static create(e){return"function"==typeof e?.handle?e:new De(e)}constructor(e){"function"==typeof e?this.configProvider=e().then((e=>e||{})):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),void 0===Le.supported&&(Le.supported=Boolean("undefined"!=typeof Request&&"keepalive"in Fe("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=Ne(r),Array.isArray(n))for(let e=0,i=n.length;e{};const f=Fe(u,h),g=[fetch(f).then((e=>{const t=e.headers,r={};for(const e of t.entries())r[e[0]]=e[1];return null!=e.body?{response:new Q({headers:r,reason:e.statusText,statusCode:e.status,body:e.body})}:e.blob().then((t=>({response:new Q({headers:r,reason:e.statusText,statusCode:e.status,body:t})})))})),Ue(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}),p=()=>e.removeEventListener("abort",n)}else t.onabort=n}))),Promise.race(g).finally(p)}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then((r=>(r[e]=t,r)))}httpHandlerConfigs(){return this.config??{}}}const Be=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 ze={},je={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();1===t.length&&(t=`0${t}`),ze[e]=t,je[t]=e}function qe(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),Ke="The stream has already been transformed.",Ve=e=>{if(!Qe(e)&&!We(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(Ke);return t=!0,await Be(e)};return Object.assign(e,{transformToByteArray:r,transformToString:async e=>{const t=await r();if("base64"===e)return Ie(t);if("hex"===e)return He(t);if(void 0===e||"utf8"===e||"utf-8"===e)return Pe(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(Ke);if(t=!0,Qe(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(We(e))return e;throw new Error(`Cannot transform payload to web stream, got ${e}`)}})},Qe=e=>"function"==typeof Blob&&e instanceof Blob;const Ge="function"==typeof ReadableStream?ReadableStream:function(){};class Je extends Ge{}const Ye=({expectedChecksum:e,checksum:t,source:r,checksumSourceLocation:n,base64Encoder:i})=>{if(!We(r))throw new Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);const o=i??Ie;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,Je.prototype),a},Xe=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return _e.mutate(e);if(!e)return _e.mutate(new Uint8Array);const r=t.streamCollector(e);return _e.mutate(await r)};function Ze(e){return encodeURIComponent(e).replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function et(e,t){return new tt(e,t)}class tt{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 V({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=>Ze(e))).join("/"):Ze(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 rt{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 nt=(it=3e5,e=>ot(e)&&e.expiration.getTime()-Date.now()void 0!==e.expiration,st="X-Amz-Date",at="X-Amz-Signature",ct="X-Amz-Security-Token",dt="authorization",ut=st.toLowerCase(),lt=[dt,ut,"date"],ht=at.toLowerCase(),pt="x-amz-content-sha256",ft=ct.toLowerCase(),gt={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},mt=/^proxy-/,yt=/^sec-/,bt="AWS4-HMAC-SHA256",vt="AWS4-HMAC-SHA256-PAYLOAD",wt="aws4_request",St={},kt=[],Et=(e,t,r)=>`${e}/${t}/${r}/${wt}`,xt=(e,t,r)=>{const n=new e(t);return n.update(Oe(r)),n.digest()},At=({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 gt||t?.has(o)||mt.test(o)||yt.test(o))&&(!r||r&&!r.has(o))||(n[o]=e[i].trim().replace(/\s+/g," "))}return n},Ct=e=>"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(e),Tt=async({headers:e,body:t},r)=>{for(const t of Object.keys(e))if(t.toLowerCase()===pt)return e[t];if(null==t)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if("string"==typeof t||ArrayBuffer.isView(t)||Ct(t)){const e=new r;return e.update(Oe(t)),He(await e.digest())}return"UNSIGNED-PAYLOAD"};class Rt{format(e){const t=[];for(const r of Object.keys(e)){const n=Re(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=Re(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 d=new Uint8Array(9);return d[0]=8,d.set(It.fromNumber(e.value.valueOf()).bytes,1),d;case"uuid":if(!Pt.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const u=new Uint8Array(17);return u[0]=9,u.set(qe(e.value.replace(/\-/g,"")),1),u}}}var Ot;!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"}(Ot||(Ot={}));const Pt=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class It{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&&_t(t),new It(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&_t(e),parseInt(He(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function _t(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}const Mt=e=>{e=V.clone(e);for(const t of Object.keys(e.headers))lt.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e},Nt=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 Rt,this.service=n,this.sha256=i,this.uriEscapePath=o,this.applyChecksum="boolean"!=typeof e||e,this.regionProvider=fe(r),this.credentialProvider=fe(t)}async presign(e,t={}){const{signingDate:r=new Date,expiresIn:n=3600,unsignableHeaders:i,unhoistableHeaders:o,signableHeaders:s,hoistableHeaders:a,signingRegion:c,signingService:d}=t,u=await this.credentialProvider();this.validateResolvedCredentials(u);const l=c??await this.regionProvider(),{longDate:h,shortDate:p}=Ft(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 f=Et(p,l,d??this.service),g=((e,t={})=>{const{headers:r,query:n={}}=V.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}})(Mt(e),{unhoistableHeaders:o,hoistableHeaders:a});u.sessionToken&&(g.query[ct]=u.sessionToken),g.query["X-Amz-Algorithm"]=bt,g.query["X-Amz-Credential"]=`${u.accessKeyId}/${f}`,g.query[st]=h,g.query["X-Amz-Expires"]=n.toString(10);const m=At(g,i,s);return g.query["X-Amz-SignedHeaders"]=Ut(m),g.query[at]=await this.getSignature(h,f,this.getSigningKey(u,l,p,d),this.createCanonicalRequest(g,m,await Tt(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}=Ft(r),d=Et(a,s,o??this.service),u=await Tt({headers:{},body:t},this.sha256),l=new this.sha256;l.update(e);const h=He(await l.digest()),p=[vt,c,d,n,h,u].join("\n");return this.signString(p,{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}=Ft(t),a=new this.sha256(await this.getSigningKey(i,o,s,n));return a.update(Oe(e)),He(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=Mt(e),{longDate:d,shortDate:u}=Ft(t),l=Et(u,a,o??this.service);c.headers[ut]=d,s.sessionToken&&(c.headers[ft]=s.sessionToken);const h=await Tt(c,this.sha256);!((e,t)=>{e=e.toLowerCase();for(const r of Object.keys(t))if(e===r.toLowerCase())return!0;return!1})(pt,c.headers)&&this.applyChecksum&&(c.headers[pt]=h);const p=At(c,n,r),f=await this.getSignature(d,l,this.getSigningKey(s,a,u,o),this.createCanonicalRequest(c,p,h));return c.headers[dt]=`${bt} Credential=${s.accessKeyId}/${l}, SignedHeaders=${Ut(p)}, Signature=${f}`,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()===ht)continue;const i=Ne(n);t.push(i);const o=e[n];"string"==typeof o?r[i]=`${i}=${Ne(o)}`:Array.isArray(o)&&(r[i]=o.slice(0).reduce(((e,t)=>e.concat([`${i}=${Ne(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(Oe(r));const i=await n.digest();return`${bt}\n${e}\n${t}\n${He(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 Ne(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(Oe(i)),He(await o.digest())}getSigningKey(e,t,r,n){return(async(e,t,r,n,i)=>{const o=`${r}:${n}:${i}:${He(await xt(e,t.secretAccessKey,t.accessKeyId))}:${t.sessionToken}`;if(o in St)return St[o];for(kt.push(o);kt.length>50;)delete St[kt.shift()];let s=`AWS4${t.secretAccessKey}`;for(const t of[r,n,i,wt])s=await xt(e,s,t);return St[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 Ft=e=>{const t=(r=e,Nt(r).toISOString().replace(/\.\d{3}Z$/,"Z")).replace(/[\-:]/g,"");var r;return{longDate:t,shortDate:t.slice(0,8)}},Ut=e=>Object.keys(e).sort().join(";"),Lt=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,nt,ot)),t||(t=e.credentialDefaultProvider?xe(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?xe(e.signer):e.regionInfoProvider?()=>xe(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 xe(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}},Dt=(e,t)=>{const r=[];if(e&&r.push(e),t)for(const e of t)r.push(e);return r},Bt=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,zt=()=>{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 Dt(t.name,t.aliases))s[e]=t;n.push(t)})),t.forEach((e=>{const t={...e,before:[],after:[]};for(const e of Dt(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 ${Bt(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)=>jt[t.step]-jt[e.step]||qt[t.priority||"normal"]-qt[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=Dt(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${Bt(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(`"${Bt(n.name,n.aliases)}" middleware with ${n.priority} priority in ${n.step} step cannot be overridden by "${Bt(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=Dt(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${Bt(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(`"${Bt(n.name,n.aliases)}" middleware ${n.relation} "${n.toMiddleware}" middleware cannot be overridden by "${Bt(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(zt()),use:e=>{e.applyToStack(a)},remove:r=>"string"==typeof r?(r=>{let i=!1;const o=e=>{const t=Dt(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 Dt(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=Dt(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(zt());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 Bt(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},jt={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},qt={high:3,normal:2,low:1};class Ht{constructor(e){this.config=e,this.middlewareStack=zt()}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 Wt{constructor(){this.middlewareStack=zt()}static classBuilder(){return new Kt}resolveMiddlewareWithContext(e,t,r,{middlewareFn:n,clientName:i,commandName:o,inputFilterSensitiveLog:s,outputFilterSensitiveLog:a,smithyContext:c,additionalContext:d,CommandCtor:u}){for(const i of n.bind(this)(u,e,t,r))this.middlewareStack.use(i);const l=e.concat(this.middlewareStack),{logger:h}=t,p={logger:h,clientName:i,commandName:o,inputFilterSensitiveLog:s,outputFilterSensitiveLog:a,[H]:{commandInstance:this,...c},...d},{requestHandler:f}=t;return l.resolve((e=>f.handle(e.request,r||{})),p)}}class Kt{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 Wt{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 Vt="***SensitiveInformation***",Qt=e=>{switch(e){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${e}"`)}},Gt=Math.ceil(2**127*(2-2**-23)),Jt=e=>{const t=(e=>{if(null!=e){if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&hr.warn(lr(`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)>Gt)throw new TypeError(`Expected 32-bit float, got ${e}`);return t},Yt=e=>{if(null!=e){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw new TypeError(`Expected integer, got ${typeof e}: ${e}`)}},Xt=e=>tr(e,32),Zt=e=>tr(e,16),er=e=>tr(e,8),tr=(e,t)=>{const r=Yt(e);if(void 0!==r&&rr(r,t)!==r)throw new TypeError(`Expected ${t}-bit integer, got ${e}`);return r},rr=(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]}},nr=(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},ir=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}`)},or=e=>{if(null!=e){if("string"==typeof e)return e;if(["boolean","number","bigint"].includes(typeof e))return hr.warn(lr(`Expected string, got ${typeof e}: ${e}`)),String(e);throw new TypeError(`Expected string, got ${typeof e}: ${e}`)}},sr=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,ar=e=>{const t=e.match(sr);if(null===t||t[0].length!==e.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(e)},cr=e=>Yt("string"==typeof e?ar(e):e),dr=e=>Xt("string"==typeof e?ar(e):e),ur=e=>Zt("string"==typeof e?ar(e):e),lr=e=>String(new TypeError(e).stack||e).split("\n").slice(0,5).filter((e=>!e.includes("stackTraceWarning"))).join("\n"),hr={warn:console.warn},pr=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],fr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function gr(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}`,d=s<10?`0${s}`:`${s}`,u=a<10?`0${a}`:`${a}`;return`${pr[n]}, ${i<10?`0${i}`:`${i}`} ${fr[r]} ${t} ${c}:${d}:${u} GMT`}const mr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),yr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-3339 date-times must be expressed as strings");const t=mr.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");const[r,n,i,o,s,a,c,d,u]=t,l=ur(_r(n)),h=Or(i,"month",1,12),p=Or(o,"day",1,31),f=kr(l,h,p,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:d});return"Z"!=u.toUpperCase()&&f.setTime(f.getTime()-Ir(u)),f},br=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$/),vr=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$/),wr=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})$/),Sr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-7231 date-times must be expressed as strings");let t=br.exec(e);if(t){const[e,r,n,i,o,s,a,c]=t;return kr(ur(_r(i)),Ar(n),Or(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c})}if(t=vr.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return xr(kr(Er(i),Ar(n),Or(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c}))}if(t=wr.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return kr(ur(_r(c)),Ar(r),Or(n.trimLeft(),"day",1,31),{hours:i,minutes:o,seconds:s,fractionalMilliseconds:a})}throw new TypeError("Invalid RFC-7231 date-time value")},kr=(e,t,r,n)=>{const i=t-1;return Tr(e,i,r),new Date(Date.UTC(e,i,r,Or(n.hours,"hour",0,23),Or(n.minutes,"minute",0,59),Or(n.seconds,"seconds",0,60),Pr(n.fractionalMilliseconds)))},Er=e=>{const t=(new Date).getUTCFullYear(),r=100*Math.floor(t/100)+ur(_r(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,Ar=e=>{const t=fr.indexOf(e);if(t<0)throw new TypeError(`Invalid month: ${e}`);return t+1},Cr=[31,28,31,30,31,30,31,31,30,31,30,31],Tr=(e,t,r)=>{let n=Cr[t];if(1===t&&Rr(e)&&(n=29),r>n)throw new TypeError(`Invalid day for ${fr[t]} in ${e}: ${r}`)},Rr=e=>e%4==0&&(e%100!=0||e%400==0),Or=(e,t,r,n)=>{const i=(e=>er("string"==typeof e?ar(e):e))(_r(e));if(in)throw new TypeError(`${t} must be between ${r} and ${n}, inclusive`);return i},Pr=e=>null==e?0:1e3*(e=>Jt("string"==typeof e?ar(e):e))("0."+e),Ir=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},_r=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"]}),Fr=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{}}},Ur=e=>{const t=[];for(const r in j){const n=j[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}}},Lr=e=>{const t={};return e.checksumAlgorithms().forEach((e=>{t[e.algorithmId()]=e.checksumConstructor()})),t},Dr=e=>{let t=e.retryStrategy;return{setRetryStrategy(e){t=e},retryStrategy:()=>t}},Br=e=>{const t={};return t.retryStrategy=e.retryStrategy(),t},zr=e=>({...Ur(e),...Dr(e)}),jr=e=>({...Lr(e),...Br(e)}),qr=e=>Array.isArray(e)?e:[e],Hr=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]=Hr(e[r]));return e},Wr=e=>null!=e,Kr=function(){const e=Object.getPrototypeOf(this).constructor,t=new(Function.bind.apply(String,[null,...arguments]));return Object.setPrototypeOf(t,e.prototype),t};Kr.prototype=Object.create(String.prototype,{constructor:{value:Kr,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(Kr,String);class Vr{trace(){}debug(){}info(){}warn(){}error(){}}function Qr(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,Gr(n,i,o);o=t}for(const e of Object.keys(o))Array.isArray(o[e])?Jr(n,null,o,e):n[e]=o[e];return n}const Gr=(e,t,r)=>Qr(e,Object.entries(r).reduce(((e,[r,n])=>(Array.isArray(n)?e[r]=n:e[r]="function"==typeof n?[t,n()]:[t,n],e)),{})),Jr=(e,t,r,n)=>{if(null!==t){let i=r[n];"function"==typeof i&&(i=[,i]);const[o=Yr,s=Xr,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)}},Yr=e=>null!=e,Xr=e=>e;function Zr(e){return(e.includes(",")||e.includes('"'))&&(e=`"${e.replace(/"/g,'\\"')}"`),e}function en(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var tn={},rn={};!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 gn("InvalidXml","XML declaration allowed only at the start of the document.",yn(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}}return t}function cn(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}tn.validate=function(e,t){t=Object.assign({},on,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++)d+=e[s];if(d=d.trim(),"/"===d[d.length-1]&&(d=d.substring(0,d.length-1),s--),o=d,!nn.isName(o)){let t;return t=0===d.trim().length?"Invalid space after '<'.":"Tag '"+d+"' is an invalid name.",gn("InvalidTag",t,yn(e,s))}const u=ln(e,s);if(!1===u)return gn("InvalidAttr","Attributes for '"+d+"' have open quote.",yn(e,s));let l=u.value;if(s=u.index,"/"===l[l.length-1]){const r=s-l.length;l=l.substring(0,l.length-1);const i=pn(l,t);if(!0!==i)return gn(i.err.code,i.err.msg,yn(e,r+i.err.line));n=!0}else if(c){if(!u.tagClosed)return gn("InvalidTag","Closing tag '"+d+"' doesn't have proper closing.",yn(e,s));if(l.trim().length>0)return gn("InvalidTag","Closing tag '"+d+"' can't have attributes or invalid starting.",yn(e,a));if(0===r.length)return gn("InvalidTag","Closing tag '"+d+"' has not been opened.",yn(e,a));{const t=r.pop();if(d!==t.tagName){let r=yn(e,t.tagStartPos);return gn("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+d+"'.",yn(e,a))}0==r.length&&(i=!0)}}else{const o=pn(l,t);if(!0!==o)return gn(o.err.code,o.err.msg,yn(e,s-l.length+o.err.line));if(!0===i)return gn("InvalidXml","Multiple possible root nodes found.",yn(e,s));-1!==t.unpairedTags.indexOf(d)||r.push({tagName:d,tagStartPos:a}),n=!0}for(s++;s0)||gn("InvalidXml","Invalid '"+JSON.stringify(r.map((e=>e.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):gn("InvalidXml","Start tag expected.",1)};const dn='"',un="'";function ln(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 hn=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function pn(e,t){const r=nn.getAllMatches(e,hn),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}};vn.buildOptions=function(e){return Object.assign({},wn,e)},vn.defaultOptions=wn;const Sn=rn;function kn(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&&xn(e,t))t+=7,[entityName,val,t]=kn(e,t+1),-1===val.indexOf("&")&&(r[Rn(entityName)]={regx:RegExp(`&${entityName};`,"g"),val:val});else if(i&&An(e,t))t+=8;else if(i&&Cn(e,t))t+=8;else if(i&&Tn(e,t))t+=9;else{if(!En)throw new Error("Invalid DOCTYPE");o=!0}n++,s=""}if(0!==n)throw new Error("Unclosed DOCTYPE")}return{entities:r,i:t}};const Pn=/^[-+]?0x[a-fA-F0-9]+$/,In=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,_n={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};const Mn=rn,Nn=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})}},$n=On,Fn=function(e,t={}){if(t=Object.assign({},_n,t),!e||"string"!=typeof e)return e;let r=e.trim();if(void 0!==t.skipLike&&t.skipLike.test(r))return e;if("0"===e)return 0;if(t.hex&&Pn.test(r))return function(e,t){if(parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(r,16);if(-1!==r.search(/[eE]/)){const n=r.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);if(n){if(t.leadingZeros)r=(n[1]||"")+n[3];else if("0"!==n[2]||"."!==n[3][0])return e;return t.eNotation?Number(r):e}return e}{const n=In.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]);if(!t.leadingZeros&&o.length>0&&i&&"."!==r[2])return e;if(!t.leadingZeros&&o.length>0&&!i&&"."!==r[1])return e;if(t.leadingZeros&&o===e)return 0;{const n=Number(r),a=""+n;return-1!==a.search(/[eE]/)?t.eNotation?n:e:-1!==r.indexOf(".")?"0"===a&&""===s||a===s||i&&a==="-"+s?n:e:o?s===a||i+s===a?n:e:r===a||r===i+a?n:e}}return e}};function Un(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 Jn(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?Jn(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function Dn(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 Bn=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function zn(e,t,r){if(!this.options.ignoreAttributes&&"string"==typeof e){const r=Mn.getAllMatches(e,Bn),n=r.length,i={};for(let e=0;e",o,"Closing Tag is not closed.");let s=e.substring(o+2,t).trim();if(this.options.removeNSPrefix){const e=s.indexOf(":");-1!==e&&(s=s.substr(e+1))}this.options.transformTagName&&(s=this.options.transformTagName(s)),r&&(n=this.saveTextToParentTag(n,r,i));const a=i.substring(i.lastIndexOf(".")+1);if(s&&-1!==this.options.unpairedTags.indexOf(s))throw new Error(`Unpaired tag can not be used as closing tag: `);let c=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(c=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):c=i.lastIndexOf("."),i=i.substring(0,c),r=this.tagsNodeStack.pop(),n="",o=t}else if("?"===e[o+1]){let t=Qn(e,o,!1,"?>");if(!t)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,r,i),this.options.ignoreDeclaration&&"?xml"===t.tagName||this.options.ignorePiTags);else{const e=new Nn(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=Vn(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=$n(e,o);this.docTypeEntities=t.entities,o=t.i}else if("!["===e.substr(o+1,2)){const t=Vn(e,"]]>",o,"CDATA is not closed.")-2,s=e.substring(o+9,t);n=this.saveTextToParentTag(n,r,i);let a=this.parseTextData(s,r.tagname,i,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?r.add(this.options.cdataPropName,[{[this.options.textNodeName]:s}]):r.add(this.options.textNodeName,a),o=t+2}else{let s=Qn(e,o,this.options.removeNSPrefix),a=s.tagName;const c=s.rawTagName;let d=s.tagExp,u=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(d.length>0&&d.lastIndexOf("/")===d.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),i=i.substr(0,i.length-1),d=a):d=d.substr(0,d.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 Nn(a);a!==d&&u&&(n[":@"]=this.buildAttributesMap(d,i,a)),t&&(t=this.parseTextData(t,a,i,!0,u,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),n.add(this.options.textNodeName,t),this.addChild(r,n,i)}else{if(d.length>0&&d.lastIndexOf("/")===d.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),i=i.substr(0,i.length-1),d=a):d=d.substr(0,d.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const e=new Nn(a);a!==d&&u&&(e[":@"]=this.buildAttributesMap(d,i,a)),this.addChild(r,e,i),i=i.substr(0,i.lastIndexOf("."))}else{const e=new Nn(a);this.tagsNodeStack.push(r),a!==d&&u&&(e[":@"]=this.buildAttributesMap(d,i,a)),this.addChild(r,e,i),r=e}n="",o=l}}else n+=e[o]}return t.child};function qn(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 Hn=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 Wn(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 Kn(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 Vn(e,t,r,n){const i=e.indexOf(t,r);if(-1===i)throw new Error(n);return i+t.length-1}function Qn(e,t,r,n=">"){const i=function(e,t,r=">"){let n,i="";for(let o=t;o",r,`${t} is not closed`);if(e.substring(r+2,o).trim()===t&&(i--,0===i))return{tagContent:e.substring(n,r),i:o};r=o}else if("?"===e[r+1]){r=Vn(e,"?>",r+1,"StopNode is not closed.")}else if("!--"===e.substr(r+1,3)){r=Vn(e,"--\x3e",r+3,"StopNode is not closed.")}else if("!["===e.substr(r+1,2)){r=Vn(e,"]]>",r,"StopNode is not closed.")-2}else{const n=Qn(e,r,">");if(n){(n&&n.tagName)===t&&"/"!==n.tagExp[n.tagExp.length-1]&&i++,r=n.closeIndex}}}function Jn(e,t,r){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&Fn(e,r)}return Mn.isExist(e)?e:""}var Yn=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=Un,this.parseXml=jn,this.parseTextData=Ln,this.resolveNameSpace=Dn,this.buildAttributesMap=zn,this.isItStopNode=Kn,this.replaceEntitiesValue=Hn,this.readStopNodeData=Gn,this.saveTextToParentTag=Wn,this.addChild=qn}},Xn={};function Zn(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 ei(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=ui(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 u=n;""!==u&&(u+=t.indentBy);const l=n+`<${c}${ui(a[":@"],t)}`,h=ci(a[c],t,d,u);-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 di(e){const t=Object.keys(e);for(let r=0;r0&&t.processEntities)for(let r=0;r0&&(r="\n"),ci(e,t,"",r)},fi={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 gi(e){this.options=Object.assign({},fi,e),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=bi),this.processTextOrObjNode=mi,this.options.format?(this.indentate=yi,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function mi(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 yi(e){return this.options.indentBy.repeat(e)}function bi(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}gi.prototype.build=function(e){return this.options.preserveOrder?pi(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0).val)},gi.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}},gi.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)=>Xe(e,t).then((e=>t.utf8Encoder(e))))(e,t).then((e=>{if(e.length){const t=new vi.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]),Hr(o)}return{}})),Si=async(e,t)=>{const r=await wi(e,t);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r},ki=[ee.CRC32,ee.CRC32C,ee.SHA1,ee.SHA256],Ei=[ee.SHA256,ee.SHA1,ee.CRC32,ee.CRC32C],xi=e=>e===ee.MD5?"content-md5":`x-amz-checksum-${e.toLowerCase()}`,Ai=e=>void 0!==e&&"string"!=typeof e&&!ArrayBuffer.isView(e)&&!Ct(e);function Ci(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 Ti(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 Oi(e){return e instanceof Uint8Array?e:"string"==typeof e?Ri(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}function Pi(e){return"string"==typeof e?0===e.length:0===e.byteLength}function Ii(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}function _i(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^$i[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}(),$i=_i([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 Fi(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 Ui(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^Bi[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}(),Bi=_i([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 zi=(e,t)=>({[ee.MD5]:t.md5,[ee.CRC32]:Li,[ee.CRC32C]:Mi,[ee.SHA1]:t.sha1,[ee.SHA256]:t.sha256}[e]),ji=(e,t)=>{const r=new e;return r.update(Oe(t||"")),r.digest()},qi={name:"flexibleChecksumsMiddleware",step:"build",tags:["BODY_CHECKSUM"],override:!0},Hi=(e,t)=>(r,n)=>async i=>{if(!V.isInstance(i.request))return r(i);const{request:o,input:s}=i,{body:a,headers:c}=o,{base64Encoder:d,streamHasher:u}=e,{requestChecksumRequired:l,requestAlgorithmMember:h}=t,p=((e,{requestChecksumRequired:t,requestAlgorithmMember:r},n)=>{const i=n?ne:re;if(!r||!e[r])return t?i:void 0;const o=e[r];if(!ki.includes(o))throw new Error(`The checksum algorithm "${o}" is not supported by the client. Select one of ${ki}.`);return o})(s,{requestChecksumRequired:l,requestAlgorithmMember:h},!!n.isS3ExpressBucket);let f=a,g=c;if(p){switch(p){case ee.CRC32:oe(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32","U");break;case ee.CRC32C:oe(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32C","V");break;case ee.SHA1:oe(n,"FLEXIBLE_CHECKSUMS_REQ_SHA1","X");break;case ee.SHA256:oe(n,"FLEXIBLE_CHECKSUMS_REQ_SHA256","Y")}const t=xi(p),r=zi(p,e);if(Ai(a)){const{getAwsChunkedEncodingStream:n,bodyLengthChecker:i}=e;f=n(a,{base64Encoder:d,bodyLengthChecker:i,checksumLocationName:t,checksumAlgorithmFn:r,streamHasher:u}),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 ji(r,a);g={...c,[t]:d(e)}}}return await r({...i,request:{...o,headers:g,body:f}})},Wi=(e=[])=>{const t=[];for(const r of Ei)e.includes(r)&&ki.includes(r)&&t.push(r);return t};function Ki(e){return new Blob([e]).stream()}const Vi=async(e,{checksumAlgorithmFn:t,base64Encoder:r})=>r(await ji(t,e)),Qi={name:"flexibleChecksumsResponseMiddleware",toMiddleware:"deserializerMiddleware",relation:"after",tags:["BODY_CHECKSUM"],override:!0},Gi=(e,t)=>(r,n)=>async i=>{if(!V.isInstance(i.request))return r(i);const o=i.input,s=await r(i),a=s.response;let c;const{requestValidationModeMember:d,responseAlgorithms:u}=t;if(d&&"ENABLED"===o[d]){const{clientName:t,commandName:r}=n;if("S3Client"===t&&"GetObjectCommand"===r&&Wi(u).every((e=>{const t=xi(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=Ai(a.body);i&&(c=await e.streamCollector(a.body),a.body=Ki(c)),await(async(e,{config:t,responseAlgorithms:r})=>{const n=Wi(r),{body:i,headers:o}=e;for(const r of n){const n=xi(r),s=o[n];if(s){const o=zi(r,t),{base64Encoder:a}=t;if(Ai(i))return void(e.body=Ye({expectedChecksum:s,checksumSourceLocation:n,checksum:new o,source:i,base64Encoder:a}));const c=await Vi(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:u}),i&&c&&(a.body=Ki(c))}return s},Ji=(e,t)=>({applyToStack:r=>{r.add(Hi(e,t),qi),r.addRelativeTo(Gi(e,t),Qi)}});const Yi={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},Xi=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{if(!V.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),Yi)}}),Zi={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},eo="X-Amzn-Trace-Id",to={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},ro=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{const{request:n}=r;if(!V.isInstance(n)||"node"!==e.runtime||n.headers.hasOwnProperty(eo))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[eo]=o),t({...r,request:n})})(e),to)}});const no={step:"finalizeRequest",tags:["CHECK_CONTENT_LENGTH_HEADER"],name:"getCheckContentLengthHeaderPlugin",override:!0},io=e=>({applyToStack:e=>{e.add(((e,t)=>async r=>{const{request:n}=r;if(V.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 Vr?console.warn(e):t.logger.warn(e)}return e({...r})}),no)}}),oo={tags:["REGION_REDIRECT","S3"],name:"regionRedirectEndpointMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};const so={step:"initialize",tags:["REGION_REDIRECT","S3"],name:"regionRedirectMiddleware",override:!0},ao=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),so),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),oo)}}),co={tags:["S3"],name:"s3ExpiresMiddleware",override:!0,relation:"after",toMiddleware:"deserializerMiddleware"},uo=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{const n=await e(r),{response:i}=n;if(Q.isInstance(i)&&i.headers.expires){i.headers.expiresstring=i.headers.expires;try{Sr(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}),co)}});class lo{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+lo.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 ho(Promise.resolve(e)))}))),e})):n.set(r,new ho(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 fo;po.REFRESH_WINDOW_MS=6e4,function(e){e.ENV="env",e.CONFIG="shared config entry"}(fo||(fo={}));const go="X-Amz-S3session-Token",mo=go.toLowerCase();class yo extends $t{async signWithCredentials(e,t,r){const n=bo(t);e.headers[mo]=t.sessionToken;return vo(this,n),this.signRequest(e,r??{})}async presignWithCredentials(e,t,r){const n=bo(t);delete e.headers[mo],e.headers[go]=t.sessionToken,e.query=e.query??{},e.query[go]=t.sessionToken;return vo(this,n),this.presign(e,r)}}function bo(e){return{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,expiration:e.expiration}}function vo(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 wo={name:"s3ExpressMiddleware",step:"build",tags:["S3","S3_EXPRESS"],override:!0},So=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)&&(oe(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,V.isInstance(n.request)&&i.sessionToken&&(n.request.headers[mo]=i.sessionToken)}}}return t(n)})(e),wo)}}),ko=e=>e=>{throw e},Eo=(e,t)=>{},xo=e=>(t,r)=>async n=>{if(!V.isInstance(n.request))return t(n);const i=pe(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 d=await t({...n,request:c}).catch((a.errorHandler||ko)(o));return(a.successHandler||Eo)(d.response,o),d},Ao={CopyObjectCommand:!0,UploadPartCopyCommand:!0,CompleteMultipartUploadCommand:!0},Co=e=>(t,r)=>async n=>{const i=await t(n),{response:o}=i;if(!Q.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,d=a;!a||"object"!=typeof a||a instanceof Uint8Array||([c,d]=await async function(e){return"function"==typeof e.stream&&(e=e.stream()),e.tee()}(a)),o.body=d;const u=await To(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(u.subarray(u.length-16));if(0===u.length&&Ao[r.commandName]){const e=new Error("S3 aborted request");throw e.name="InternalError",e}return l&&l.endsWith("")&&(o.statusCode=400),i},To=(e=new Uint8Array,t)=>e instanceof Uint8Array?Promise.resolve(e):t.streamCollector(e)||Promise.resolve(new Uint8Array),Ro={relation:"after",toMiddleware:"deserializerMiddleware",tags:["THROW_200_EXCEPTIONS","S3"],name:"throw200ExceptionsMiddleware",override:!0},Oo=e=>({applyToStack:t=>{t.addRelativeTo(Co(e),Ro)}});const Po={name:"bucketEndpointMiddleware",override:!0,relation:"after",toMiddleware:"endpointV2Middleware"};const Io={step:"initialize",tags:["VALIDATE_BUCKET_NAME"],name:"validateBucketNameMiddleware",override:!0},_o=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),Io),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),Po)}});const Mo=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}$"),No=e=>Mo.test(e)||e.startsWith("[")&&e.endsWith("]"),$o=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),Fo=(e,t=!1)=>{if(!t)return $o.test(e);const r=e.split(".");for(const e of r)if(!Fo(e))return!1;return!0},Uo={},Lo="endpoints";function Do(e){return"object"!=typeof e||null==e?e:"ref"in e?`$${Do(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(Do).join(", ")})`:JSON.stringify(e,null,2)}class Bo extends Error{constructor(e){super(e),this.name="EndpointError"}}const zo=(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 Bo(`Path: '${e}' does not end with ']'`);const i=n.slice(t+1,-1);if(Number.isNaN(parseInt(i)))throw new Bo(`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 Bo(`Index '${n}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(r)?r[parseInt(n)]:r[n]}),e),jo={[z.HTTP]:80,[z.HTTPS]:443},qo={booleanEquals:(e,t)=>e===t,getAttr:zo,isSet:e=>null!=e,isValidHostLabel:Fo,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(z).includes(c))return null;const d=No(i);return{scheme:c,authority:`${n}${r.includes(`${n}:${jo[c]}`)||"string"==typeof e&&e.includes(`${n}:${jo[c]}`)?`:${jo[c]}`:""}`,path:o,normalizedPath:o.endsWith("/")?o:`${o}/`,isIp:d}},stringEquals:(e,t)=>e===t,substring:(e,t,r,n)=>t>=r||e.lengthencodeURIComponent(e).replace(/[!*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))},Ho=(e,t)=>{const r=[],n={...t.endpointParams,...t.referenceRecord};let i=0;for(;i{if("string"==typeof e)return Ho(e,r);if(e.fn)return Ko(e,r);if(e.ref)return(({ref:e},t)=>({...t.endpointParams,...t.referenceRecord}[e]))(e,r);throw new Bo(`'${t}': ${String(e)} is not a string, function or reference.`)},Ko=({fn:e,argv:t},r)=>{const n=t.map((e=>["boolean","number"].includes(typeof e)?e:Wo(e,"arg",r))),i=e.split(".");return i[0]in Uo&&null!=i[1]?Uo[i[0]][i[1]](...n):qo[e](...n)},Vo=({assign:e,...t},r)=>{if(e&&e in r.referenceRecord)throw new Bo(`'${e}' is already defined in Reference Record.`);const n=Ko(t,r);return r.logger?.debug?.(`${Lo} evaluateCondition: ${Do(t)} = ${Do(n)}`),{result:""===n||!!n,...null!=e&&{toAssign:{name:e,value:n}}}},Qo=(e=[],t)=>{const r={};for(const n of e){const{result:e,toAssign:i}=Vo(n,{...t,referenceRecord:{...t.referenceRecord,...r}});if(!e)return{result:e};i&&(r[i.name]=i.value,t.logger?.debug?.(`${Lo} assign: ${i.name} := ${Do(i.value)}`))}return{result:!0,referenceRecord:r}},Go=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:n.map((e=>{const n=Wo(e,"Header value entry",t);if("string"!=typeof n)throw new Bo(`Header '${r}' value '${n}' is not a string`);return n}))})),{}),Jo=(e,t)=>{if(Array.isArray(e))return e.map((e=>Jo(e,t)));switch(typeof e){case"string":return Ho(e,t);case"object":if(null===e)throw new Bo(`Unexpected endpoint property: ${e}`);return Yo(e,t);case"boolean":return e;default:throw new Bo("Unexpected endpoint property type: "+typeof e)}},Yo=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:Jo(n,t)})),{}),Xo=(e,t)=>{const r=Wo(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 Bo("Endpoint URL must be a string, got "+typeof r)},Zo=(e,t)=>{const{conditions:r,endpoint:n}=e,{result:i,referenceRecord:o}=Qo(r,t);if(!i)return;const s={...t,referenceRecord:{...t.referenceRecord,...o}},{url:a,properties:c,headers:d}=n;return t.logger?.debug?.(`${Lo} Resolving endpoint from template: ${Do(n)}`),{...null!=d&&{headers:Go(d,s)},...null!=c&&{properties:Yo(c,s)},url:Xo(a,s)}},es=(e,t)=>{const{conditions:r,error:n}=e,{result:i,referenceRecord:o}=Qo(r,t);if(i)throw new Bo(Wo(n,"Error",{...t,referenceRecord:{...t.referenceRecord,...o}}))},ts=(e,t)=>{const{conditions:r,rules:n}=e,{result:i,referenceRecord:o}=Qo(r,t);if(i)return rs(n,{...t,referenceRecord:{...t.referenceRecord,...o}})},rs=(e,t)=>{for(const r of e)if("endpoint"===r.type){const e=Zo(r,t);if(e)return e}else if("error"===r.type)es(r,t);else{if("tree"!==r.type)throw new Bo(`Unknown endpoint rule: ${r}`);{const e=ts(r,t);if(e)return e}}throw new Bo("Rules evaluation failed")},ns=(e,t=!1)=>{if(t){for(const t of e.split("."))if(!ns(t))return!1;return!0}return!!Fo(e)&&(!(e.length<3||e.length>63)&&(e===e.toLowerCase()&&!No(e)))};let is={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 os={isVirtualHostableS3Bucket:ns,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}=is;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}}};Uo.aws=os;const ss=/\d{12}\.ddb/;const as="user-agent",cs="x-amz-user-agent",ds=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g,us=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;const ls=e=>(t,r)=>async n=>{const{request:i}=n;if(!V.isInstance(i))return t(n);const{headers:o}=i,s=r?.userAgent?.map(hs)||[],a=(await e.defaultUserAgentProvider()).map(hs);await async function(e,t,r){const n=r.request;if("rpc-v2-cbor"===n?.headers?.["smithy-protocol"]&&oe(e,"PROTOCOL_RPC_V2_CBOR","M"),"function"==typeof t.retryStrategy){const r=await t.retryStrategy();"function"==typeof r.acquireInitialRetryToken?r.constructor?.name?.includes("Adaptive")?oe(e,"RETRY_MODE_ADAPTIVE","F"):oe(e,"RETRY_MODE_STANDARD","E"):oe(e,"RETRY_MODE_LEGACY","D")}if("function"==typeof t.accountIdEndpointMode){const r=e.endpointV2;switch(String(r?.url?.hostname).match(ss)&&oe(e,"ACCOUNT_ID_ENDPOINT","O"),await(t.accountIdEndpointMode?.())){case"disabled":oe(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":oe(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":oe(e,"ACCOUNT_ID_MODE_REQUIRED","R")}}const i=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const t=i;t.accountId&&oe(e,"RESOLVED_ACCOUNT_ID","T");for(const[r,n]of Object.entries(t.$source??{}))oe(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 d=e?.customUserAgent?.map(hs)||[],u=await e.userAgentAppId();u&&a.push(hs([`app/${u}`]));const l=[].concat([...a,...s,...d]).join(" "),h=[...a.filter((e=>e.startsWith("aws-sdk-"))),...d].join(" ");return"browser"!==e.runtime?(h&&(o[cs]=o[cs]?`${o[as]} ${h}`:h),o[as]=l):o[cs]=l,t({...n,request:i})},hs=e=>{const t=e[0].split("/").map((e=>e.replace(ds,"-"))).join("/"),r=e[1]?.replace(us,"-"),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}`}}),"")},ps={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},fs=e=>"string"==typeof e&&(e.startsWith("fips-")||e.endsWith("-fips")),gs=e=>fs(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,ms="content-length";const ys={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},bs=e=>({applyToStack:t=>{var r;t.add((r=e.bodyLengthChecker,e=>async t=>{const n=t.request;if(V.isInstance(n)){const{body:e,headers:t}=n;if(e&&-1===Object.keys(t).map((e=>e.toLowerCase())).indexOf(ms))try{const t=r(e);n.headers={...n.headers,[ms]:String(t)}}catch(e){}}return e({...t,request:n})}),ys)}}),vs=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,ws=/(\d+\.){3}\d+/,Ss=/\.\./,ks=e=>vs.test(e)&&!ws.test(e)&&!Ss.test(e),Es=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},xs=(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},As=async e=>{};const Cs=e=>{if("string"==typeof e)return Cs(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}},Ts=e=>"object"==typeof e?"url"in e?Cs(e.url):e:Cs(e),Rs=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 xs(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("?"))),Es(t)){if(!0===e.ForcePathStyle)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!ks(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},Os=({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 As(r.serviceId),e&&(r.endpoint=()=>Promise.resolve(Ts(e)))}const i=await Rs(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=pe(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})},Ps={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:be.name},Is=(e,t)=>({applyToStack:r=>{r.addRelativeTo(Os({config:e,instructions:t}),Ps)}});var _s;!function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"}(_s||(_s={}));const Ms=_s.STANDARD,Ns=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],$s=["TimeoutError","RequestTimeout","RequestTimeoutException"],Fs=[500,502,503,504],Us=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],Ls=e=>429===e.$metadata?.httpStatusCode||Ns.includes(e.name)||1==e.$retryable?.throttling,Ds=e=>(e=>e.$metadata?.clockSkewCorrected)(e)||$s.includes(e.name)||Us.includes(e?.code||"")||Fs.includes(e.$metadata?.httpStatusCode||0);class Bs{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=>Bs.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(),Ls(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))}}Bs.setTimeoutFn=setTimeout;const zs=({retryDelay:e,retryCount:t,retryCost:r})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(2e4,e),getRetryCost:()=>r});class js{constructor(e){this.maxAttempts=e,this.mode=_s.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 zs({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,zs({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 qs{constructor(e,t){this.maxAttemptsProvider=e,this.mode=_s.ADAPTIVE;const{rateLimiter:r}=t??{};this.rateLimiter=r??new Bs,this.standardRetryStrategy=new js(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 Hs;const Ws=new Uint8Array(16);function Ks(){if(!Hs&&(Hs="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Hs))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Hs(Ws)}const Vs=[];for(let e=0;e<256;++e)Vs.push((e+256).toString(16).slice(1));var Qs={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Gs(e,t,r){if(Qs.randomUUID&&!t&&!e)return Qs.randomUUID();const n=(e=e||{}).random||(e.rng||Ks)();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 Vs[e[t+0]]+Vs[e[t+1]]+Vs[e[t+2]]+Vs[e[t+3]]+"-"+Vs[e[t+4]]+Vs[e[t+5]]+"-"+Vs[e[t+6]]+Vs[e[t+7]]+"-"+Vs[e[t+8]]+Vs[e[t+9]]+"-"+Vs[e[t+10]]+Vs[e[t+11]]+Vs[e[t+12]]+Vs[e[t+13]]+Vs[e[t+14]]+Vs[e[t+15]]}(n)}const Js=e=>e?.body instanceof ReadableStream,Ys=e=>void 0!==e.acquireInitialRetryToken&&void 0!==e.refreshRetryTokenForRetry&&void 0!==e.recordSuccess,Xs=e=>{const t={error:e,errorType:Zs(e)},r=ra(e.$response);return r&&(t.retryAfterHint=r),t},Zs=e=>Ls(e)?"THROTTLING":Ds(e)?"TRANSIENT":(e=>{if(void 0!==e.$metadata?.httpStatusCode){const t=e.$metadata.httpStatusCode;return 500<=t&&t<=599&&!Ds(e)}return!1})(e)?"SERVER_ERROR":"CLIENT_ERROR",ea={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},ta=e=>({applyToStack:t=>{t.add((e=>(t,r)=>async n=>{let i=await e.retryStrategy();const o=await e.maxAttempts();if(!Ys(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,d=0;const{request:u}=n,l=V.isInstance(u);for(l&&(u.headers["amz-sdk-invocation-id"]=Gs());;)try{l&&(u.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=d,{response:r,output:s}}catch(t){const n=Xs(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&&Js(u))throw(r.logger instanceof Vr?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=d,a}c=e.getRetryCount();const o=e.getRetryDelay();d+=o,await new Promise((e=>setTimeout(e,o)))}}var s})(e),ea)}}),ra=e=>{if(!Q.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)},na=null;class ia{constructor(e){this.sigv4Signer=new yo(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=na,"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 oa="required",sa="type",aa="conditions",ca="fn",da="argv",ua="ref",la="assign",ha="url",pa="properties",fa="backend",ga="authSchemes",ma="disableDoubleEncoding",ya="signingName",ba="signingRegion",va="headers",wa="signingRegionSet",Sa=!0,ka="isSet",Ea="booleanEquals",xa="error",Aa="aws.partition",Ca="stringEquals",Ta="getAttr",Ra="name",Oa="substring",Pa="bucketSuffix",Ia="parseURL",_a="{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",Ma="endpoint",Na="tree",$a="aws.isVirtualHostableS3Bucket",Fa="{url#scheme}://{Bucket}.{url#authority}{url#path}",Ua="not",La="{url#scheme}://{url#authority}{url#path}",Da="hardwareType",Ba="regionPrefix",za="bucketAliasSuffix",ja="outpostId",qa="isValidHostLabel",Ha="sigv4a",Wa="s3-outposts",Ka="s3",Va="{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}",Qa="https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}",Ga="https://{Bucket}.s3.{partitionResult#dnsSuffix}",Ja="aws.parseArn",Ya="bucketArn",Xa="arnType",Za="s3-object-lambda",ec="accesspoint",tc="accessPointName",rc="{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}",nc="mrapPartition",ic="outpostType",oc="arnPrefix",sc="{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}",ac="https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",cc="https://s3.{partitionResult#dnsSuffix}",dc={[oa]:!1,[sa]:"String"},uc={[oa]:!0,default:!1,[sa]:"Boolean"},lc={[oa]:!1,[sa]:"Boolean"},hc={[ca]:Ea,[da]:[{[ua]:"Accelerate"},!0]},pc={[ca]:Ea,[da]:[{[ua]:"UseFIPS"},!0]},fc={[ca]:Ea,[da]:[{[ua]:"UseDualStack"},!0]},gc={[ca]:ka,[da]:[{[ua]:"Endpoint"}]},mc={[ca]:Aa,[da]:[{[ua]:"Region"}],[la]:"partitionResult"},yc={[ca]:Ca,[da]:[{[ca]:Ta,[da]:[{[ua]:"partitionResult"},Ra]},"aws-cn"]},bc={[ca]:ka,[da]:[{[ua]:"Bucket"}]},vc={[ua]:"Bucket"},wc={[ca]:Ia,[da]:[{[ua]:"Endpoint"}],[la]:"url"},Sc={[ca]:Ea,[da]:[{[ca]:Ta,[da]:[{[ua]:"url"},"isIp"]},!0]},kc={[ua]:"url"},Ec={[ca]:"uriEncode",[da]:[vc],[la]:"uri_encoded_bucket"},xc={[fa]:"S3Express",[ga]:[{[ma]:!0,[Ra]:"sigv4",[ya]:"s3express",[ba]:"{Region}"}]},Ac={},Cc={[ca]:$a,[da]:[vc,!1]},Tc={[xa]:"S3Express bucket name is not a valid virtual hostable name.",[sa]:xa},Rc={[fa]:"S3Express",[ga]:[{[ma]:!0,[Ra]:"sigv4-s3express",[ya]:"s3express",[ba]:"{Region}"}]},Oc={[ca]:ka,[da]:[{[ua]:"UseS3ExpressControlEndpoint"}]},Pc={[ca]:Ea,[da]:[{[ua]:"UseS3ExpressControlEndpoint"},!0]},Ic={[ca]:Ua,[da]:[gc]},_c={[xa]:"Unrecognized S3Express bucket name format.",[sa]:xa},Mc={[ca]:Ua,[da]:[bc]},Nc={[ua]:Da},$c={[aa]:[Ic],[xa]:"Expected a endpoint to be specified but no endpoint was found",[sa]:xa},Fc={[ga]:[{[ma]:!0,[Ra]:Ha,[ya]:Wa,[wa]:["*"]},{[ma]:!0,[Ra]:"sigv4",[ya]:Wa,[ba]:"{Region}"}]},Uc={[ca]:Ea,[da]:[{[ua]:"ForcePathStyle"},!1]},Lc={[ua]:"ForcePathStyle"},Dc={[ca]:Ea,[da]:[{[ua]:"Accelerate"},!1]},Bc={[ca]:Ca,[da]:[{[ua]:"Region"},"aws-global"]},zc={[ga]:[{[ma]:!0,[Ra]:"sigv4",[ya]:Ka,[ba]:"us-east-1"}]},jc={[ca]:Ua,[da]:[Bc]},qc={[ca]:Ea,[da]:[{[ua]:"UseGlobalEndpoint"},!0]},Hc={[ha]:"https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[pa]:{[ga]:[{[ma]:!0,[Ra]:"sigv4",[ya]:Ka,[ba]:"{Region}"}]},[va]:{}},Wc={[ga]:[{[ma]:!0,[Ra]:"sigv4",[ya]:Ka,[ba]:"{Region}"}]},Kc={[ca]:Ea,[da]:[{[ua]:"UseGlobalEndpoint"},!1]},Vc={[ca]:Ea,[da]:[{[ua]:"UseDualStack"},!1]},Qc={[ha]:"https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",[pa]:Wc,[va]:{}},Gc={[ca]:Ea,[da]:[{[ua]:"UseFIPS"},!1]},Jc={[ha]:"https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",[pa]:Wc,[va]:{}},Yc={[ha]:"https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[pa]:Wc,[va]:{}},Xc={[ca]:Ea,[da]:[{[ca]:Ta,[da]:[kc,"isIp"]},!1]},Zc={[ha]:Va,[pa]:Wc,[va]:{}},ed={[ha]:Fa,[pa]:Wc,[va]:{}},td={[Ma]:ed,[sa]:Ma},rd={[ha]:Qa,[pa]:Wc,[va]:{}},nd={[ha]:"https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",[pa]:Wc,[va]:{}},id={[xa]:"Invalid region: region was not a valid DNS name.",[sa]:xa},od={[ua]:Ya},sd={[ua]:Xa},ad={[ca]:Ta,[da]:[od,"service"]},cd={[ua]:tc},dd={[aa]:[fc],[xa]:"S3 Object Lambda does not support Dual-stack",[sa]:xa},ud={[aa]:[hc],[xa]:"S3 Object Lambda does not support S3 Accelerate",[sa]:xa},ld={[aa]:[{[ca]:ka,[da]:[{[ua]:"DisableAccessPoints"}]},{[ca]:Ea,[da]:[{[ua]:"DisableAccessPoints"},!0]}],[xa]:"Access points are not supported for this operation",[sa]:xa},hd={[aa]:[{[ca]:ka,[da]:[{[ua]:"UseArnRegion"}]},{[ca]:Ea,[da]:[{[ua]:"UseArnRegion"},!1]},{[ca]:Ua,[da]:[{[ca]:Ca,[da]:[{[ca]:Ta,[da]:[od,"region"]},"{Region}"]}]}],[xa]:"Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",[sa]:xa},pd={[ca]:Ta,[da]:[{[ua]:"bucketPartition"},Ra]},fd={[ca]:Ta,[da]:[od,"accountId"]},gd={[ga]:[{[ma]:!0,[Ra]:"sigv4",[ya]:Za,[ba]:"{bucketArn#region}"}]},md={[xa]:"Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",[sa]:xa},yd={[xa]:"Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",[sa]:xa},bd={[xa]:"Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",[sa]:xa},vd={[xa]:"Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",[sa]:xa},wd={[xa]:"Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",[sa]:xa},Sd={[xa]:"Invalid ARN: Expected a resource of the format `accesspoint:` but no name was provided",[sa]:xa},kd={[ga]:[{[ma]:!0,[Ra]:"sigv4",[ya]:Ka,[ba]:"{bucketArn#region}"}]},Ed={[ga]:[{[ma]:!0,[Ra]:Ha,[ya]:Wa,[wa]:["*"]},{[ma]:!0,[Ra]:"sigv4",[ya]:Wa,[ba]:"{bucketArn#region}"}]},xd={[ca]:Ja,[da]:[vc]},Ad={[ha]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[pa]:Wc,[va]:{}},Cd={[ha]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[pa]:Wc,[va]:{}},Td={[ha]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[pa]:Wc,[va]:{}},Rd={[ha]:sc,[pa]:Wc,[va]:{}},Od={[ha]:"https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[pa]:Wc,[va]:{}},Pd={[ua]:"UseObjectLambdaEndpoint"},Id={[ga]:[{[ma]:!0,[Ra]:"sigv4",[ya]:Za,[ba]:"{Region}"}]},_d={[ha]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[pa]:Wc,[va]:{}},Md={[ha]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}",[pa]:Wc,[va]:{}},Nd={[ha]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[pa]:Wc,[va]:{}},$d={[ha]:La,[pa]:Wc,[va]:{}},Fd={[ha]:"https://s3.{Region}.{partitionResult#dnsSuffix}",[pa]:Wc,[va]:{}},Ud=[{[ua]:"Region"}],Ld=[{[ua]:"Endpoint"}],Dd=[vc],Bd=[fc],zd=[hc],jd=[gc,wc],qd=[{[ca]:ka,[da]:[{[ua]:"DisableS3ExpressSessionAuth"}]},{[ca]:Ea,[da]:[{[ua]:"DisableS3ExpressSessionAuth"},!0]}],Hd=[Sc],Wd=[Ec],Kd=[Cc],Vd=[pc],Qd=[{[ca]:Oa,[da]:[vc,6,14,!0],[la]:"s3expressAvailabilityZoneId"},{[ca]:Oa,[da]:[vc,14,16,!0],[la]:"s3expressAvailabilityZoneDelim"},{[ca]:Ca,[da]:[{[ua]:"s3expressAvailabilityZoneDelim"},"--"]}],Gd=[{[aa]:[pc],[Ma]:{[ha]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[pa]:xc,[va]:{}},[sa]:Ma},{[Ma]:{[ha]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[pa]:xc,[va]:{}},[sa]:Ma}],Jd=[{[ca]:Oa,[da]:[vc,6,15,!0],[la]:"s3expressAvailabilityZoneId"},{[ca]:Oa,[da]:[vc,15,17,!0],[la]:"s3expressAvailabilityZoneDelim"},{[ca]:Ca,[da]:[{[ua]:"s3expressAvailabilityZoneDelim"},"--"]}],Yd=[{[aa]:[pc],[Ma]:{[ha]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[pa]:Rc,[va]:{}},[sa]:Ma},{[Ma]:{[ha]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[pa]:Rc,[va]:{}},[sa]:Ma}],Xd=[bc],Zd=[{[ca]:qa,[da]:[{[ua]:ja},!1]}],eu=[{[ca]:Ca,[da]:[{[ua]:Ba},"beta"]}],tu=[mc],ru=[{[ca]:qa,[da]:[{[ua]:"Region"},!1]}],nu=[{[ca]:Ca,[da]:[{[ua]:"Region"},"us-east-1"]}],iu=[{[ca]:Ca,[da]:[sd,ec]}],ou=[{[ca]:Ta,[da]:[od,"resourceId[1]"],[la]:tc},{[ca]:Ua,[da]:[{[ca]:Ca,[da]:[cd,""]}]}],su=[od,"resourceId[1]"],au=[{[ca]:Ua,[da]:[{[ca]:Ca,[da]:[{[ca]:Ta,[da]:[od,"region"]},""]}]}],cu=[{[ca]:Ua,[da]:[{[ca]:ka,[da]:[{[ca]:Ta,[da]:[od,"resourceId[2]"]}]}]}],du=[od,"resourceId[2]"],uu=[{[ca]:Aa,[da]:[{[ca]:Ta,[da]:[od,"region"]}],[la]:"bucketPartition"}],lu=[{[ca]:Ca,[da]:[pd,{[ca]:Ta,[da]:[{[ua]:"partitionResult"},Ra]}]}],hu=[{[ca]:qa,[da]:[{[ca]:Ta,[da]:[od,"region"]},!0]}],pu=[{[ca]:qa,[da]:[fd,!1]}],fu=[{[ca]:qa,[da]:[cd,!1]}],gu=[{[ca]:qa,[da]:[{[ua]:"Region"},!0]}],mu={version:"1.0",parameters:{Bucket:dc,Region:dc,UseFIPS:uc,UseDualStack:uc,Endpoint:dc,ForcePathStyle:uc,Accelerate:uc,UseGlobalEndpoint:uc,UseObjectLambdaEndpoint:lc,Key:dc,Prefix:dc,CopySource:dc,DisableAccessPoints:lc,DisableMultiRegionAccessPoints:uc,UseArnRegion:lc,UseS3ExpressControlEndpoint:lc,DisableS3ExpressSessionAuth:lc},rules:[{[aa]:[{[ca]:ka,[da]:Ud}],rules:[{[aa]:[hc,pc],error:"Accelerate cannot be used with FIPS",[sa]:xa},{[aa]:[fc,gc],error:"Cannot set dual-stack in combination with a custom endpoint.",[sa]:xa},{[aa]:[gc,pc],error:"A custom endpoint cannot be combined with FIPS",[sa]:xa},{[aa]:[gc,hc],error:"A custom endpoint cannot be combined with S3 Accelerate",[sa]:xa},{[aa]:[pc,mc,yc],error:"Partition does not support FIPS",[sa]:xa},{[aa]:[bc,{[ca]:Oa,[da]:[vc,0,6,Sa],[la]:Pa},{[ca]:Ca,[da]:[{[ua]:Pa},"--x-s3"]}],rules:[{[aa]:Bd,error:"S3Express does not support Dual-stack.",[sa]:xa},{[aa]:zd,error:"S3Express does not support S3 Accelerate.",[sa]:xa},{[aa]:jd,rules:[{[aa]:qd,rules:[{[aa]:Hd,rules:[{[aa]:Wd,rules:[{endpoint:{[ha]:_a,[pa]:xc,[va]:Ac},[sa]:Ma}],[sa]:Na}],[sa]:Na},{[aa]:Kd,rules:[{endpoint:{[ha]:Fa,[pa]:xc,[va]:Ac},[sa]:Ma}],[sa]:Na},Tc],[sa]:Na},{[aa]:Hd,rules:[{[aa]:Wd,rules:[{endpoint:{[ha]:_a,[pa]:Rc,[va]:Ac},[sa]:Ma}],[sa]:Na}],[sa]:Na},{[aa]:Kd,rules:[{endpoint:{[ha]:Fa,[pa]:Rc,[va]:Ac},[sa]:Ma}],[sa]:Na},Tc],[sa]:Na},{[aa]:[Oc,Pc],rules:[{[aa]:[Ec,Ic],rules:[{[aa]:Vd,endpoint:{[ha]:"https://s3express-control-fips.{Region}.amazonaws.com/{uri_encoded_bucket}",[pa]:xc,[va]:Ac},[sa]:Ma},{endpoint:{[ha]:"https://s3express-control.{Region}.amazonaws.com/{uri_encoded_bucket}",[pa]:xc,[va]:Ac},[sa]:Ma}],[sa]:Na}],[sa]:Na},{[aa]:Kd,rules:[{[aa]:qd,rules:[{[aa]:Qd,rules:Gd,[sa]:Na},{[aa]:Jd,rules:Gd,[sa]:Na},_c],[sa]:Na},{[aa]:Qd,rules:Yd,[sa]:Na},{[aa]:Jd,rules:Yd,[sa]:Na},_c],[sa]:Na},Tc],[sa]:Na},{[aa]:[Mc,Oc,Pc],rules:[{[aa]:jd,endpoint:{[ha]:La,[pa]:xc,[va]:Ac},[sa]:Ma},{[aa]:Vd,endpoint:{[ha]:"https://s3express-control-fips.{Region}.amazonaws.com",[pa]:xc,[va]:Ac},[sa]:Ma},{endpoint:{[ha]:"https://s3express-control.{Region}.amazonaws.com",[pa]:xc,[va]:Ac},[sa]:Ma}],[sa]:Na},{[aa]:[bc,{[ca]:Oa,[da]:[vc,49,50,Sa],[la]:Da},{[ca]:Oa,[da]:[vc,8,12,Sa],[la]:Ba},{[ca]:Oa,[da]:[vc,0,7,Sa],[la]:za},{[ca]:Oa,[da]:[vc,32,49,Sa],[la]:ja},{[ca]:Aa,[da]:Ud,[la]:"regionPartition"},{[ca]:Ca,[da]:[{[ua]:za},"--op-s3"]}],rules:[{[aa]:Zd,rules:[{[aa]:[{[ca]:Ca,[da]:[Nc,"e"]}],rules:[{[aa]:eu,rules:[$c,{[aa]:jd,endpoint:{[ha]:"https://{Bucket}.ec2.{url#authority}",[pa]:Fc,[va]:Ac},[sa]:Ma}],[sa]:Na},{endpoint:{[ha]:"https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[pa]:Fc,[va]:Ac},[sa]:Ma}],[sa]:Na},{[aa]:[{[ca]:Ca,[da]:[Nc,"o"]}],rules:[{[aa]:eu,rules:[$c,{[aa]:jd,endpoint:{[ha]:"https://{Bucket}.op-{outpostId}.{url#authority}",[pa]:Fc,[va]:Ac},[sa]:Ma}],[sa]:Na},{endpoint:{[ha]:"https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[pa]:Fc,[va]:Ac},[sa]:Ma}],[sa]:Na},{error:'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',[sa]:xa}],[sa]:Na},{error:"Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",[sa]:xa}],[sa]:Na},{[aa]:Xd,rules:[{[aa]:[gc,{[ca]:Ua,[da]:[{[ca]:ka,[da]:[{[ca]:Ia,[da]:Ld}]}]}],error:"Custom endpoint `{Endpoint}` was not a valid URI",[sa]:xa},{[aa]:[Uc,Cc],rules:[{[aa]:tu,rules:[{[aa]:ru,rules:[{[aa]:[hc,yc],error:"S3 Accelerate cannot be used in this region",[sa]:xa},{[aa]:[fc,pc,Dc,Ic,Bc],endpoint:{[ha]:"https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[fc,pc,Dc,Ic,jc,qc],rules:[{endpoint:Hc,[sa]:Ma}],[sa]:Na},{[aa]:[fc,pc,Dc,Ic,jc,Kc],endpoint:Hc,[sa]:Ma},{[aa]:[Vc,pc,Dc,Ic,Bc],endpoint:{[ha]:"https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[Vc,pc,Dc,Ic,jc,qc],rules:[{endpoint:Qc,[sa]:Ma}],[sa]:Na},{[aa]:[Vc,pc,Dc,Ic,jc,Kc],endpoint:Qc,[sa]:Ma},{[aa]:[fc,Gc,hc,Ic,Bc],endpoint:{[ha]:"https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[fc,Gc,hc,Ic,jc,qc],rules:[{endpoint:Jc,[sa]:Ma}],[sa]:Na},{[aa]:[fc,Gc,hc,Ic,jc,Kc],endpoint:Jc,[sa]:Ma},{[aa]:[fc,Gc,Dc,Ic,Bc],endpoint:{[ha]:"https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[fc,Gc,Dc,Ic,jc,qc],rules:[{endpoint:Yc,[sa]:Ma}],[sa]:Na},{[aa]:[fc,Gc,Dc,Ic,jc,Kc],endpoint:Yc,[sa]:Ma},{[aa]:[Vc,Gc,Dc,gc,wc,Sc,Bc],endpoint:{[ha]:Va,[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[Vc,Gc,Dc,gc,wc,Xc,Bc],endpoint:{[ha]:Fa,[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[Vc,Gc,Dc,gc,wc,Sc,jc,qc],rules:[{[aa]:nu,endpoint:Zc,[sa]:Ma},{endpoint:Zc,[sa]:Ma}],[sa]:Na},{[aa]:[Vc,Gc,Dc,gc,wc,Xc,jc,qc],rules:[{[aa]:nu,endpoint:ed,[sa]:Ma},td],[sa]:Na},{[aa]:[Vc,Gc,Dc,gc,wc,Sc,jc,Kc],endpoint:Zc,[sa]:Ma},{[aa]:[Vc,Gc,Dc,gc,wc,Xc,jc,Kc],endpoint:ed,[sa]:Ma},{[aa]:[Vc,Gc,hc,Ic,Bc],endpoint:{[ha]:Qa,[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[Vc,Gc,hc,Ic,jc,qc],rules:[{[aa]:nu,endpoint:rd,[sa]:Ma},{endpoint:rd,[sa]:Ma}],[sa]:Na},{[aa]:[Vc,Gc,hc,Ic,jc,Kc],endpoint:rd,[sa]:Ma},{[aa]:[Vc,Gc,Dc,Ic,Bc],endpoint:{[ha]:Ga,[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[Vc,Gc,Dc,Ic,jc,qc],rules:[{[aa]:nu,endpoint:{[ha]:Ga,[pa]:Wc,[va]:Ac},[sa]:Ma},{endpoint:nd,[sa]:Ma}],[sa]:Na},{[aa]:[Vc,Gc,Dc,Ic,jc,Kc],endpoint:nd,[sa]:Ma}],[sa]:Na},id],[sa]:Na}],[sa]:Na},{[aa]:[gc,wc,{[ca]:Ca,[da]:[{[ca]:Ta,[da]:[kc,"scheme"]},"http"]},{[ca]:$a,[da]:[vc,Sa]},Uc,Gc,Vc,Dc],rules:[{[aa]:tu,rules:[{[aa]:ru,rules:[td],[sa]:Na},id],[sa]:Na}],[sa]:Na},{[aa]:[Uc,{[ca]:Ja,[da]:Dd,[la]:Ya}],rules:[{[aa]:[{[ca]:Ta,[da]:[od,"resourceId[0]"],[la]:Xa},{[ca]:Ua,[da]:[{[ca]:Ca,[da]:[sd,""]}]}],rules:[{[aa]:[{[ca]:Ca,[da]:[ad,Za]}],rules:[{[aa]:iu,rules:[{[aa]:ou,rules:[dd,ud,{[aa]:au,rules:[ld,{[aa]:cu,rules:[hd,{[aa]:uu,rules:[{[aa]:tu,rules:[{[aa]:lu,rules:[{[aa]:hu,rules:[{[aa]:[{[ca]:Ca,[da]:[fd,""]}],error:"Invalid ARN: Missing account id",[sa]:xa},{[aa]:pu,rules:[{[aa]:fu,rules:[{[aa]:jd,endpoint:{[ha]:rc,[pa]:gd,[va]:Ac},[sa]:Ma},{[aa]:Vd,endpoint:{[ha]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[pa]:gd,[va]:Ac},[sa]:Ma},{endpoint:{[ha]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",[pa]:gd,[va]:Ac},[sa]:Ma}],[sa]:Na},md],[sa]:Na},yd],[sa]:Na},bd],[sa]:Na},vd],[sa]:Na}],[sa]:Na}],[sa]:Na},wd],[sa]:Na},{error:"Invalid ARN: bucket ARN is missing a region",[sa]:xa}],[sa]:Na},Sd],[sa]:Na},{error:"Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",[sa]:xa}],[sa]:Na},{[aa]:iu,rules:[{[aa]:ou,rules:[{[aa]:au,rules:[{[aa]:iu,rules:[{[aa]:au,rules:[ld,{[aa]:cu,rules:[hd,{[aa]:uu,rules:[{[aa]:tu,rules:[{[aa]:[{[ca]:Ca,[da]:[pd,"{partitionResult#name}"]}],rules:[{[aa]:hu,rules:[{[aa]:[{[ca]:Ca,[da]:[ad,Ka]}],rules:[{[aa]:pu,rules:[{[aa]:fu,rules:[{[aa]:zd,error:"Access Points do not support S3 Accelerate",[sa]:xa},{[aa]:[pc,fc],endpoint:{[ha]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[pa]:kd,[va]:Ac},[sa]:Ma},{[aa]:[pc,Vc],endpoint:{[ha]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[pa]:kd,[va]:Ac},[sa]:Ma},{[aa]:[Gc,fc],endpoint:{[ha]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[pa]:kd,[va]:Ac},[sa]:Ma},{[aa]:[Gc,Vc,gc,wc],endpoint:{[ha]:rc,[pa]:kd,[va]:Ac},[sa]:Ma},{[aa]:[Gc,Vc],endpoint:{[ha]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",[pa]:kd,[va]:Ac},[sa]:Ma}],[sa]:Na},md],[sa]:Na},yd],[sa]:Na},{error:"Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",[sa]:xa}],[sa]:Na},bd],[sa]:Na},vd],[sa]:Na}],[sa]:Na}],[sa]:Na},wd],[sa]:Na}],[sa]:Na}],[sa]:Na},{[aa]:[{[ca]:qa,[da]:[cd,Sa]}],rules:[{[aa]:Bd,error:"S3 MRAP does not support dual-stack",[sa]:xa},{[aa]:Vd,error:"S3 MRAP does not support FIPS",[sa]:xa},{[aa]:zd,error:"S3 MRAP does not support S3 Accelerate",[sa]:xa},{[aa]:[{[ca]:Ea,[da]:[{[ua]:"DisableMultiRegionAccessPoints"},Sa]}],error:"Invalid configuration: Multi-Region Access Point ARNs are disabled.",[sa]:xa},{[aa]:[{[ca]:Aa,[da]:Ud,[la]:nc}],rules:[{[aa]:[{[ca]:Ca,[da]:[{[ca]:Ta,[da]:[{[ua]:nc},Ra]},{[ca]:Ta,[da]:[od,"partition"]}]}],rules:[{endpoint:{[ha]:"https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",[pa]:{[ga]:[{[ma]:Sa,name:Ha,[ya]:Ka,[wa]:["*"]}]},[va]:Ac},[sa]:Ma}],[sa]:Na},{error:"Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",[sa]:xa}],[sa]:Na}],[sa]:Na},{error:"Invalid Access Point Name",[sa]:xa}],[sa]:Na},Sd],[sa]:Na},{[aa]:[{[ca]:Ca,[da]:[ad,Wa]}],rules:[{[aa]:Bd,error:"S3 Outposts does not support Dual-stack",[sa]:xa},{[aa]:Vd,error:"S3 Outposts does not support FIPS",[sa]:xa},{[aa]:zd,error:"S3 Outposts does not support S3 Accelerate",[sa]:xa},{[aa]:[{[ca]:ka,[da]:[{[ca]:Ta,[da]:[od,"resourceId[4]"]}]}],error:"Invalid Arn: Outpost Access Point ARN contains sub resources",[sa]:xa},{[aa]:[{[ca]:Ta,[da]:su,[la]:ja}],rules:[{[aa]:Zd,rules:[hd,{[aa]:uu,rules:[{[aa]:tu,rules:[{[aa]:lu,rules:[{[aa]:hu,rules:[{[aa]:pu,rules:[{[aa]:[{[ca]:Ta,[da]:du,[la]:ic}],rules:[{[aa]:[{[ca]:Ta,[da]:[od,"resourceId[3]"],[la]:tc}],rules:[{[aa]:[{[ca]:Ca,[da]:[{[ua]:ic},ec]}],rules:[{[aa]:jd,endpoint:{[ha]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",[pa]:Ed,[va]:Ac},[sa]:Ma},{endpoint:{[ha]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",[pa]:Ed,[va]:Ac},[sa]:Ma}],[sa]:Na},{error:"Expected an outpost type `accesspoint`, found {outpostType}",[sa]:xa}],[sa]:Na},{error:"Invalid ARN: expected an access point name",[sa]:xa}],[sa]:Na},{error:"Invalid ARN: Expected a 4-component resource",[sa]:xa}],[sa]:Na},yd],[sa]:Na},bd],[sa]:Na},vd],[sa]:Na}],[sa]:Na}],[sa]:Na},{error:"Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",[sa]:xa}],[sa]:Na},{error:"Invalid ARN: The Outpost Id was not set",[sa]:xa}],[sa]:Na},{error:"Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",[sa]:xa}],[sa]:Na},{error:"Invalid ARN: No ARN type specified",[sa]:xa}],[sa]:Na},{[aa]:[{[ca]:Oa,[da]:[vc,0,4,!1],[la]:oc},{[ca]:Ca,[da]:[{[ua]:oc},"arn:"]},{[ca]:Ua,[da]:[{[ca]:ka,[da]:[xd]}]}],error:"Invalid ARN: `{Bucket}` was not a valid ARN",[sa]:xa},{[aa]:[{[ca]:Ea,[da]:[Lc,Sa]},xd],error:"Path-style addressing cannot be used with ARN buckets",[sa]:xa},{[aa]:Wd,rules:[{[aa]:tu,rules:[{[aa]:[Dc],rules:[{[aa]:[fc,Ic,pc,Bc],endpoint:{[ha]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[fc,Ic,pc,jc,qc],rules:[{endpoint:Ad,[sa]:Ma}],[sa]:Na},{[aa]:[fc,Ic,pc,jc,Kc],endpoint:Ad,[sa]:Ma},{[aa]:[Vc,Ic,pc,Bc],endpoint:{[ha]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[Vc,Ic,pc,jc,qc],rules:[{endpoint:Cd,[sa]:Ma}],[sa]:Na},{[aa]:[Vc,Ic,pc,jc,Kc],endpoint:Cd,[sa]:Ma},{[aa]:[fc,Ic,Gc,Bc],endpoint:{[ha]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[fc,Ic,Gc,jc,qc],rules:[{endpoint:Td,[sa]:Ma}],[sa]:Na},{[aa]:[fc,Ic,Gc,jc,Kc],endpoint:Td,[sa]:Ma},{[aa]:[Vc,gc,wc,Gc,Bc],endpoint:{[ha]:sc,[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[Vc,gc,wc,Gc,jc,qc],rules:[{[aa]:nu,endpoint:Rd,[sa]:Ma},{endpoint:Rd,[sa]:Ma}],[sa]:Na},{[aa]:[Vc,gc,wc,Gc,jc,Kc],endpoint:Rd,[sa]:Ma},{[aa]:[Vc,Ic,Gc,Bc],endpoint:{[ha]:ac,[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[Vc,Ic,Gc,jc,qc],rules:[{[aa]:nu,endpoint:{[ha]:ac,[pa]:Wc,[va]:Ac},[sa]:Ma},{endpoint:Od,[sa]:Ma}],[sa]:Na},{[aa]:[Vc,Ic,Gc,jc,Kc],endpoint:Od,[sa]:Ma}],[sa]:Na},{error:"Path-style addressing cannot be used with S3 Accelerate",[sa]:xa}],[sa]:Na}],[sa]:Na}],[sa]:Na},{[aa]:[{[ca]:ka,[da]:[Pd]},{[ca]:Ea,[da]:[Pd,Sa]}],rules:[{[aa]:tu,rules:[{[aa]:gu,rules:[dd,ud,{[aa]:jd,endpoint:{[ha]:La,[pa]:Id,[va]:Ac},[sa]:Ma},{[aa]:Vd,endpoint:{[ha]:"https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",[pa]:Id,[va]:Ac},[sa]:Ma},{endpoint:{[ha]:"https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",[pa]:Id,[va]:Ac},[sa]:Ma}],[sa]:Na},id],[sa]:Na}],[sa]:Na},{[aa]:[Mc],rules:[{[aa]:tu,rules:[{[aa]:gu,rules:[{[aa]:[pc,fc,Ic,Bc],endpoint:{[ha]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[pc,fc,Ic,jc,qc],rules:[{endpoint:_d,[sa]:Ma}],[sa]:Na},{[aa]:[pc,fc,Ic,jc,Kc],endpoint:_d,[sa]:Ma},{[aa]:[pc,Vc,Ic,Bc],endpoint:{[ha]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[pc,Vc,Ic,jc,qc],rules:[{endpoint:Md,[sa]:Ma}],[sa]:Na},{[aa]:[pc,Vc,Ic,jc,Kc],endpoint:Md,[sa]:Ma},{[aa]:[Gc,fc,Ic,Bc],endpoint:{[ha]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[Gc,fc,Ic,jc,qc],rules:[{endpoint:Nd,[sa]:Ma}],[sa]:Na},{[aa]:[Gc,fc,Ic,jc,Kc],endpoint:Nd,[sa]:Ma},{[aa]:[Gc,Vc,gc,wc,Bc],endpoint:{[ha]:La,[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[Gc,Vc,gc,wc,jc,qc],rules:[{[aa]:nu,endpoint:$d,[sa]:Ma},{endpoint:$d,[sa]:Ma}],[sa]:Na},{[aa]:[Gc,Vc,gc,wc,jc,Kc],endpoint:$d,[sa]:Ma},{[aa]:[Gc,Vc,Ic,Bc],endpoint:{[ha]:cc,[pa]:zc,[va]:Ac},[sa]:Ma},{[aa]:[Gc,Vc,Ic,jc,qc],rules:[{[aa]:nu,endpoint:{[ha]:cc,[pa]:Wc,[va]:Ac},[sa]:Ma},{endpoint:Fd,[sa]:Ma}],[sa]:Na},{[aa]:[Gc,Vc,Ic,jc,Kc],endpoint:Fd,[sa]:Ma}],[sa]:Na},id],[sa]:Na}],[sa]:Na}],[sa]:Na},{error:"A region must be set when sending requests to S3.",[sa]:xa}]},yu=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"]}),bu=(e,t={})=>yu.get(e,(()=>((e,t)=>{const{endpointParams:r,logger:n}=t,{parameters:i,rules:o}=e;t.logger?.debug?.(`${Lo} Initial EndpointParams: ${Do(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 Bo(`Missing required parameter: '${e}'`);const c=rs(o,{endpointParams:r,logger:n,referenceRecord:{}});return t.logger?.debug?.(`${Lo} Resolved endpoint: ${Do(c)}`),c})(mu,{endpointParams:e,logger:t.logger})));Uo.aws=os;const vu=(wu=async(e,t,r)=>({operation:pe(t).operation,region:await fe(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 wu(e,t,r),i=pe(t)?.commandInstance?.constructor?.getEndpointParameterInstructions;if(!i)throw new Error(`getEndpointParameterInstructions() is not defined on \`${t.commandName}\``);const o=await Rs(r,{getEndpointParameterInstructions:i},e);return Object.assign(n,o)});var wu;function Su(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function ku(e){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}const Eu=((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 d;if(t!==c&&console.warn(`HttpAuthScheme has been normalized with lowercasing: \`${t}\` to \`${c}\``),"sigv4a"===c){d="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}\``);d="aws.auth#sigv4"}const u=r[d];if(!u)throw new Error(`Could not find HttpAuthOption create function for \`${d}\``);const l=u(n);l.schemeId=d,l.signingProperties={...l.signingProperties||{},...a,...i},s.push(l)}return s})(bu,(e=>{const t=[];return e.operation,t.push(Su(e)),t.push(ku(e)),t}),{"aws.auth#sigv4":Su,"aws.auth#sigv4a":ku}),xu=e=>{const t=(e=>(e.sigv4aSigningRegionSet=xe(e.sigv4aSigningRegionSet),e))(Lt(e));return{...t}},Au={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 Cu extends Mr{constructor(e){super(e),Object.setPrototypeOf(this,Cu.prototype)}}class Tu extends Cu{constructor(e){super({name:"NoSuchUpload",$fault:"client",...e}),this.name="NoSuchUpload",this.$fault="client",Object.setPrototypeOf(this,Tu.prototype)}}class Ru extends Cu{constructor(e){super({name:"ObjectNotInActiveTierError",$fault:"client",...e}),this.name="ObjectNotInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,Ru.prototype)}}class Ou extends Cu{constructor(e){super({name:"BucketAlreadyExists",$fault:"client",...e}),this.name="BucketAlreadyExists",this.$fault="client",Object.setPrototypeOf(this,Ou.prototype)}}class Pu extends Cu{constructor(e){super({name:"BucketAlreadyOwnedByYou",$fault:"client",...e}),this.name="BucketAlreadyOwnedByYou",this.$fault="client",Object.setPrototypeOf(this,Pu.prototype)}}class Iu extends Cu{constructor(e){super({name:"NoSuchBucket",$fault:"client",...e}),this.name="NoSuchBucket",this.$fault="client",Object.setPrototypeOf(this,Iu.prototype)}}var _u,Mu;!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])}(_u||(_u={})),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])}(Mu||(Mu={}));class Nu extends Cu{constructor(e){super({name:"InvalidObjectState",$fault:"client",...e}),this.name="InvalidObjectState",this.$fault="client",Object.setPrototypeOf(this,Nu.prototype),this.StorageClass=e.StorageClass,this.AccessTier=e.AccessTier}}class $u extends Cu{constructor(e){super({name:"NoSuchKey",$fault:"client",...e}),this.name="NoSuchKey",this.$fault="client",Object.setPrototypeOf(this,$u.prototype)}}class Fu extends Cu{constructor(e){super({name:"NotFound",$fault:"client",...e}),this.name="NotFound",this.$fault="client",Object.setPrototypeOf(this,Fu.prototype)}}const Uu=e=>({...e,...e.SecretAccessKey&&{SecretAccessKey:Vt},...e.SessionToken&&{SessionToken:Vt}}),Lu=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Vt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Vt},...e.Credentials&&{Credentials:Uu(e.Credentials)}}),Du=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Vt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Vt}}),Bu=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Vt}}),zu=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:Vt}});class ju extends Cu{constructor(e){super({name:"EncryptionTypeMismatch",$fault:"client",...e}),this.name="EncryptionTypeMismatch",this.$fault="client",Object.setPrototypeOf(this,ju.prototype)}}class qu extends Cu{constructor(e){super({name:"InvalidRequest",$fault:"client",...e}),this.name="InvalidRequest",this.$fault="client",Object.setPrototypeOf(this,qu.prototype)}}class Hu extends Cu{constructor(e){super({name:"InvalidWriteOffset",$fault:"client",...e}),this.name="InvalidWriteOffset",this.$fault="client",Object.setPrototypeOf(this,Hu.prototype)}}class Wu extends Cu{constructor(e){super({name:"TooManyParts",$fault:"client",...e}),this.name="TooManyParts",this.$fault="client",Object.setPrototypeOf(this,Wu.prototype)}}class Ku extends Cu{constructor(e){super({name:"ObjectAlreadyInActiveTierError",$fault:"client",...e}),this.name="ObjectAlreadyInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,Ku.prototype)}}var Vu;!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])}(Vu||(Vu={}));const Qu=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:Vt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Vt}}),Gu=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:Vt},...e.SSEKMSKeyId&&{SSEKMSKeyId:Vt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:Vt}}),Ju=async(e,t)=>{const r=et(e,t),n=Qr({},Wr,{[rf]:e[ep],[Tf]:e[tp],[Rf]:e[sp],[Pf]:e[op],[Of]:[()=>Wr(e[Nl]),()=>e[Nl].toString()]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=Qr({[Kp]:[,""]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Yu=async(e,t)=>{const r=et(e,t),n=Qr({},Wr,{[pf]:e[Ah],[Ef]:e[Vh],[Jp]:[()=>Wr(e[Ml]),()=>e[Ml].toString()],[sf]:e[nh],[Pp]:e[fh],[lf]:[()=>Wr(e[gh]),()=>gr(e[gh]).toString()],[hf]:[()=>Wr(e[mh]),()=>e[mh].toString()]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=Qr({[Df]:[,"DeleteObject"],[Qp]:[,e[lp]]});return r.m("DELETE").h(n).q(i).b(undefined),r.build()},Xu=async(e,t)=>{const r=et(e,t),n=Qr({},Wr,{[Pp]:e[fh],[Ip]:[()=>Wr(e[yh]),()=>gr(e[yh]).toString()],[_p]:e[bh],[Mp]:[()=>Wr(e[Sh]),()=>gr(e[Sh]).toString()],[Dp]:e[Lh],[If]:e[rp],[_f]:e[np],[Mf]:e[ip],[Ef]:e[Vh],[sf]:e[nh],[Zp]:e[Hl]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=Qr({[Df]:[,"GetObject"],[Bp]:[,e[Bh]],[zp]:[,e[zh]],[jp]:[,e[jh]],[qp]:[,e[qh]],[Hp]:[,e[Hh]],[Wp]:[()=>void 0!==e.ResponseExpires,()=>gr(e[Wh]).toString()],[Qp]:[,e[lp]],[Up]:[()=>void 0!==e.PartNumber,()=>e[Uh].toString()]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Zu=async(e,t)=>{const r=et(e,t),n=Qr({},Wr,{[Ef]:e[Vh],[sf]:e[nh],[vf]:[()=>Wr(e[Nh]),()=>(e[Nh]||[]).map(Zr).join(", ")]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=Qr({[$p]:[,"2"],[xp]:[,e[Zl]],[Cp]:[,e[oh]],[Fp]:[()=>void 0!==e.MaxKeys,()=>e[Ch].toString()],[Lp]:[,e[$h]],[Ep]:[,e[Yl]],[Op]:[()=>void 0!==e.FetchOwner,()=>e[ch].toString()],[Vp]:[,e[Yh]]});return r.m("GET").h(n).q(i).b(undefined),r.build()},el=async(e,t)=>{const r=et(e,t),n=Qr({},Wr,{[kp]:e[Jl]||"application/octet-stream",[Gp]:e[Ol],[gp]:e[Ul],[mp]:e[Bl],[yp]:e[zl],[bp]:e[jl],[vp]:[()=>Wr(e[ql]),()=>e[ql].toString()],[wp]:e[Wl],[Cf]:e[Fl],[Yp]:e[Ll],[Xp]:e[Dl],[ef]:e[Ql],[tf]:e[Gl],[Ap]:[()=>Wr(e[rh]),()=>gr(e[rh]).toString()],[Pp]:e[fh],[_p]:e[bh],[af]:e[dh],[cf]:e[uh],[df]:e[lh],[uf]:e[hh],[Uf]:[()=>Wr(e[hp]),()=>e[hp].toString()],[Tf]:e[tp],[Af]:e[Zh],[Lf]:e[pp],[If]:e[rp],[_f]:e[np],[Mf]:e[ip],[Rf]:e[sp],[Pf]:e[op],[Of]:[()=>Wr(e[Nl]),()=>e[Nl].toString()],[Ef]:e[Vh],[Nf]:e[dp],[yf]:e[_h],[bf]:[()=>Wr(e[Mh]),()=>{return(t=e[Mh],t.toISOString().replace(".000Z","Z")).toString();var t}],[mf]:e[Ih],[sf]:e[nh],...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=Qr({[Df]:[,"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()},tl=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return sl(e,t);const r=Qr({$metadata:Rl(e),[tp]:[,e.headers[Tf]],[sp]:[,e.headers[Rf]],[op]:[,e.headers[Pf]],[Nl]:[()=>void 0!==e.headers[Of],()=>Qt(e.headers[Of])]}),n=nr(ir(await wi(e.body,t)),"body");return null!=n[$l]&&(r[$l]=Tl(n[$l])),r},rl=async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return sl(e,t);const r=Qr({$metadata:Rl(e),[eh]:[()=>void 0!==e.headers[nf],()=>Qt(e.headers[nf])],[lp]:[,e.headers[Ff]],[Dh]:[,e.headers[kf]]});return await Xe(e.body,t),r},nl=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return sl(e,t);const r=Qr({$metadata:Rl(e),[eh]:[()=>void 0!==e.headers[nf],()=>Qt(e.headers[nf])],[Il]:[,e.headers[fp]],[ah]:[,e.headers[of]],[Jh]:[,e.headers[Sf]],[xh]:[()=>void 0!==e.headers[Np],()=>nr(Sr(e.headers[Np]))],[ql]:[()=>void 0!==e.headers[vp],()=>cr(e.headers[vp])],[sh]:[,e.headers[Tp]],[Ll]:[,e.headers[Yp]],[Dl]:[,e.headers[Xp]],[Ql]:[,e.headers[ef]],[Gl]:[,e.headers[tf]],[Th]:[()=>void 0!==e.headers[ff],()=>dr(e.headers[ff])],[lp]:[,e.headers[Ff]],[Ul]:[,e.headers[gp]],[Bl]:[,e.headers[mp]],[zl]:[,e.headers[yp]],[jl]:[,e.headers[bp]],[Vl]:[,e.headers[Sp]],[Jl]:[,e.headers[kp]],[rh]:[()=>void 0!==e.headers[Ap],()=>nr(Sr(e.headers[Ap]))],[ih]:[,e.headers[Rp]],[pp]:[,e.headers[Lf]],[tp]:[,e.headers[Tf]],[rp]:[,e.headers[If]],[ip]:[,e.headers[Mf]],[sp]:[,e.headers[Rf]],[Nl]:[()=>void 0!==e.headers[Of],()=>Qt(e.headers[Of])],[Zh]:[,e.headers[Af]],[Dh]:[,e.headers[kf]],[Qh]:[,e.headers[xf]],[Fh]:[()=>void 0!==e.headers[gf],()=>dr(e.headers[gf])],[up]:[()=>void 0!==e.headers[$f],()=>dr(e.headers[$f])],[_h]:[,e.headers[yf]],[Mh]:[()=>void 0!==e.headers[bf],()=>nr(yr(e.headers[bf]))],[Ih]:[,e.headers[mf]],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},il=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return sl(e,t);const r=Qr({$metadata:Rl(e),[Dh]:[,e.headers[kf]]}),n=nr(ir(await wi(e.body,t)),"body");return""===n.CommonPrefixes?r[Kl]=[]:null!=n[Kl]&&(r[Kl]=kl(qr(n[Kl]))),""===n.Contents?r[Xl]=[]:null!=n[Xl]&&(r[Xl]=xl(qr(n[Xl]))),null!=n[Yl]&&(r[Yl]=or(n[Yl])),null!=n[Zl]&&(r[Zl]=or(n[Zl])),null!=n[oh]&&(r[oh]=or(n[oh])),null!=n[wh]&&(r[wh]=Qt(n[wh])),null!=n[Eh]&&(r[Eh]=dr(n[Eh])),null!=n[Ch]&&(r[Ch]=dr(n[Ch])),null!=n[Rh]&&(r[Rh]=or(n[Rh])),null!=n[Oh]&&(r[Oh]=or(n[Oh])),null!=n[$h]&&(r[$h]=or(n[$h])),null!=n[Yh]&&(r[Yh]=or(n[Yh])),r},ol=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return sl(e,t);const r=Qr({$metadata:Rl(e),[ah]:[,e.headers[of]],[sh]:[,e.headers[Tp]],[Ll]:[,e.headers[Yp]],[Dl]:[,e.headers[Xp]],[Ql]:[,e.headers[ef]],[Gl]:[,e.headers[tf]],[tp]:[,e.headers[Tf]],[lp]:[,e.headers[Ff]],[rp]:[,e.headers[If]],[ip]:[,e.headers[Mf]],[sp]:[,e.headers[Rf]],[op]:[,e.headers[Pf]],[Nl]:[()=>void 0!==e.headers[Of],()=>Qt(e.headers[Of])],[cp]:[()=>void 0!==e.headers[wf],()=>cr(e.headers[wf])],[Dh]:[,e.headers[kf]]});return await Xe(e.body,t),r},sl=async(e,t)=>{const r={...e,body:await Si(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 yl(r,t);case"ObjectNotInActiveTierError":case"com.amazonaws.s3#ObjectNotInActiveTierError":throw await wl(r,t);case"BucketAlreadyExists":case"com.amazonaws.s3#BucketAlreadyExists":throw await dl(r,t);case"BucketAlreadyOwnedByYou":case"com.amazonaws.s3#BucketAlreadyOwnedByYou":throw await ul(r,t);case"NoSuchBucket":case"com.amazonaws.s3#NoSuchBucket":throw await gl(r,t);case"InvalidObjectState":case"com.amazonaws.s3#InvalidObjectState":throw await hl(r,t);case"NoSuchKey":case"com.amazonaws.s3#NoSuchKey":throw await ml(r,t);case"NotFound":case"com.amazonaws.s3#NotFound":throw await bl(r,t);case"EncryptionTypeMismatch":case"com.amazonaws.s3#EncryptionTypeMismatch":throw await ll(r,t);case"InvalidRequest":case"com.amazonaws.s3#InvalidRequest":throw await pl(r,t);case"InvalidWriteOffset":case"com.amazonaws.s3#InvalidWriteOffset":throw await fl(r,t);case"TooManyParts":case"com.amazonaws.s3#TooManyParts":throw await Sl(r,t);case"ObjectAlreadyInActiveTierError":case"com.amazonaws.s3#ObjectAlreadyInActiveTierError":throw await vl(r,t);default:const i=r.body;return al({output:e,parsedBody:i,errorCode:n})}},al=(cl=Cu,({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 Nr(s,t)})({output:e,parsedBody:t,exceptionCtor:cl,errorCode:r})});var cl;const dl=async(e,t)=>{const r=Qr({});e.body;const n=new Ou({$metadata:Rl(e),...r});return Nr(n,e.body)},ul=async(e,t)=>{const r=Qr({});e.body;const n=new Pu({$metadata:Rl(e),...r});return Nr(n,e.body)},ll=async(e,t)=>{const r=Qr({});e.body;const n=new ju({$metadata:Rl(e),...r});return Nr(n,e.body)},hl=async(e,t)=>{const r=Qr({}),n=e.body;null!=n[_l]&&(r[_l]=or(n[_l])),null!=n[Zh]&&(r[Zh]=or(n[Zh]));const i=new Nu({$metadata:Rl(e),...r});return Nr(i,e.body)},pl=async(e,t)=>{const r=Qr({});e.body;const n=new qu({$metadata:Rl(e),...r});return Nr(n,e.body)},fl=async(e,t)=>{const r=Qr({});e.body;const n=new Hu({$metadata:Rl(e),...r});return Nr(n,e.body)},gl=async(e,t)=>{const r=Qr({});e.body;const n=new Iu({$metadata:Rl(e),...r});return Nr(n,e.body)},ml=async(e,t)=>{const r=Qr({});e.body;const n=new $u({$metadata:Rl(e),...r});return Nr(n,e.body)},yl=async(e,t)=>{const r=Qr({});e.body;const n=new Tu({$metadata:Rl(e),...r});return Nr(n,e.body)},bl=async(e,t)=>{const r=Qr({});e.body;const n=new Fu({$metadata:Rl(e),...r});return Nr(n,e.body)},vl=async(e,t)=>{const r=Qr({});e.body;const n=new Ku({$metadata:Rl(e),...r});return Nr(n,e.body)},wl=async(e,t)=>{const r=Qr({});e.body;const n=new Ru({$metadata:Rl(e),...r});return Nr(n,e.body)},Sl=async(e,t)=>{const r=Qr({});e.body;const n=new Wu({$metadata:Rl(e),...r});return Nr(n,e.body)},kl=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>(e=>{const t={};return null!=e[$h]&&(t[$h]=or(e[$h])),t})(e))),El=(e,t)=>{const r={};return null!=e[kh]&&(r[kh]=or(e[kh])),null!=e[xh]&&(r[xh]=nr(yr(e[xh]))),null!=e[sh]&&(r[sh]=or(e[sh])),""===e.ChecksumAlgorithm?r[Fl]=[]:null!=e[Fl]&&(r[Fl]=(e=>(e||[]).filter((e=>null!=e)).map((e=>or(e))))(qr(e[Fl]))),null!=e[cp]&&(r[cp]=cr(e[cp])),null!=e[Zh]&&(r[Zh]=or(e[Zh])),null!=e[Ph]&&(r[Ph]=Al(e[Ph])),null!=e[Gh]&&(r[Gh]=Cl(e[Gh])),r},xl=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>El(e))),Al=(e,t)=>{const r={};return null!=e[th]&&(r[th]=or(e[th])),null!=e[ph]&&(r[ph]=or(e[ph])),r},Cl=(e,t)=>{const r={};return null!=e[vh]&&(r[vh]=Qt(e[vh])),null!=e[Kh]&&(r[Kh]=nr(yr(e[Kh]))),r},Tl=(e,t)=>{const r={};return null!=e[Pl]&&(r[Pl]=or(e[Pl])),null!=e[Xh]&&(r[Xh]=or(e[Xh])),null!=e[ap]&&(r[ap]=or(e[ap])),null!=e[ah]&&(r[ah]=nr(yr(e[ah]))),r},Rl=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"]}),Ol="ACL",Pl="AccessKeyId",Il="AcceptRanges",_l="AccessTier",Ml="BypassGovernanceRetention",Nl="BucketKeyEnabled",$l="Credentials",Fl="ChecksumAlgorithm",Ul="CacheControl",Ll="ChecksumCRC32",Dl="ChecksumCRC32C",Bl="ContentDisposition",zl="ContentEncoding",jl="ContentLanguage",ql="ContentLength",Hl="ChecksumMode",Wl="ContentMD5",Kl="CommonPrefixes",Vl="ContentRange",Ql="ChecksumSHA1",Gl="ChecksumSHA256",Jl="ContentType",Yl="ContinuationToken",Xl="Contents",Zl="Delimiter",eh="DeleteMarker",th="DisplayName",rh="Expires",nh="ExpectedBucketOwner",ih="ExpiresString",oh="EncodingType",sh="ETag",ah="Expiration",ch="FetchOwner",dh="GrantFullControl",uh="GrantRead",lh="GrantReadACP",hh="GrantWriteACP",ph="ID",fh="IfMatch",gh="IfMatchLastModifiedTime",mh="IfMatchSize",yh="IfModifiedSince",bh="IfNoneMatch",vh="IsRestoreInProgress",wh="IsTruncated",Sh="IfUnmodifiedSince",kh="Key",Eh="KeyCount",xh="LastModified",Ah="MFA",Ch="MaxKeys",Th="MissingMeta",Rh="Name",Oh="NextContinuationToken",Ph="Owner",Ih="ObjectLockLegalHoldStatus",_h="ObjectLockMode",Mh="ObjectLockRetainUntilDate",Nh="OptionalObjectAttributes",$h="Prefix",Fh="PartsCount",Uh="PartNumber",Lh="Range",Dh="RequestCharged",Bh="ResponseCacheControl",zh="ResponseContentDisposition",jh="ResponseContentEncoding",qh="ResponseContentLanguage",Hh="ResponseContentType",Wh="ResponseExpires",Kh="RestoreExpiryDate",Vh="RequestPayer",Qh="ReplicationStatus",Gh="RestoreStatus",Jh="Restore",Yh="StartAfter",Xh="SecretAccessKey",Zh="StorageClass",ep="SessionMode",tp="ServerSideEncryption",rp="SSECustomerAlgorithm",np="SSECustomerKey",ip="SSECustomerKeyMD5",op="SSEKMSEncryptionContext",sp="SSEKMSKeyId",ap="SessionToken",cp="Size",dp="Tagging",up="TagCount",lp="VersionId",hp="WriteOffsetBytes",pp="WebsiteRedirectLocation",fp="accept-ranges",gp="cache-control",mp="content-disposition",yp="content-encoding",bp="content-language",vp="content-length",wp="content-md5",Sp="content-range",kp="content-type",Ep="continuation-token",xp="delimiter",Ap="expires",Cp="encoding-type",Tp="etag",Rp="expiresstring",Op="fetch-owner",Pp="if-match",Ip="if-modified-since",_p="if-none-match",Mp="if-unmodified-since",Np="last-modified",$p="list-type",Fp="max-keys",Up="partNumber",Lp="prefix",Dp="range",Bp="response-cache-control",zp="response-content-disposition",jp="response-content-encoding",qp="response-content-language",Hp="response-content-type",Wp="response-expires",Kp="session",Vp="start-after",Qp="versionId",Gp="x-amz-acl",Jp="x-amz-bypass-governance-retention",Yp="x-amz-checksum-crc32",Xp="x-amz-checksum-crc32c",Zp="x-amz-checksum-mode",ef="x-amz-checksum-sha1",tf="x-amz-checksum-sha256",rf="x-amz-create-session-mode",nf="x-amz-delete-marker",of="x-amz-expiration",sf="x-amz-expected-bucket-owner",af="x-amz-grant-full-control",cf="x-amz-grant-read",df="x-amz-grant-read-acp",uf="x-amz-grant-write-acp",lf="x-amz-if-match-last-modified-time",hf="x-amz-if-match-size",pf="x-amz-mfa",ff="x-amz-missing-meta",gf="x-amz-mp-parts-count",mf="x-amz-object-lock-legal-hold",yf="x-amz-object-lock-mode",bf="x-amz-object-lock-retain-until-date",vf="x-amz-optional-object-attributes",wf="x-amz-object-size",Sf="x-amz-restore",kf="x-amz-request-charged",Ef="x-amz-request-payer",xf="x-amz-replication-status",Af="x-amz-storage-class",Cf="x-amz-sdk-checksum-algorithm",Tf="x-amz-server-side-encryption",Rf="x-amz-server-side-encryption-aws-kms-key-id",Of="x-amz-server-side-encryption-bucket-key-enabled",Pf="x-amz-server-side-encryption-context",If="x-amz-server-side-encryption-customer-algorithm",_f="x-amz-server-side-encryption-customer-key",Mf="x-amz-server-side-encryption-customer-key-md5",Nf="x-amz-tagging",$f="x-amz-tagging-count",Ff="x-amz-version-id",Uf="x-amz-write-offset-bytes",Lf="x-amz-website-redirect-location",Df="x-id";class Bf extends(Wt.classBuilder().ep({...Au,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(e,t,r,n){return[ve(r,this.serialize,this.deserialize),Is(r,e.getEndpointParameterInstructions()),Oo(r)]})).s("AmazonS3","CreateSession",{}).n("S3Client","CreateSessionCommand").f(Du,Lu).ser(Ju).de(tl).build()){}var zf="3.701.0";function jf(e){return"string"==typeof e?0===e.length:0===e.byteLength}var qf={name:"SHA-1"},Hf={name:"HMAC",hash:qf},Wf=new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]);const Kf={};function Vf(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:Kf}var Qf=function(){function e(e){this.toHash=new Uint8Array(0),void 0!==e&&(this.key=new Promise((function(t,r){Vf().crypto.subtle.importKey("raw",Gf(e),Hf,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))}return e.prototype.update=function(e){if(!jf(e)){var t=Gf(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 Vf().crypto.subtle.sign(Hf,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):jf(this.toHash)?Promise.resolve(Wf):Promise.resolve().then((function(){return Vf().crypto.subtle.digest(qf,e.toHash)})).then((function(e){return Promise.resolve(new Uint8Array(e))}))},e.prototype.reset=function(){this.toHash=new Uint8Array(0)},e}();function Gf(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 Jf=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function Yf(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&&Jf.every((function(t){return"function"==typeof e[t]}))}(e.crypto.subtle)}var Xf=function(){function e(e){if(!Yf(Vf()))throw new Error("SHA1 not supported");this.hash=new Qf(e)}return e.prototype.update=function(e,t){this.hash.update(Oi(e))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e}(),Zf={name:"SHA-256"},eg={name:"HMAC",hash:Zf},tg=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]),rg=function(){function e(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return e.prototype.update=function(e){if(!Pi(e)){var t=Oi(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 Vf().crypto.subtle.sign(eg,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):Pi(this.toHash)?Promise.resolve(tg):Promise.resolve().then((function(){return Vf().crypto.subtle.digest(Zf,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){Vf().crypto.subtle.importKey("raw",Oi(e.secret),eg,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))},e}();function ng(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 ig(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]cg)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;r>0;)this.buffer[this.bufferLength++]=e[t++],r--,this.bufferLength===og&&(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%og>=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],d=t[7],u=0;u>>17|l<<15)^(l>>>19|l<<13)^l>>>10,p=((l=this.temp[u-15])>>>7|l<<25)^(l>>>18|l<<14)^l>>>3;this.temp[u]=(h+this.temp[u-7]|0)+(p+this.temp[u-16]|0)}var f=(((s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7))+(s&a^~s&c)|0)+(d+(sg[u]+this.temp[u]|0)|0)|0,g=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&n^r&i^n&i)|0;d=c,c=a,a=s,s=o+f|0,o=i,i=n,n=r,r=f+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]+=d},e}(),ug=function(){function e(e){this.secret=e,this.hash=new dg,this.reset()}return e.prototype.update=function(e){if(!Pi(e)&&!this.error)try{this.hash.update(Oi(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 ng(this,void 0,void 0,(function(){return ig(this,(function(e){return[2,this.digestSync()]}))}))},e.prototype.reset=function(){if(this.hash=new dg,this.secret){this.outer=new dg;var e=function(e){var t=Oi(e);if(t.byteLength>og){var r=new dg;r.update(t),t=r.digest()}var n=new Uint8Array(og);return n.set(t),n}(this.secret),t=new Uint8Array(og);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 d=this.satisfies(r[c]);if(void 0!==d)return d}var u=a.default.find(s,(function(e){return t.isPlatform(e)}));if(u){var l=this.satisfies(r[u]);if(void 0!==l)return l}}if(o>0){var h=Object.keys(i),p=a.default.find(h,(function(e){return t.isBrowser(e,!0)}));if(void 0!==p)return this.compareVersion(i[p])}},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=d,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 pg=en(hg.exports);const fg=({serviceId:e,clientVersion:t})=>async r=>{const n="undefined"!=typeof window&&window?.navigator?.userAgent?pg.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 gg{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&&mg(t),new gg(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&mg(e),parseInt(He(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function mg(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}class yg{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 d=new Uint8Array(9);return d[0]=8,d.set(gg.fromNumber(e.value.valueOf()).bytes,1),d;case"uuid":if(!Rg.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const u=new Uint8Array(17);return u[0]=9,u.set(qe(e.value.replace(/\-/g,"")),1),u}}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 Di;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 Di).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 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.decoder.decode(e);yield t}}}class Ig{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 _g{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 Mg{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 Ng(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 $g{constructor({utf8Encoder:e,utf8Decoder:t}){this.eventStreamCodec=new Og(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 d=0;for(;d{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 Ug=e=>"function"==typeof ReadableStream&&e instanceof ReadableStream,Lg=e=>new Fg(e);const Dg=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()},Bg=64,zg=[1732584193,4023233417,2562383102,271733878];class jg{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 Re(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===Bg&&(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%Bg>=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=Hg(r,n,i,o,e.getUint32(0,!0),7,3614090360),o=Hg(o,r,n,i,e.getUint32(4,!0),12,3905402710),i=Hg(i,o,r,n,e.getUint32(8,!0),17,606105819),n=Hg(n,i,o,r,e.getUint32(12,!0),22,3250441966),r=Hg(r,n,i,o,e.getUint32(16,!0),7,4118548399),o=Hg(o,r,n,i,e.getUint32(20,!0),12,1200080426),i=Hg(i,o,r,n,e.getUint32(24,!0),17,2821735955),n=Hg(n,i,o,r,e.getUint32(28,!0),22,4249261313),r=Hg(r,n,i,o,e.getUint32(32,!0),7,1770035416),o=Hg(o,r,n,i,e.getUint32(36,!0),12,2336552879),i=Hg(i,o,r,n,e.getUint32(40,!0),17,4294925233),n=Hg(n,i,o,r,e.getUint32(44,!0),22,2304563134),r=Hg(r,n,i,o,e.getUint32(48,!0),7,1804603682),o=Hg(o,r,n,i,e.getUint32(52,!0),12,4254626195),i=Hg(i,o,r,n,e.getUint32(56,!0),17,2792965006),n=Hg(n,i,o,r,e.getUint32(60,!0),22,1236535329),r=Wg(r,n,i,o,e.getUint32(4,!0),5,4129170786),o=Wg(o,r,n,i,e.getUint32(24,!0),9,3225465664),i=Wg(i,o,r,n,e.getUint32(44,!0),14,643717713),n=Wg(n,i,o,r,e.getUint32(0,!0),20,3921069994),r=Wg(r,n,i,o,e.getUint32(20,!0),5,3593408605),o=Wg(o,r,n,i,e.getUint32(40,!0),9,38016083),i=Wg(i,o,r,n,e.getUint32(60,!0),14,3634488961),n=Wg(n,i,o,r,e.getUint32(16,!0),20,3889429448),r=Wg(r,n,i,o,e.getUint32(36,!0),5,568446438),o=Wg(o,r,n,i,e.getUint32(56,!0),9,3275163606),i=Wg(i,o,r,n,e.getUint32(12,!0),14,4107603335),n=Wg(n,i,o,r,e.getUint32(32,!0),20,1163531501),r=Wg(r,n,i,o,e.getUint32(52,!0),5,2850285829),o=Wg(o,r,n,i,e.getUint32(8,!0),9,4243563512),i=Wg(i,o,r,n,e.getUint32(28,!0),14,1735328473),n=Wg(n,i,o,r,e.getUint32(48,!0),20,2368359562),r=Kg(r,n,i,o,e.getUint32(20,!0),4,4294588738),o=Kg(o,r,n,i,e.getUint32(32,!0),11,2272392833),i=Kg(i,o,r,n,e.getUint32(44,!0),16,1839030562),n=Kg(n,i,o,r,e.getUint32(56,!0),23,4259657740),r=Kg(r,n,i,o,e.getUint32(4,!0),4,2763975236),o=Kg(o,r,n,i,e.getUint32(16,!0),11,1272893353),i=Kg(i,o,r,n,e.getUint32(28,!0),16,4139469664),n=Kg(n,i,o,r,e.getUint32(40,!0),23,3200236656),r=Kg(r,n,i,o,e.getUint32(52,!0),4,681279174),o=Kg(o,r,n,i,e.getUint32(0,!0),11,3936430074),i=Kg(i,o,r,n,e.getUint32(12,!0),16,3572445317),n=Kg(n,i,o,r,e.getUint32(24,!0),23,76029189),r=Kg(r,n,i,o,e.getUint32(36,!0),4,3654602809),o=Kg(o,r,n,i,e.getUint32(48,!0),11,3873151461),i=Kg(i,o,r,n,e.getUint32(60,!0),16,530742520),n=Kg(n,i,o,r,e.getUint32(8,!0),23,3299628645),r=Vg(r,n,i,o,e.getUint32(0,!0),6,4096336452),o=Vg(o,r,n,i,e.getUint32(28,!0),10,1126891415),i=Vg(i,o,r,n,e.getUint32(56,!0),15,2878612391),n=Vg(n,i,o,r,e.getUint32(20,!0),21,4237533241),r=Vg(r,n,i,o,e.getUint32(48,!0),6,1700485571),o=Vg(o,r,n,i,e.getUint32(12,!0),10,2399980690),i=Vg(i,o,r,n,e.getUint32(40,!0),15,4293915773),n=Vg(n,i,o,r,e.getUint32(4,!0),21,2240044497),r=Vg(r,n,i,o,e.getUint32(32,!0),6,1873313359),o=Vg(o,r,n,i,e.getUint32(60,!0),10,4264355552),i=Vg(i,o,r,n,e.getUint32(24,!0),15,2734768916),n=Vg(n,i,o,r,e.getUint32(52,!0),21,1309151649),r=Vg(r,n,i,o,e.getUint32(16,!0),6,4149444226),o=Vg(o,r,n,i,e.getUint32(44,!0),10,3174756917),i=Vg(i,o,r,n,e.getUint32(8,!0),15,718787259),n=Vg(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(zg),this.buffer=new DataView(new ArrayBuffer(Bg)),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}}function qg(e,t,r,n,i,o){return((t=(t+e&4294967295)+(n+o&4294967295)&4294967295)<>>32-i)+r&4294967295}function Hg(e,t,r,n,i,o,s){return qg(t&r|~t&n,e,t,i,o,s)}function Wg(e,t,r,n,i,o,s){return qg(t&n|r&~n,e,t,i,o,s)}function Kg(e,t,r,n,i,o,s){return qg(t^r^n,e,t,i,o,s)}function Vg(e,t,r,n,i,o,s){return qg(r^(t|~n),e,t,i,o,s)}const Qg="function"==typeof TextEncoder?new TextEncoder:null,Gg=e=>{if("string"==typeof e){if(Qg)return Qg.encode(e).byteLength;let t=e.length;for(let r=t-1;r>=0;r--){const n=e.charCodeAt(r);n>127&&n<=2047?t++:n>2047&&n<=65535&&(t+=2),n>=56320&&n<=57343&&r--}return t}if("number"==typeof e.byteLength)return e.byteLength;if("number"==typeof e.size)return e.size;throw new Error(`Body Length computation failed for ${e}`)},Jg=["in-region","cross-region","mobile","standard","legacy"],Yg=()=>{const e="undefined"!=typeof window&&window?.navigator?.userAgent?pg.parse(window.navigator.userAgent):void 0,t=e?.platform?.type;return"tablet"===t||"mobile"===t},Xg=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(Yg()?"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 ${Jg.join(", ")}, got ${t}`)}})))(e),r=()=>t().then(Fr),n=(e=>({apiVersion:"2006-03-01",base64Decoder:e?.base64Decoder??Te,base64Encoder:e?.base64Encoder??Ie,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??bu,extensions:e?.extensions??[],getAwsChunkedEncodingStream:e?.getAwsChunkedEncodingStream??Me,httpAuthSchemeProvider:e?.httpAuthSchemeProvider??Eu,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new le},{schemeId:"aws.auth#sigv4a",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4a"),signer:new he}],logger:e?.logger??new Vr,sdkStreamMixin:e?.sdkStreamMixin??Ve,serviceId:e?.serviceId??"S3",signerConstructor:e?.signerConstructor??ia,signingEscapePath:e?.signingEscapePath??!1,urlParser:e?.urlParser??Cs,useArnRegion:e?.useArnRegion??!1,utf8Decoder:e?.utf8Decoder??Re,utf8Encoder:e?.utf8Encoder??Pe}))(e);return{...n,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??Gg,credentialDefaultProvider:e?.credentialDefaultProvider??(e=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??fg({serviceId:n.serviceId,clientVersion:zf}),eventStreamSerdeProvider:e?.eventStreamSerdeProvider??Lg,maxAttempts:e?.maxAttempts??3,md5:e?.md5??jg,region:e?.region??(i="Region is missing",()=>Promise.reject(i)),requestHandler:De.create(e?.requestHandler??r),retryMode:e?.retryMode??(async()=>(await r()).retryMode||Ms),sha1:e?.sha1??Xf,sha256:e?.sha256??lg,streamCollector:e?.streamCollector??Be,streamHasher:e?.streamHasher??Dg,useDualstackEndpoint:e?.useDualstackEndpoint??(()=>Promise.resolve(false)),useFipsEndpoint:e?.useFipsEndpoint??(()=>Promise.resolve(false))};var i},Zg=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}},em=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}},tm=e=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()});class rm extends Ht{constructor(...[e]){const t=Xg(e||{});var r;const n=function(e){const t=xe(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()=>Ts(await fe(r)()):void 0,i=!!r,o={...e,endpoint:n,tls:t,isCustomEndpoint:i,useDualstackEndpoint:fe(e.useDualstackEndpoint??!1),useFipsEndpoint:fe(e.useFipsEndpoint??!1)};let s;return o.serviceConfiguredEndpoint=async()=>(e.serviceId&&!s&&(s=As(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 gs(t);const e=await t();return gs(e)},useFipsEndpoint:async()=>{const e="string"==typeof t?t:await t();return!!fs(e)||("function"!=typeof r?Promise.resolve(!!r):r())}}})((e=>{const{retryStrategy:t}=e,r=fe(e.maxAttempts??3);return{...e,maxAttempts:r,retryStrategy:async()=>t||(await fe(e.retryMode)()===_s.ADAPTIVE?new qs(r):new js(r))}})((i=n,{...i,requestChecksumCalculation:fe(i.requestChecksumCalculation??X),responseChecksumValidation:fe(i.responseChecksumValidation??Z)}))))),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 po((async e=>r().send(new n({Bucket:e,SessionMode:"ReadWrite"})))),bucketEndpoint:e.bucketEndpoint??!1}})(xu(o),{session:[()=>this,Bf]}),a=((e,t)=>{const r={...Zg(e),...zr(e),...L(e),...em(e)};return t.forEach((e=>e.configure(r))),{...e,...(i=r,{region:i.region()}),...jr(r),...(n=r,{httpHandler:n.httpHandler()}),...tm(r)};var n,i})(s,e?.extensions||[]);super(a),this.config=a,this.middlewareStack.use((e=>({applyToStack:t=>{t.add(ls(e),ps)}}))(this.config)),this.middlewareStack.use(ta(this.config)),this.middlewareStack.use(bs(this.config)),this.middlewareStack.use(Xi(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:d}=a,u=c??t.inputFilterSensitiveLog,l=d??t.outputFilterSensitiveLog,{$metadata:h,...p}=n.output;return s?.info?.({clientName:i,commandName:o,input:u(r.input),output:l(p),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}}),Zi)}})),this.middlewareStack.use(ro(this.config)),this.middlewareStack.use(((e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(ge(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r}),me)}}))(this.config,{httpAuthSchemeParametersProvider:vu,identityProviderConfigProvider:async e=>new rt({"aws.auth#sigv4":e.credentials,"aws.auth#sigv4a":e.credentials})})),this.middlewareStack.use(Ee(this.config)),this.middlewareStack.use(_o(this.config)),this.middlewareStack.use(J(this.config)),this.middlewareStack.use(ao(this.config)),this.middlewareStack.use(So(this.config)),this.middlewareStack.use((e=>({applyToStack:t=>{t.addRelativeTo(xo(e),ke)}}))(this.config))}destroy(){super.destroy()}}const nm={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0},im=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?om(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})}),nm)}});function om(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 sm extends(Wt.classBuilder().ep({...Au,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[ve(r,this.serialize,this.deserialize),Is(r,e.getEndpointParameterInstructions()),Oo(r)]})).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").f(void 0,void 0).ser(Yu).de(rl).build()){}class am extends(Wt.classBuilder().ep({...Au,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[ve(r,this.serialize,this.deserialize),Is(r,e.getEndpointParameterInstructions()),Ji(r,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC32","CRC32C","SHA256","SHA1"]}),im(r),uo()]})).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").f(zu,Bu).ser(Xu).de(nl).build()){}class cm extends(Wt.classBuilder().ep({...Au,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(e,t,r,n){return[ve(r,this.serialize,this.deserialize),Is(r,e.getEndpointParameterInstructions()),Oo(r)]})).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").f(void 0,void 0).ser(Zu).de(il).build()){}class dm extends(Wt.classBuilder().ep({...Au,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[ve(r,this.serialize,this.deserialize),Is(r,e.getEndpointParameterInstructions()),Ji(r,{requestAlgorithmMember:"ChecksumAlgorithm",requestAlgorithmMemberHttpHeader:"x-amz-sdk-checksum-algorithm",requestChecksumRequired:!1}),io(),Oo(r),im(r)]})).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").f(Gu,Qu).ser(el).de(ol).build()){}class um{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)))}}))}shouldUsePathStyle(){try{if(this.config.forcePathStyle&&"no"!==this.config.forcePathStyle)return!0;let e=this.config.endpoint;const t=new URL(e),r=t.hostname,n=/^(\d{1,3}\.){3}\d{1,3}$/.test(r),i=""!==t.port;return!n&&i}catch(e){return!0}}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 rm({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o},forcePathStyle:this.shouldUsePathStyle()});try{let e,t=[],r=[],i=!0;for(;i;){const o=yield c.send(new cm({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:""})})),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 rm({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o},forcePathStyle:this.shouldUsePathStyle()});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield a.send(new sm({Bucket:n,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class lm extends um{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 rm({endpoint:r,region:n,credentials:{accessKeyId:o,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle()});a=a&&"KoodoReader"===this.baseFolder?a:this.baseFolder;let d=a+"/"+t;for(;d.startsWith("/");)d=d.substring(1);try{let t=yield c.send(new dm({Bucket:i,Key:d,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 rm({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o},forcePathStyle:this.shouldUsePathStyle()});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{const e=yield a.send(new am({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 hm{constructor(e){this.config=e,this.taskQueue=new f(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=1){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=this.config.access_token;let n=this.baseFolder;t&&""!==t.trim()&&(n=n+"/"+t),n=n.replace(/\/+/g,"/"),n.startsWith("/")&&(n=n.substring(1));let i=[],o=0;const s=1e3;for(;;){const t=yield e.get("https://pan.baidu.com/rest/2.0/xpan/file",{params:{method:"list",access_token:r,dir:"/"+n,start:o,limit:s,order:"name",desc:0,web:1,folder:0},headers:{"User-Agent":"pan.baidu.com"}});if(t.status>=300||0!==t.data.errno){console.error("百度网盘API错误:",t.data);break}const a=t.data.list||[];if(0===a.length)break;if(i=i.concat(a),a.length({name:e.server_filename,size:e.size||0,type:e.isdir?"folder":"file",modified:new Date(1e3*e.server_mtime).toISOString(),path:e.path,fs_id:e.fs_id})))}catch(e){return console.error("获取百度网盘文件列表时发生错误:",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=this.config.access_token;let n=this.baseFolder+"/"+t;n=n.replace(/\/+/g,"/"),n.startsWith("/")&&(n=n.substring(1));const i=new URLSearchParams({async:"0",filelist:JSON.stringify(["/"+n])}),o=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=${r}&opera=delete`,i.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==o.data.errno)return console.error("百度网盘删除文件API错误:",o.data),-9===o.data.errno?console.error("文件不存在"):111===o.data.errno?console.error("有其他异步任务正在执行"):-7===o.data.errno&&console.error("文件名非法"),!1;const s=o.data.info||[];for(const e of s)if(0!==e.errno)return console.error(`文件删除失败: ${e.path}, 错误码: ${e.errno}`),!1;return!0}catch(e){return console.error("删除文件时发生错误:",e),!1}}))}getAuthUrl(e){return`https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=${y.duboxClientId}&redirect_uri=${e}&scope=basic,netdisk&device_id=119827642&display=page&qrcode=1`}}class pm extends hm{constructor(e){super(e)}uploadFile(e,t){return a(this,void 0,void 0,(function*(){return!0}))}downloadFile(e){return a(this,void 0,void 0,(function*(){return!1}))}}class fm{constructor(e){this.baseUrl="https://proapi.115.com",this.config=e,this.taskQueue=new f(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=1){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)))}}))}getUploadCredentials(t){return a(this,void 0,void 0,(function*(){try{const r=yield e.get(`${this.baseUrl}/open/upload/get_token`,{headers:{Authorization:`Bearer ${t}`}});return r.status>=300||!r.data.state?(console.error("Error getting upload credentials:",r.data),null):r.data.data}catch(e){return console.error("Error occurred during get upload credentials:",e),null}}))}generateOSSPolicy(e,t,r=new Date(Date.now()+36e5)){const n={expiration:r.toISOString(),conditions:[{bucket:e},{key:t},["starts-with","$success_action_status","2"],["content-length-range",0,1073741824]]};return JSON.stringify(n)}getAuthUrl(e){return`https://passportapi.115.com/open/authorize?client_id=${y.yiyiwuClientId}&response_type=code&redirect_uri=${e}`}}class gm extends fm{constructor(e){super(e)}uploadFile(e,t){return a(this,void 0,void 0,(function*(){return!0}))}downloadFile(e){return a(this,void 0,void 0,(function*(){return!1}))}}class mm{constructor(e){let{username:t,password:r,url:n,dir:i,AuthType:o,createClient:s}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,i=i&&"KoodoReader"===this.baseFolder?i:this.baseFolder,this.username=t,this.password=r,this.url=n,this.dir=i,this.taskQueue=new f(5),this.AuthType=o,this.createClient=s}getClient(){return a(this,void 0,void 0,(function*(){return this.webdavClient||(this.url=yield this.handleUrlRedirection(this.url),this.webdavClient=this.createClient(this.url,{authType:this.AuthType.Password,username:this.username,password:this.password})),this.webdavClient}))}handleUrlRedirection(t){return a(this,void 0,void 0,(function*(){try{const r=yield e.head(t,{maxRedirects:0,validateStatus:()=>!0});return r.request&&r.request.responseURL&&r.request.responseURL!==t?r.request.responseURL:r.status>=300&&r.status<400&&r.headers.location?r.headers.location:t}catch(e){return console.info("Error handling URL redirection:",e),t}}))}retryOperation(e,t=1){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*(){const t=yield this.getClient();try{return(yield t.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(r){return r.response&&404===r.response.status&&(yield t.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",r),[]}}))}deleteFile(e){return a(this,void 0,void 0,(function*(){const t=yield this.getClient();try{return yield t.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(e){return a(this,void 0,void 0,(function*(){let t=yield this.getClient();try{const r=e.replace(/^\/+|\/+$/g,"").split("/").filter((e=>e.length>0));let n="";for(const e of r)n=n?`${n}/${e}`:e,(yield t.exists(`/${n}`))||(yield t.createDirectory(`/${n}`));return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}}class ym extends mm{constructor(e){super(Object.assign(Object.assign({},e),{AuthType:n,createClient:i}))}retryOperation(e,t=1){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{let n=this.dir+"/"+r,i=yield this.getClient();const o=i.exists(n.substring(0,n.lastIndexOf("/"))),s=new Promise(((e,t)=>{setTimeout((()=>t(new Error("WebDAV exists check timeout"))),5e3)}));!1===(yield Promise.race([o,s]))&&(yield this.ensureDirectoryExists(n.substring(0,n.lastIndexOf("/"))));let a=r.split("/").pop()||"",c=new File([t],a,{lastModified:(new Date).getTime(),type:t.type}),d=i.getFileUploadLink(this.dir+"/"+r);const u=new URL(d);u.search="",d=u.toString();const l=btoa(this.username+":"+this.password),h=yield e.put(d,c,{headers:{Authorization:"Basic "+l},maxContentLength:1/0,maxBodyLength:1/0});return!(h.status>=300)||(console.error("Error occurred during file upload:",h),!1)}catch(e){return console.error("Error 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}}))))))}))}}class bm{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.taskQueue=new f(3)}retryOperation(e,t=1){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 vm extends bm{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=this.listFiles("");const s=new Promise(((e,t)=>{setTimeout((()=>t(new Error("Docker connection timeout"))),5e3)}));yield Promise.race([o,s]);let a=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const c=new FormData;c.append("file",a);const d=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(i)}`,c,{headers:{Authorization:this.getAuthHeader(),"Content-Type":"multipart/form-data"},maxContentLength:1/0,maxBodyLength:1/0});return!(d.status>=300)||(console.error("Error occurred during file upload:",d),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return 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 wm=["book","config","cover","font"];class Sm{constructor(e,t){this.type=e,this.remote="dropbox"===e?new C(t):"microsoft"===e?new N(t):"google"===e?new P(t):"microsoft_exp"===e?new N(Object.assign(Object.assign({},t),{isExp:!0})):"google_exp"===e?new P(Object.assign(Object.assign({},t),{isExp:!0})):"s3compatible"===e?new lm(t):"webdav"===e?new ym(t):"docker"===e?new vm(t):"boxnet"===e?new x(t):"mega"===e?new _(t):"adrive"===e?new k(t):"pcloud"===e?new U(t):"dubox"===e?new pm(t):"yandex"===e?new R(t):"yiyiwu"===e?new gm(t):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 0===r.size||(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 wm){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,e)}}))}getAuthUrl(e){return this.remote.getAuthUrl?this.remote.getAuthUrl(e):""}getStats(){return this.remote.taskQueue.getStats()}clearQueue(){return this.remote.taskQueue.clearQueue()}resetCounters(){this.remote.taskQueue.resetCounters()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const km={words:['ALTER TABLE words ADD COLUMN "sentence" text']},Em={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 = ?"},xm={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},Am={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"},Cm={createTableStatement:Tm({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 "sentence" text,\n "chapter" text\n );\n '}),migrateStatement:Tm(km),getAllStatement:Tm({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),getPagedStatement:Tm({notes:"SELECT * FROM notes LIMIT ? OFFSET ?",bookmarks:"SELECT * FROM bookmarks LIMIT ? OFFSET ?",books:"SELECT * FROM books LIMIT ? OFFSET ?",plugins:"SELECT * FROM plugins LIMIT ? OFFSET ?",words:"SELECT * FROM words LIMIT ? OFFSET ?"}),getCountStatement:Tm({notes:"SELECT COUNT(*) as count FROM notes",bookmarks:"SELECT COUNT(*) as count FROM bookmarks",books:"SELECT COUNT(*) as count FROM books",plugins:"SELECT COUNT(*) as count FROM plugins",words:"SELECT COUNT(*) as count FROM words"}),saveStatement:Tm({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, sentence, chapter) VALUES (@key, @bookKey, @date, @word, @sentence, @chapter)"}),deleteAllStatement:Tm({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:Tm({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, sentence = @sentence, chapter = @chapter WHERE key = @key"}),deleteStatement:Tm({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:Tm({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:Tm(Em),getByBookKeyStatement:Tm(xm),getByBookKeysStatement:Tm({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(",")})`}),getKeysStatement:Tm({notes:"SELECT key FROM notes",bookmarks:"SELECT key FROM bookmarks",books:"SELECT key FROM books",plugins:"SELECT key FROM plugins",words:"SELECT key FROM words"}),getWithSortAndPageStatement:Tm({notes:(e,t,r,n)=>`SELECT * FROM notes ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${n}`,bookmarks:(e,t,r,n)=>`SELECT * FROM bookmarks ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${n}`,books:(e,t,r,n)=>`SELECT * FROM books ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${n}`,plugins:(e,t,r,n)=>`SELECT * FROM plugins ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${n}`,words:(e,t,r,n)=>`SELECT * FROM words ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${n}`}),getByKeysStatement:Tm({notes:e=>`SELECT * FROM notes WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,bookmarks:e=>`SELECT * FROM bookmarks WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,plugins:e=>`SELECT * FROM plugins WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,words:e=>`SELECT * FROM words WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`}),deleteByBookKeyStatement:Tm(Am)};function Tm(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const Rm={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),void 0===t.sentence&&(t.sentence=""),t}};var Om={sqlStatement:Cm,jsonToSqlite:Tm({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),void 0===t.sentence&&(t.sentence=""),t}}),sqliteToJson:Tm(Rm)};const Pm=m.cloudUrl,Im=m.cloudCNUrl;class _m{constructor(e,t,r){this.TokenService=e,this.ConfigService=t,this.baseUrl="china"===r?Im:Pm,this.serverRegion=r,this.refreshToken="",this.accessToken="",this.streamPromise=null,this.expiresAt=0}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),yield this.TokenService.setToken("expires_at",(1e3*t.data.expires_at).toString()),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token,this.expiresAt=1e3*t.data.expires_at),t}))}requestWithRetry(e){return a(this,void 0,void 0,(function*(){return _m.requestQueue||(_m.requestQueue=[]),new Promise(((t,r)=>{_m.requestQueue.push({config:e,resolve:t,reject:r}),_m.processingQueue||this.processQueue()}))}))}isTokenValid(){return a(this,void 0,void 0,(function*(){if(this.accessToken||(this.accessToken=(yield this.TokenService.getToken("access_token"))||""),!this.expiresAt){const e=yield this.TokenService.getToken("expires_at");this.expiresAt=e?parseInt(e):(new Date).getTime()+31536e9}return""!==this.accessToken&&this.expiresAt>(new Date).getTime()+6e4}))}processQueue(){return a(this,void 0,void 0,(function*(){if(!_m.processingQueue){_m.processingQueue=!0;try{for(;_m.requestQueue.length>0;){const e=_m.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{_m.processingQueue=!1}}}))}executeRequest(t){return a(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());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&&console.error("Request error:",n),n}catch(e){return console.error("Request execution error:",e),"Network Error"===e.message?{code:503,message:"network error",data:null,msg:"Network error, please try again later. 网络错误,请稍后再试。"}:{code:500,message:e.message||"Unknown error",msg:e.message||"Unknown 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{(yield this.isTokenValid())||(yield this.refreshUserToken());let n=this.accessToken||"",i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((o,s)=>{let c=this.ConfigService.getItem("appVersion"),d=this.ConfigService.getItem("appPlatform");const u=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":d||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});u.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),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(),o(r)):t(r.data)})))),u.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);o(t),u.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{(yield this.isTokenValid())||(yield this.refreshUserToken());let r=this.accessToken||"",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 d=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"});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(),i(r)):t(r.data)})))),d.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),d.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const t=JSON.parse(e.data);i(t),d.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}_m.processingQueue=!1,_m.requestQueue=[];class Mm extends _m{constructor(e,t,r){super(e,t,r)}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)}))}getBatchTrans(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_batch_trans",data:e};return yield this.requestWithRetry(t)}))}getSplitSentence(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_split_sentence",data:e};return yield this.requestWithRetry(t)}))}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)}))}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)}))}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)}))}getDictionaryStream(e,t,r){return a(this,void 0,void 0,(function*(){const n={method:"post",url:"/api/v1/pro/reader/get_llm_dict_stream",data:e};return yield this.requestWithStream(n,t,r)}))}getDictionaryFetch(e,t){return a(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_dict_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)}))}detectLanguage(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/detect_language",data:e};return yield this.requestWithRetry(t)}))}getTTSAudio(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_tts_audio",data:e};return yield this.executeRequest(t)}))}getOcrResult(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_ocr_result",data:e};return yield this.requestWithRetry(t)}))}analyzeText(e){return a(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/analyze_text",data:e};return yield this.requestWithRetry(t)}))}}class Nm extends _m{constructor(e,t,r){super(e,t,r),this.serverRegion=r}encryptToken(e){return a(this,void 0,void 0,(function*(){let t=e.token,r=p.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&&n.data&&n.data.token){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 n="";if("github"===e?n=`https://github.com/login/oauth/authorize?client_id=${y.githubClientId}&redirect_uri=${r}&scope=${b.github.scopes.join(" ")}&response_type=code`:"google"===e?n=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${r}&prompt=consent&response_type=code&client_id=${y.googleClientId}&scope=${b.google.scopes.join(" ")}&access_type=offline`:"facebook"===e?n=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${y.facebookClientId}&redirect_uri=${r}&scope=&response_type=code`:"microsoft"===e&&(n=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${y.microsoftClientId}&scope=${b.microsoft.scopes.join(" ")}&response_type=code&redirect_uri=${r}`),"manual"===t)return n;let i=JSON.stringify({deeplink:"desktop"===t?"koodo-reader://callback":"browser"===t?`${y.callbackUrl}#/login`:"",service:e});return`${n}&state=${"state|"+encodeURIComponent(i)}`}};class Um{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"))),d=Object.keys(t).filter((e=>e.startsWith("database.sqlite.notes"))),u=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"))),p={books:Array.from(new Set(n.concat(c))),notes:Array.from(new Set(i.concat(d))),bookmarks:Array.from(new Set(o.concat(u))),plugins:Array.from(new Set(s.concat(l))),words:Array.from(new Set(a.concat(h)))},f={books:{save:[],update:[],delete:[],conflict:[],upload:[]},notes:{save:[],update:[],delete:[],conflict:[],upload:[]},bookmarks:{save:[],update:[],delete:[],conflict:[],upload:[]},plugins:{save:[],update:[],delete:[],conflict:[],upload:[]},words:{save:[],update:[],delete:[],conflict:[],upload:[]}},g=["books","notes","bookmarks","plugins","words"];for(let n of g)for(let i of p[n]){let o=i.split(".")[3],s=e[i],a=t[i];s?a?("save"===a.operation&&("update"!==s.operation&&"delete"!==s.operation||f[n].upload.push(o)),"delete"===a.operation&&("save"===s.operation&&(f[n].delete.push(o),e[i]=a),"update"===s.operation&&(s.timea.time&&(f[n].conflict.push(o),"cloud"===r?(f[n].delete.push(o),e[i]=a):f[n].upload.push(o))),s.operation),"update"===a.operation&&("save"===s.operation&&(f[n].update.push(o),e[i]=a),"update"===s.operation&&(s.timea.time&&f[n].upload.push(o)),"delete"===s.operation&&(s.timea.time&&f[n].upload.push(o)))):f[n].upload.push(o):(f[n].save.push(o),e[i]=a)}return{compareResult:f,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"))),d=Object.keys(t).filter((e=>e.startsWith("config.objectConfig"))),u=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(d))),mapConfig:Array.from(new Set(s.concat(u)))},h={readerConfig:{update:[],upload:[]},listConfig:{update:[],upload:[]},objectConfig:{update:[],delete:[],conflict:[],save:[],upload:[]},mapConfig:{update:[],delete:[],conflict:[],save:[],upload:[]}},p=["readerConfig","listConfig"];for(let r of p)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):h[r].upload.push(i):(h[r].update.push(i),e[n]=s)}let f=["objectConfig","mapConfig"];for(let n of f)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))),s.operation),"update"===a.operation&&("update"===s.operation&&(s.timea.time&&h[n].upload.push(o)),"delete"===s.operation&&(s.timea.time&&h[n].upload.push(o)))):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:d}=yield this.CompareConfig(a,t,o),u=Object.assign(Object.assign({},s),c);return r.setAllSyncRecord(d),"local"===o&&(u.books.conflict.length>0||u.notes.conflict.length>0||u.bookmarks.conflict.length>0||u.plugins.conflict.length>0||u.words.conflict.length>0||u.objectConfig.conflict.length>0||u.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"),u}))}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,o,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,o){return a(this,void 0,void 0,(function*(){let s=[];for(let t of d){if(e[t].save.length+e[t].update.length>0){let n=yield o.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 o of e[t].delete)"books"===t&&(yield n.deleteOfflineBook(o),yield i.deleteOfflineCover(o)),yield r.deleteRecord(o,t);yield r.dumpDatabase(t,!0)}if(e.readerConfig.update.length>0||e.listConfig.update.length>0||e.objectConfig.update.length>0||e.mapConfig.update.length>0){let r=yield o.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 d)e[t].upload.length>0&&s.push((()=>o.uploadDatabase(t)));return s.push((()=>o.uploadConfig("config"))),s.push((()=>o.uploadConfig("sync"))),s}))}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()}))}}class Lm{constructor(e,t){this.bookKey="",this.sessionStart=0,this.unregisterUnload=null,this.configService=e,this.platform=t}getDailySeconds(e,t){const r=((this.configService.getAllMapConfig("readingStats")||{})[t]||[]).find((t=>t.startsWith(e+"-")));if(!r)return 0;const n=r.split("-");return parseInt(n[n.length-1],10)||0}setDailySeconds(e,t,r){const n=(this.configService.getAllMapConfig("readingStats")||{})[t]||[],i=`${e}-${r}`,o=n.filter((t=>!t.startsWith(e+"-")));this.configService.setOneMapConfig(t,[...o,i],"readingStats")}start(e){this.bookKey=e,this.sessionStart=Date.now(),this.unregisterUnload=this.platform.registerUnloadHandler((()=>{var e,t;this.commit(),null===(t=(e=this.platform).onBeforeClose)||void 0===t||t.call(e)}))}stop(){var e;this.commit(),null===(e=this.unregisterUnload)||void 0===e||e.call(this),this.unregisterUnload=null,this.bookKey="",this.sessionStart=0}commit(){if(!this.bookKey||!this.sessionStart)return;const e=Date.now()-this.sessionStart;if(e<1e3)return void(this.sessionStart=0);const t=Math.round(e/1e3);this.sessionStart=0;const r=this.configService.getObjectConfig(this.bookKey,"readingTime",0);this.configService.setObjectConfig(this.bookKey,r+t,"readingTime");const n=function(){const e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}(),i=this.getDailySeconds(this.bookKey,n);this.setDailySeconds(this.bookKey,n,i+t)}getTotalSeconds(e){return this.configService.getObjectConfig(e,"readingTime",0)}getDailySecondsForBook(e,t){return this.getDailySeconds(e,t)}getDayStats(e){return((this.configService.getAllMapConfig("readingStats")||{})[e]||[]).map((e=>{const t=e.lastIndexOf("-");return{bookKey:e.substring(0,t),seconds:parseInt(e.substring(t+1),10)||0}}))}getAllDates(){const e=this.configService.getAllMapConfig("readingStats");return Object.keys(e||{})}}const Dm=(Bm=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,t){localStorage.setItem(e,t)}static removeItem(e){localStorage.removeItem(e)}},zm="browser",(jm=class extends Bm{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:zm,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 flushSyncRecords(){if(0===Object.keys(this.pendingSyncRecords).length)return;let e=JSON.parse(this.getItem("syncRecord")||"{}");Object.assign(e,this.pendingSyncRecords),this.setItem("syncRecord",JSON.stringify(e)),this.pendingSyncRecords={},this.syncRecordTimer=null}static setSyncRecord(e,t){const r=e.type+"."+e.catergory+"."+e.name+"."+e.key;this.pendingSyncRecords[r]=t,null!==this.syncRecordTimer&&clearTimeout(this.syncRecordTimer),this.syncRecordTimer=setTimeout((()=>{this.flushSyncRecords()}),this.DEBOUNCE_DELAY)}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}}).pendingSyncRecords={},jm.syncRecordTimer=null,jm.DEBOUNCE_DELAY=1e3,jm);var Bm,zm,jm;class qm{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 Km(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=Hm((new TextEncoder).encode(JSON.stringify(r))),i=Hm((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}.${Hm(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"child_database"===e.type));if(!n)throw new Error(`No child database found in page ${t}. Please provide a Database ID directly.`);return n.id}))}findOrCreatePage(e,t,r){return a(this,void 0,void 0,(function*(){const n=`${r}`,i=yield fetch(`https://api.notion.com/v1/databases/${t}/query`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({filter:{property:"title",title:{equals:n}}})});if(!i.ok){const n=yield i.json().catch((()=>({})));if(400===i.status&&"validation_error"===(null==n?void 0:n.code)&&"string"==typeof(null==n?void 0:n.message)&&n.message.includes("is a page, not a database")){const n=yield this.resolveDatabaseId(e,t);return this.findOrCreatePage(e,n,r)}throw new Error(`Notion API error: ${i.status} ${i.statusText}`)}const o=yield i.json();if(o.results&&o.results.length>0)return o.results[0].id;const s=yield fetch("https://api.notion.com/v1/pages",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({parent:{database_id:t},properties:{title:{title:[{text:{content:n}}]}}})});if(!s.ok)throw new Error(`Notion create page error: ${s.status} ${s.statusText}`);return(yield s.json()).id}))}appendBlocks(e,t,r,n){return a(this,void 0,void 0,(function*(){const i=!r.notes||0===r.notes.length,o=[];o.push({object:"block",type:"divider",divider:{}}),n&&o.push({object:"block",type:"heading_3",heading_3:{rich_text:[{type:"text",text:{content:n}}]}}),o.push({object:"block",type:"quote",quote:{rich_text:[{type:"text",text:{content:r.text||""}}]}}),!i&&r.notes&&o.push({object:"block",type:"paragraph",paragraph:{rich_text:[{type:"text",text:{content:`📝 ${r.notes}`}}]}});const s=`${r.date.year}-${String(r.date.month).padStart(2,"0")}-${String(r.date.day).padStart(2,"0")}`;o.push({object:"block",type:"paragraph",paragraph:{rich_text:[{type:"text",text:{content:`Added on ${s}`},annotations:{italic:!0,color:"gray"}}]}});const a=yield fetch(`https://api.notion.com/v1/blocks/${t}/children`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","Notion-Version":"2022-06-28"},body:JSON.stringify({children:o})});if(!a.ok)throw new Error(`Notion append blocks error: ${a.status} ${a.statusText}`)}))}syncNote(e,t){return a(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const r=this.getConfig();if(!r)return!1;try{const n=yield this.findOrCreatePage(r.token,r.databaseId,t);return yield this.appendBlocks(r.token,n,e,e.chapter||""),!0}catch(e){return console.error("Notion sync failed:",e),!1}}))}}class Qm{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("yuqueSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?null:e}catch(e){return null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableYuqueSync")}findOrCreateDoc(e,t,r){return a(this,void 0,void 0,(function*(){const n=`${r}`,i=`koodo-reader-${r.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g,"-").replace(/-+/g,"-").toLowerCase().substring(0,50)}`;try{const r=yield fetch(`${Qm.API_BASE}/repos/${t}/docs/${i}`,{method:"GET",headers:{"X-Auth-Token":e,"Content-Type":"application/json"}});if(r.ok){const e=yield r.json();return{id:e.data.id,slug:e.data.slug,body:e.data.body||""}}}catch(e){}const o=yield fetch(`${Qm.API_BASE}/repos/${t}/docs`,{method:"POST",headers:{"X-Auth-Token":e,"Content-Type":"application/json"},body:JSON.stringify({title:n,slug:i,body:`# ${n}\n\n`,format:"markdown"})});if(!o.ok)throw new Error(`Yuque create doc error: ${o.status} ${o.statusText}`);const s=yield o.json();return{id:s.data.id,slug:s.data.slug,body:s.data.body||""}}))}formatNoteMarkdown(e){const t=!e.notes||0===e.notes.length,r=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let n="\n---\n\n";return e.chapter&&(n+=`### ${e.chapter}\n\n`),n+=`> ${e.text||""}\n\n`,!t&&e.notes&&(n+=`📝 ${e.notes}\n\n`),n+=`*Added on ${r}*\n\n`,n}updateDoc(e,t,r,n){return a(this,void 0,void 0,(function*(){const i=yield fetch(`${Qm.API_BASE}/repos/${t}/docs/${r}`,{method:"PUT",headers:{"X-Auth-Token":e,"Content-Type":"application/json"},body:JSON.stringify({body:n,format:"markdown"})});if(!i.ok)throw new Error(`Yuque update doc error: ${i.status} ${i.statusText}`)}))}syncNote(e,t){return a(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const r=this.getConfig();if(!r)return!1;try{const n=yield this.findOrCreateDoc(r.token,r.namespace,t),i=this.formatNoteMarkdown(e),o=n.body+i;return yield this.updateDoc(r.token,r.namespace,n.id,o),!0}catch(e){return console.error("Yuque sync failed:",e),!1}}))}}Qm.API_BASE="https://www.yuque.com/api/v2";class Gm{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("readwiseSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?null:e}catch(e){return null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableReadwiseSync")}syncNote(e,t,r){return a(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const n=this.getConfig();if(!n)return!1;const i=`${t}`,o=!e.notes||0===e.notes.length,s={text:e.text||"",title:i,author:r||"Unknown",source_type:"koodo-reader",category:"books",highlighted_at:`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`};if(!o&&e.notes&&(s.note=e.notes),e.chapter){const t=parseInt(e.chapter,10);isNaN(t)||(s.location_type="order",s.location=t)}try{const e=yield fetch(`${Gm.API_BASE}/highlights/`,{method:"POST",headers:{Authorization:`Token ${n.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({highlights:[s]})});if(!e.ok)throw new Error(`Readwise API error: ${e.status} ${e.statusText}`);return!0}catch(e){return console.error("Readwise sync failed:",e),!1}}))}}Gm.API_BASE="https://readwise.io/api/v2";class Jm{constructor(e,t){this.databaseService=e,this.notionSync=new Vm(t),this.yuqueSync=new Qm(t),this.readwiseSync=new Gm(t)}getExtraServices(){return[]}getEnabledServices(){const e=[];return this.notionSync.isEnabled()&&e.push({name:"Notion",sync:this.notionSync.syncNote.bind(this.notionSync)}),this.yuqueSync.isEnabled()&&e.push({name:"Yuque",sync:this.yuqueSync.syncNote.bind(this.yuqueSync)}),this.readwiseSync.isEnabled()&&e.push({name:"Readwise",sync:this.readwiseSync.syncNote.bind(this.readwiseSync)}),[...e,...this.getExtraServices()]}syncNote(e,t){return a(this,void 0,void 0,(function*(){const r=this.getEnabledServices();if(0===r.length)return;let n="Unknown Book",i="";if(t||e.bookKey)try{const r=yield this.databaseService.getRecord(t||e.bookKey,"books");r&&r.name&&(n=r.name),r&&r.author&&(i=r.author)}catch(r){console.warn(`Failed to resolve book info for key: ${t||e.bookKey}`)}const o=(yield Promise.allSettled(r.map((t=>a(this,void 0,void 0,(function*(){try{const r=yield t.sync(e,n,i);return{name:t.name,success:r}}catch(e){return console.error(`${t.name} sync error:`,e),{name:t.name,success:!1}}})))))).filter((e=>"rejected"===e.status||"fulfilled"===e.status&&!e.value.success)).map((e=>"fulfilled"===e.status?e.value.name:"Unknown"));o.length>0&&console.error(`Note sync failed for: ${o.join(", ")}`)}))}}class Ym{constructor(e){this.configService=e}getConfig(){try{const e=this.configService.getObjectConfig("markdownSyncConfig","thirdpartyToken",{});return 0===Object.keys(e).length?null:e}catch(e){return null}}isEnabled(){return"yes"===this.configService.getReaderConfig("isEnableMarkdownSync")}formatNoteMarkdown(e){const t=!e.notes||0===e.notes.length,r=`${e.date.year}-${String(e.date.month).padStart(2,"0")}-${String(e.date.day).padStart(2,"0")}`;let n="\n---\n\n";return e.chapter&&(n+=`### ${e.chapter}\n\n`),n+=`> ${e.text||""}\n\n`,!t&&e.notes&&(n+=`📝 ${e.notes}\n\n`),n+=`*Added on ${r}*\n\n`,n}sanitizeFileName(e){return e.replace(/[\\/:*?"<>|]/g,"_").trim()}syncNote(e,t,r){return a(this,void 0,void 0,(function*(){if(!this.isEnabled())return!1;const n=window.require("fs"),i=window.require("path"),o=this.getConfig();if(!o)return!1;const s=o.folder;if(!s)return!1;try{const o=this.sanitizeFileName(t),a=i.join(s,`${o}.md`);if(!n.existsSync(a)){const e=`# ${t}\n`,i=r?`**Author:** ${r}\n\n`:"\n";n.writeFileSync(a,e+i,"utf-8")}const c=this.formatNoteMarkdown(e);return n.appendFileSync(a,c,"utf-8"),!0}catch(e){return console.error("Markdown sync failed:",e),!1}}))}}class Xm extends Jm{constructor(e,t){super(e,t),this.markdownSync=new Ym(t)}getExtraServices(){return this.markdownSync.isEnabled()?[{name:"Markdown",sync:this.markdownSync.syncNote.bind(this.markdownSync)}]:[]}}export{g as CommonTool,Dm as ConfigService,w as KookitConfig,Fm as LoginHelper,Xm as NoteSyncManager,Mm as ReaderRequest,Lm as ReadingTimeUtil,Om as SqlStatement,Um as SyncHelper,Sm as SyncUtil,Nm as ThirdpartyRequest,qm as TokenService,$m as UserRequest}; diff --git a/src/assets/locales/zh-CN.json b/src/assets/locales/zh-CN.json index 08a21870..93b21e04 100644 --- a/src/assets/locales/zh-CN.json +++ b/src/assets/locales/zh-CN.json @@ -729,6 +729,8 @@ "Reader menu will not be triggered by hovering but clicking on the area": "阅读器菜单不是进入特定区域就触发,而是需要点击相关区域才能触发", "Gesture and UI optimization for touch screen": "针对触控屏进行了UI和手势操作的优化", "The book that you read from last time will be open automatically when launching": "软件启动时,自动打开上次阅读的图书", + "Number parser": "数字目录解析器", + "Suitable for novels with number chapter titles, eg. 1, 2, 3": "适用于章节标题为数字的小说,如 1、2、一、二", "All the folded content will be expanded in the navigation panel": "自动展开图书的多级目录", "Reader window will be maximized to fit the screen when opening a book": "打开图书时,窗口自动最大化", "Please upgrade to Pro to unlock more daily free quota or wait until the quota resets. You can also use other TTS voices instead.": "请升级到专业版以解锁更多每日免费额度,或等待额度重置。您也可以使用其他 TTS 语音替代。", diff --git a/src/components/readerSettings/dropdownList/component.tsx b/src/components/readerSettings/dropdownList/component.tsx index 5084fd55..d776d672 100644 --- a/src/components/readerSettings/dropdownList/component.tsx +++ b/src/components/readerSettings/dropdownList/component.tsx @@ -1,12 +1,12 @@ import React from "react"; -import { - contentRegxConfig, - dropdownList, -} from "../../../constants/dropdownList"; +import { dropdownList } from "../../../constants/dropdownList"; import "./dropdownList.css"; import { Trans } from "react-i18next"; import { DropdownListProps, DropdownListState } from "./interface"; -import { ConfigService } from "../../../assets/lib/kookit-extra-browser.min"; +import { + ConfigService, + KookitConfig, +} from "../../../assets/lib/kookit-extra-browser.min"; import { loadFontData, vexComfirmAsync } from "../../../utils/common"; import toast from "react-hot-toast"; declare var window: any; @@ -65,7 +65,10 @@ class DropdownList extends React.Component< value: label, })); this.setState({ - txtParserOptions: [...contentRegxConfig, ...customParserOptions], + txtParserOptions: [ + ...KookitConfig.ContentRegxConfig, + ...customParserOptions, + ], }); loadFontData().then((result) => { if (!result || result.length === 0) return; diff --git a/src/constants/dropdownList.tsx b/src/constants/dropdownList.tsx index 61539624..7a7ca70e 100644 --- a/src/constants/dropdownList.tsx +++ b/src/constants/dropdownList.tsx @@ -338,23 +338,3 @@ export const titleSizeList = [ { label: "4", value: "4" }, { label: "5", value: "5" }, ]; -export const contentRegxConfig = [ - { - label: "Default parser", - value: "Default parser", - subtitle: "Suitable for most txt files", - regex: "", - }, - { - label: "Chinese novel parser", - value: "Chinese novel parser", - subtitle: "Suitable for most Chinese novels, eg. 第一章,第2回", - regex: String.raw`^\s*(第[0-9一二三四五六七八九十百千万零]+[章回])\s*(.*?)$`, - }, - { - label: "English novel parser", - value: "English novel parser", - subtitle: "Suitable for most English novels, eg. Chapter 1, Part II", - regex: String.raw`^(Chapter|Part|Book|CHAPTER|PART|BOOK)\b.*$`, - }, -]; diff --git a/src/containers/settings/chapterSetting/component.tsx b/src/containers/settings/chapterSetting/component.tsx index 990f4efe..f2aac891 100644 --- a/src/containers/settings/chapterSetting/component.tsx +++ b/src/containers/settings/chapterSetting/component.tsx @@ -2,8 +2,10 @@ import React from "react"; import { SettingInfoProps, SettingInfoState, TxtParser } from "./interface"; import { Trans } from "react-i18next"; import toast from "react-hot-toast"; -import { ConfigService } from "../../../assets/lib/kookit-extra-browser.min"; -import { contentRegxConfig } from "../../../constants/dropdownList"; +import { + ConfigService, + KookitConfig, +} from "../../../assets/lib/kookit-extra-browser.min"; class ChapterSetting extends React.Component< SettingInfoProps, @@ -195,7 +197,7 @@ class ChapterSetting extends React.Component< Built-in parsers - {contentRegxConfig.map((parser) => ( + {KookitConfig.ContentRegxConfig.map((parser) => (
{ } let txtParsers: any[] = [ ...Object.values(ConfigService.getAllObjectConfig("txtParsers")), - ...contentRegxConfig, + ...KookitConfig.ContentRegxConfig, ]; let txtParser = txtParsers.find( (parser) => parser.value === defaultTxtParser