@aws/amazon-location-utilities-auth-helper 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  (function(global,factory){if(typeof define==="function"&&define.amd){define("amazonLocationAuthHelper",["exports"],factory)}else if(typeof exports!=="undefined"){factory(exports)}else{var mod={exports:{}};factory(mod.exports);global.amazonLocationAuthHelper=mod.exports}})(typeof globalThis!=="undefined"?globalThis:typeof self!=="undefined"?self:this,function(_exports){"use strict";Object.defineProperty(_exports,"__esModule",{value:true});_exports.withAPIKey=withAPIKey;_exports.withIdentityPoolId=withIdentityPoolId;// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  // Third party license at https://github.com/aws-geospatial/amazon-location-utilities-auth-helper-js/blob/main/LICENSE-THIRD-PARTY.txt
4
- class ProviderError extends Error{constructor(message){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;let logger;let tryNextLink=true;if(typeof options==="boolean"){logger=undefined;tryNextLink=options}else if(options!=null&&typeof options==="object"){logger=options.logger;tryNextLink=options.tryNextLink??true}super(message);this.name="ProviderError";this.tryNextLink=tryNextLink;Object.setPrototypeOf(this,ProviderError.prototype);logger?.debug?.(`@smithy/property-provider ${tryNextLink?"->":"(!)"} ${message}`)}static from(error){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;return Object.assign(new this(error.message,options),error)}}class CredentialsProviderError extends ProviderError{constructor(message){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;super(message,options);this.name="CredentialsProviderError";Object.setPrototypeOf(this,CredentialsProviderError.prototype)}}const memoize=(provider,isExpired,requiresRefresh)=>{let resolved;let pending;let hasResult;let isConstant=false;const coalesceProvider=async()=>{if(!pending){pending=provider()}try{resolved=await pending;hasResult=true;isConstant=false}finally{pending=undefined}return resolved};if(isExpired===undefined){return async options=>{if(!hasResult||options?.forceRefresh){resolved=await coalesceProvider()}return resolved}}return async options=>{if(!hasResult||options?.forceRefresh){resolved=await coalesceProvider()}if(isConstant){return resolved}if(requiresRefresh&&!requiresRefresh(resolved)){isConstant=true;return resolved}if(isExpired(resolved)){await coalesceProvider();return resolved}return resolved}};function resolveLogins(logins){return Promise.all(Object.keys(logins).reduce((arr,name)=>{const tokenOrProvider=logins[name];if(typeof tokenOrProvider==="string"){arr.push([name,tokenOrProvider])}else{arr.push(tokenOrProvider().then(token=>[name,token]))}return arr},[])).then(resolvedPairs=>resolvedPairs.reduce((logins,_ref)=>{let[key,value]=_ref;logins[key]=value;return logins},{}))}function fromCognitoIdentity(parameters){return async()=>{parameters.logger?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity");const{GetCredentialsForIdentityCommand,CognitoIdentityClient}=await Promise.resolve().then(function(){return loadCognitoIdentity});const{Credentials:{AccessKeyId=throwOnMissingAccessKeyId(parameters.logger),Expiration,SecretKey=throwOnMissingSecretKey(parameters.logger),SessionToken}=throwOnMissingCredentials(parameters.logger)}=await(parameters.client??new CognitoIdentityClient(Object.assign({},parameters.clientConfig??{},{region:parameters.clientConfig?.region??parameters.parentClientConfig?.region}))).send(new GetCredentialsForIdentityCommand({CustomRoleArn:parameters.customRoleArn,IdentityId:parameters.identityId,Logins:parameters.logins?await resolveLogins(parameters.logins):undefined}));return{identityId:parameters.identityId,accessKeyId:AccessKeyId,secretAccessKey:SecretKey,sessionToken:SessionToken,expiration:Expiration}}}function throwOnMissingAccessKeyId(logger){throw new CredentialsProviderError("Response from Amazon Cognito contained no access key ID",{logger})}function throwOnMissingCredentials(logger){throw new CredentialsProviderError("Response from Amazon Cognito contained no credentials",{logger})}function throwOnMissingSecretKey(logger){throw new CredentialsProviderError("Response from Amazon Cognito contained no secret key",{logger})}const STORE_NAME="IdentityIds";class IndexedDbStorage{constructor(){let dbName=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"aws:cognito-identity-ids";this.dbName=dbName}getItem(key){return this.withObjectStore("readonly",store=>{const req=store.get(key);return new Promise(resolve=>{req.onerror=()=>resolve(null);req.onsuccess=()=>resolve(req.result?req.result.value:null)})}).catch(()=>null)}removeItem(key){return this.withObjectStore("readwrite",store=>{const req=store.delete(key);return new Promise((resolve,reject)=>{req.onerror=()=>reject(req.error);req.onsuccess=()=>resolve()})})}setItem(id,value){return this.withObjectStore("readwrite",store=>{const req=store.put({id,value});return new Promise((resolve,reject)=>{req.onerror=()=>reject(req.error);req.onsuccess=()=>resolve()})})}getDb(){const openDbRequest=self.indexedDB.open(this.dbName,1);return new Promise((resolve,reject)=>{openDbRequest.onsuccess=()=>{resolve(openDbRequest.result)};openDbRequest.onerror=()=>{reject(openDbRequest.error)};openDbRequest.onblocked=()=>{reject(new Error("Unable to access DB"))};openDbRequest.onupgradeneeded=()=>{const db=openDbRequest.result;db.onerror=()=>{reject(new Error("Failed to create object store"))};db.createObjectStore(STORE_NAME,{keyPath:"id"})}})}withObjectStore(mode,action){return this.getDb().then(db=>{const tx=db.transaction(STORE_NAME,mode);tx.oncomplete=()=>db.close();return new Promise((resolve,reject)=>{tx.onerror=()=>reject(tx.error);resolve(action(tx.objectStore(STORE_NAME)))}).catch(err=>{db.close();throw err})})}}class InMemoryStorage{constructor(){let store=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};this.store=store}getItem(key){if(key in this.store){return this.store[key]}return null}removeItem(key){delete this.store[key]}setItem(key,value){this.store[key]=value}}const inMemoryStorage=new InMemoryStorage;function localStorage(){if(typeof self==="object"&&self.indexedDB){return new IndexedDbStorage}if(typeof window==="object"&&window.localStorage){return window.localStorage}return inMemoryStorage}function fromCognitoIdentityPool$1(_ref2){let{accountId,cache=localStorage(),client,clientConfig,customRoleArn,identityPoolId,logins,userIdentifier=!logins||Object.keys(logins).length===0?"ANONYMOUS":undefined,logger,parentClientConfig}=_ref2;logger?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity");const cacheKey=userIdentifier?`aws:cognito-identity-credentials:${identityPoolId}:${userIdentifier}`:undefined;let provider=async()=>{const{GetIdCommand,CognitoIdentityClient}=await Promise.resolve().then(function(){return loadCognitoIdentity});const _client=client??new CognitoIdentityClient(Object.assign({},clientConfig??{},{region:clientConfig?.region??parentClientConfig?.region}));let identityId=cacheKey&&(await cache.getItem(cacheKey));if(!identityId){const{IdentityId=throwOnMissingId(logger)}=await _client.send(new GetIdCommand({AccountId:accountId,IdentityPoolId:identityPoolId,Logins:logins?await resolveLogins(logins):undefined}));identityId=IdentityId;if(cacheKey){Promise.resolve(cache.setItem(cacheKey,identityId)).catch(()=>{})}}provider=fromCognitoIdentity({client:_client,customRoleArn,logins,identityId});return provider()};return()=>provider().catch(async err=>{if(cacheKey){Promise.resolve(cache.removeItem(cacheKey)).catch(()=>{})}throw err})}function throwOnMissingId(logger){throw new CredentialsProviderError("Response from Amazon Cognito contained no identity ID",{logger})}const fromCognitoIdentityPool=options=>fromCognitoIdentityPool$1({...options});const getHttpHandlerExtensionConfiguration=runtimeConfig=>{let httpHandler=runtimeConfig.httpHandler;return{setHttpHandler(handler){httpHandler=handler},httpHandler(){return httpHandler},updateHttpClientConfig(key,value){httpHandler.updateHttpClientConfig(key,value)},httpHandlerConfigs(){return httpHandler.httpHandlerConfigs()}}};const resolveHttpHandlerRuntimeConfig=httpHandlerExtensionConfiguration=>{return{httpHandler:httpHandlerExtensionConfiguration.httpHandler()}};var HttpAuthLocation;(function(HttpAuthLocation){HttpAuthLocation["HEADER"]="header";HttpAuthLocation["QUERY"]="query"})(HttpAuthLocation||(HttpAuthLocation={}));var HttpApiKeyAuthLocation;(function(HttpApiKeyAuthLocation){HttpApiKeyAuthLocation["HEADER"]="header";HttpApiKeyAuthLocation["QUERY"]="query"})(HttpApiKeyAuthLocation||(HttpApiKeyAuthLocation={}));var EndpointURLScheme;(function(EndpointURLScheme){EndpointURLScheme["HTTP"]="http";EndpointURLScheme["HTTPS"]="https"})(EndpointURLScheme||(EndpointURLScheme={}));var AlgorithmId;(function(AlgorithmId){AlgorithmId["MD5"]="md5";AlgorithmId["CRC32"]="crc32";AlgorithmId["CRC32C"]="crc32c";AlgorithmId["SHA1"]="sha1";AlgorithmId["SHA256"]="sha256"})(AlgorithmId||(AlgorithmId={}));var FieldPosition;(function(FieldPosition){FieldPosition[FieldPosition["HEADER"]=0]="HEADER";FieldPosition[FieldPosition["TRAILER"]=1]="TRAILER"})(FieldPosition||(FieldPosition={}));const SMITHY_CONTEXT_KEY="__smithy_context";var IniSectionType;(function(IniSectionType){IniSectionType["PROFILE"]="profile";IniSectionType["SSO_SESSION"]="sso-session";IniSectionType["SERVICES"]="services"})(IniSectionType||(IniSectionType={}));var RequestHandlerProtocol;(function(RequestHandlerProtocol){RequestHandlerProtocol["HTTP_0_9"]="http/0.9";RequestHandlerProtocol["HTTP_1_0"]="http/1.0";RequestHandlerProtocol["TDS_8_0"]="tds/8.0"})(RequestHandlerProtocol||(RequestHandlerProtocol={}));class HttpRequest{constructor(options){this.method=options.method||"GET";this.hostname=options.hostname||"localhost";this.port=options.port;this.query=options.query||{};this.headers=options.headers||{};this.body=options.body;this.protocol=options.protocol?options.protocol.slice(-1)!==":"?`${options.protocol}:`:options.protocol:"https:";this.path=options.path?options.path.charAt(0)!=="/"?`/${options.path}`:options.path:"/";this.username=options.username;this.password=options.password;this.fragment=options.fragment}static clone(request){const cloned=new HttpRequest({...request,headers:{...request.headers}});if(cloned.query){cloned.query=cloneQuery(cloned.query)}return cloned}static isInstance(request){if(!request){return false}const req=request;return"method"in req&&"protocol"in req&&"hostname"in req&&"path"in req&&typeof req["query"]==="object"&&typeof req["headers"]==="object"}clone(){return HttpRequest.clone(this)}}function cloneQuery(query){return Object.keys(query).reduce((carry,paramName)=>{const param=query[paramName];return{...carry,[paramName]:Array.isArray(param)?[...param]:param}},{})}class HttpResponse{constructor(options){this.statusCode=options.statusCode;this.reason=options.reason;this.headers=options.headers||{};this.body=options.body}static isInstance(response){if(!response)return false;const resp=response;return typeof resp.statusCode==="number"&&typeof resp.headers==="object"}}const escapeUri$1=uri=>encodeURIComponent(uri).replace(/[!'()*]/g,hexEncode$1);const hexEncode$1=c=>`%${c.charCodeAt(0).toString(16).toUpperCase()}`;function buildQueryString(query){const parts=[];for(let key of Object.keys(query).sort()){const value=query[key];key=escapeUri$1(key);if(Array.isArray(value)){for(let i=0,iLen=value.length;i<iLen;i++){parts.push(`${key}=${escapeUri$1(value[i])}`)}}else{let qsEntry=key;if(value||typeof value==="string"){qsEntry+=`=${escapeUri$1(value)}`}parts.push(qsEntry)}}return parts.join("&")}function requestTimeout(){let timeoutInMs=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return new Promise((resolve,reject)=>{if(timeoutInMs){setTimeout(()=>{const timeoutError=new Error(`Request did not complete within ${timeoutInMs} ms`);timeoutError.name="TimeoutError";reject(timeoutError)},timeoutInMs)}})}const keepAliveSupport={supported:undefined};class FetchHttpHandler{static create(instanceOrOptions){if(typeof instanceOrOptions?.handle==="function"){return instanceOrOptions}return new FetchHttpHandler(instanceOrOptions)}constructor(options){if(typeof options==="function"){this.configProvider=options().then(opts=>opts||{})}else{this.config=options??{};this.configProvider=Promise.resolve(this.config)}if(keepAliveSupport.supported===undefined){keepAliveSupport.supported=Boolean(typeof Request!=="undefined"&&"keepalive"in new Request("https://[::1]"))}}destroy(){}async handle(request){let{abortSignal}=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(!this.config){this.config=await this.configProvider}const requestTimeoutInMs=this.config.requestTimeout;const keepAlive=this.config.keepAlive===true;const credentials=this.config.credentials;if(abortSignal?.aborted){const abortError=new Error("Request aborted");abortError.name="AbortError";return Promise.reject(abortError)}let path=request.path;const queryString=buildQueryString(request.query||{});if(queryString){path+=`?${queryString}`}if(request.fragment){path+=`#${request.fragment}`}let auth="";if(request.username!=null||request.password!=null){const username=request.username??"";const password=request.password??"";auth=`${username}:${password}@`}const{port,method}=request;const url=`${request.protocol}//${auth}${request.hostname}${port?`:${port}`:""}${path}`;const body=method==="GET"||method==="HEAD"?undefined:request.body;const requestOptions={body,headers:new Headers(request.headers),method:method,credentials};if(this.config?.cache){requestOptions.cache=this.config.cache}if(body){requestOptions.duplex="half"}if(typeof AbortController!=="undefined"){requestOptions.signal=abortSignal}if(keepAliveSupport.supported){requestOptions.keepalive=keepAlive}if(typeof this.config.requestInit==="function"){Object.assign(requestOptions,this.config.requestInit(request))}let removeSignalEventListener=()=>{};const fetchRequest=new Request(url,requestOptions);const raceOfPromises=[fetch(fetchRequest).then(response=>{const fetchHeaders=response.headers;const transformedHeaders={};for(const pair of fetchHeaders.entries()){transformedHeaders[pair[0]]=pair[1]}const hasReadableStream=response.body!=undefined;if(!hasReadableStream){return response.blob().then(body=>({response:new HttpResponse({headers:transformedHeaders,reason:response.statusText,statusCode:response.status,body})}))}return{response:new HttpResponse({headers:transformedHeaders,reason:response.statusText,statusCode:response.status,body:response.body})}}),requestTimeout(requestTimeoutInMs)];if(abortSignal){raceOfPromises.push(new Promise((resolve,reject)=>{const onAbort=()=>{const abortError=new Error("Request aborted");abortError.name="AbortError";reject(abortError)};if(typeof abortSignal.addEventListener==="function"){const signal=abortSignal;signal.addEventListener("abort",onAbort,{once:true});removeSignalEventListener=()=>signal.removeEventListener("abort",onAbort)}else{abortSignal.onabort=onAbort}}))}return Promise.race(raceOfPromises).finally(removeSignalEventListener)}updateHttpClientConfig(key,value){this.config=undefined;this.configProvider=this.configProvider.then(config=>{config[key]=value;return config})}httpHandlerConfigs(){return this.config??{}}}const alphabetByEncoding={};const alphabetByValue=new Array(64);for(let i=0,start="A".charCodeAt(0),limit="Z".charCodeAt(0);i+start<=limit;i++){const char=String.fromCharCode(i+start);alphabetByEncoding[char]=i;alphabetByValue[i]=char}for(let i=0,start="a".charCodeAt(0),limit="z".charCodeAt(0);i+start<=limit;i++){const char=String.fromCharCode(i+start);const index=i+26;alphabetByEncoding[char]=index;alphabetByValue[index]=char}for(let i=0;i<10;i++){alphabetByEncoding[i.toString(10)]=i+52;const char=i.toString(10);const index=i+52;alphabetByEncoding[char]=index;alphabetByValue[index]=char}alphabetByEncoding["+"]=62;alphabetByValue[62]="+";alphabetByEncoding["/"]=63;alphabetByValue[63]="/";const bitsPerLetter=6;const bitsPerByte=8;const maxLetterValue=63;const fromBase64=input=>{let totalByteLength=input.length/4*3;if(input.slice(-2)==="=="){totalByteLength-=2}else if(input.slice(-1)==="="){totalByteLength--}const out=new ArrayBuffer(totalByteLength);const dataView=new DataView(out);for(let i=0;i<input.length;i+=4){let bits=0;let bitLength=0;for(let j=i,limit=i+3;j<=limit;j++){if(input[j]!=="="){if(!(input[j]in alphabetByEncoding)){throw new TypeError(`Invalid character ${input[j]} in base64 string.`)}bits|=alphabetByEncoding[input[j]]<<(limit-j)*bitsPerLetter;bitLength+=bitsPerLetter}else{bits>>=bitsPerLetter}}const chunkOffset=i/4*3;bits>>=bitLength%bitsPerByte;const byteLength=Math.floor(bitLength/bitsPerByte);for(let k=0;k<byteLength;k++){const offset=(byteLength-k-1)*bitsPerByte;dataView.setUint8(chunkOffset+k,(bits&255<<offset)>>offset)}}return new Uint8Array(out)};const fromUtf8$5=input=>new TextEncoder().encode(input);function toBase64(_input){let input;if(typeof _input==="string"){input=fromUtf8$5(_input)}else{input=_input}const isArrayLike=typeof input==="object"&&typeof input.length==="number";const isUint8Array=typeof input==="object"&&typeof input.byteOffset==="number"&&typeof input.byteLength==="number";if(!isArrayLike&&!isUint8Array){throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.")}let str="";for(let i=0;i<input.length;i+=3){let bits=0;let bitLength=0;for(let j=i,limit=Math.min(i+3,input.length);j<limit;j++){bits|=input[j]<<(limit-j-1)*bitsPerByte;bitLength+=bitsPerByte}const bitClusterCount=Math.ceil(bitLength/bitsPerLetter);bits<<=bitClusterCount*bitsPerLetter-bitLength;for(let k=1;k<=bitClusterCount;k++){const offset=(bitClusterCount-k)*bitsPerLetter;str+=alphabetByValue[(bits&maxLetterValue<<offset)>>offset]}str+="==".slice(0,4-bitClusterCount)}return str}const streamCollector=stream=>{if(typeof Blob==="function"&&stream instanceof Blob){return collectBlob(stream)}return collectStream(stream)};async function collectBlob(blob){const base64=await readToBase64(blob);const arrayBuffer=fromBase64(base64);return new Uint8Array(arrayBuffer)}async function collectStream(stream){const chunks=[];const reader=stream.getReader();let isDone=false;let length=0;while(!isDone){const{done,value}=await reader.read();if(value){chunks.push(value);length+=value.length}isDone=done}const collected=new Uint8Array(length);let offset=0;for(const chunk of chunks){collected.set(chunk,offset);offset+=chunk.length}return collected}function readToBase64(blob){return new Promise((resolve,reject)=>{const reader=new FileReader;reader.onloadend=()=>{if(reader.readyState!==2){return reject(new Error("Reader aborted too early"))}const result=reader.result??"";const commaIndex=result.indexOf(",");const dataOffset=commaIndex>-1?commaIndex+1:result.length;resolve(result.substring(dataOffset))};reader.onabort=()=>reject(new Error("Read aborted"));reader.onerror=()=>reject(reader.error);reader.readAsDataURL(blob)})}const getAllAliases=(name,aliases)=>{const _aliases=[];if(name){_aliases.push(name)}if(aliases){for(const alias of aliases){_aliases.push(alias)}}return _aliases};const getMiddlewareNameWithAliases=(name,aliases)=>{return`${name||"anonymous"}${aliases&&aliases.length>0?` (a.k.a. ${aliases.join(",")})`:""}`};const constructStack=()=>{let absoluteEntries=[];let relativeEntries=[];let identifyOnResolve=false;const entriesNameSet=new Set;const sort=entries=>entries.sort((a,b)=>stepWeights[b.step]-stepWeights[a.step]||priorityWeights[b.priority||"normal"]-priorityWeights[a.priority||"normal"]);const removeByName=toRemove=>{let isRemoved=false;const filterCb=entry=>{const aliases=getAllAliases(entry.name,entry.aliases);if(aliases.includes(toRemove)){isRemoved=true;for(const alias of aliases){entriesNameSet.delete(alias)}return false}return true};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved};const removeByReference=toRemove=>{let isRemoved=false;const filterCb=entry=>{if(entry.middleware===toRemove){isRemoved=true;for(const alias of getAllAliases(entry.name,entry.aliases)){entriesNameSet.delete(alias)}return false}return true};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved};const cloneTo=toStack=>{absoluteEntries.forEach(entry=>{toStack.add(entry.middleware,{...entry})});relativeEntries.forEach(entry=>{toStack.addRelativeTo(entry.middleware,{...entry})});toStack.identifyOnResolve?.(stack.identifyOnResolve());return toStack};const expandRelativeMiddlewareList=from=>{const expandedMiddlewareList=[];from.before.forEach(entry=>{if(entry.before.length===0&&entry.after.length===0){expandedMiddlewareList.push(entry)}else{expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry))}});expandedMiddlewareList.push(from);from.after.reverse().forEach(entry=>{if(entry.before.length===0&&entry.after.length===0){expandedMiddlewareList.push(entry)}else{expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry))}});return expandedMiddlewareList};const getMiddlewareList=function(){let debug=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;const normalizedAbsoluteEntries=[];const normalizedRelativeEntries=[];const normalizedEntriesNameMap={};absoluteEntries.forEach(entry=>{const normalizedEntry={...entry,before:[],after:[]};for(const alias of getAllAliases(normalizedEntry.name,normalizedEntry.aliases)){normalizedEntriesNameMap[alias]=normalizedEntry}normalizedAbsoluteEntries.push(normalizedEntry)});relativeEntries.forEach(entry=>{const normalizedEntry={...entry,before:[],after:[]};for(const alias of getAllAliases(normalizedEntry.name,normalizedEntry.aliases)){normalizedEntriesNameMap[alias]=normalizedEntry}normalizedRelativeEntries.push(normalizedEntry)});normalizedRelativeEntries.forEach(entry=>{if(entry.toMiddleware){const toMiddleware=normalizedEntriesNameMap[entry.toMiddleware];if(toMiddleware===undefined){if(debug){return}throw new Error(`${entry.toMiddleware} is not found when adding `+`${getMiddlewareNameWithAliases(entry.name,entry.aliases)} `+`middleware ${entry.relation} ${entry.toMiddleware}`)}if(entry.relation==="after"){toMiddleware.after.push(entry)}if(entry.relation==="before"){toMiddleware.before.push(entry)}}});const mainChain=sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList,expandedMiddlewareList)=>{wholeList.push(...expandedMiddlewareList);return wholeList},[]);return mainChain};const stack={add:function(middleware){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const{name,override,aliases:_aliases}=options;const entry={step:"initialize",priority:"normal",middleware,...options};const aliases=getAllAliases(name,_aliases);if(aliases.length>0){if(aliases.some(alias=>entriesNameSet.has(alias))){if(!override)throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name,_aliases)}'`);for(const alias of aliases){const toOverrideIndex=absoluteEntries.findIndex(entry=>entry.name===alias||entry.aliases?.some(a=>a===alias));if(toOverrideIndex===-1){continue}const toOverride=absoluteEntries[toOverrideIndex];if(toOverride.step!==entry.step||entry.priority!==toOverride.priority){throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name,toOverride.aliases)}" middleware with `+`${toOverride.priority} priority in ${toOverride.step} step cannot `+`be overridden by "${getMiddlewareNameWithAliases(name,_aliases)}" middleware with `+`${entry.priority} priority in ${entry.step} step.`)}absoluteEntries.splice(toOverrideIndex,1)}}for(const alias of aliases){entriesNameSet.add(alias)}}absoluteEntries.push(entry)},addRelativeTo:(middleware,options)=>{const{name,override,aliases:_aliases}=options;const entry={middleware,...options};const aliases=getAllAliases(name,_aliases);if(aliases.length>0){if(aliases.some(alias=>entriesNameSet.has(alias))){if(!override)throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name,_aliases)}'`);for(const alias of aliases){const toOverrideIndex=relativeEntries.findIndex(entry=>entry.name===alias||entry.aliases?.some(a=>a===alias));if(toOverrideIndex===-1){continue}const toOverride=relativeEntries[toOverrideIndex];if(toOverride.toMiddleware!==entry.toMiddleware||toOverride.relation!==entry.relation){throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name,toOverride.aliases)}" middleware `+`${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden `+`by "${getMiddlewareNameWithAliases(name,_aliases)}" middleware ${entry.relation} `+`"${entry.toMiddleware}" middleware.`)}relativeEntries.splice(toOverrideIndex,1)}}for(const alias of aliases){entriesNameSet.add(alias)}}relativeEntries.push(entry)},clone:()=>cloneTo(constructStack()),use:plugin=>{plugin.applyToStack(stack)},remove:toRemove=>{if(typeof toRemove==="string")return removeByName(toRemove);else return removeByReference(toRemove)},removeByTag:toRemove=>{let isRemoved=false;const filterCb=entry=>{const{tags,name,aliases:_aliases}=entry;if(tags&&tags.includes(toRemove)){const aliases=getAllAliases(name,_aliases);for(const alias of aliases){entriesNameSet.delete(alias)}isRemoved=true;return false}return true};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved},concat:from=>{const cloned=cloneTo(constructStack());cloned.use(from);cloned.identifyOnResolve(identifyOnResolve||cloned.identifyOnResolve()||(from.identifyOnResolve?.()??false));return cloned},applyToStack:cloneTo,identify:()=>{return getMiddlewareList(true).map(mw=>{const step=mw.step??mw.relation+" "+mw.toMiddleware;return getMiddlewareNameWithAliases(mw.name,mw.aliases)+" - "+step})},identifyOnResolve(toggle){if(typeof toggle==="boolean")identifyOnResolve=toggle;return identifyOnResolve},resolve:(handler,context)=>{for(const middleware of getMiddlewareList().map(entry=>entry.middleware).reverse()){handler=middleware(handler,context)}if(identifyOnResolve){console.log(stack.identify())}return handler}};return stack};const stepWeights={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1};const priorityWeights={high:3,normal:2,low:1};class Client{constructor(config){this.config=config;this.middlewareStack=constructStack()}send(command,optionsOrCb,cb){const options=typeof optionsOrCb!=="function"?optionsOrCb:undefined;const callback=typeof optionsOrCb==="function"?optionsOrCb:cb;const useHandlerCache=options===undefined&&this.config.cacheMiddleware===true;let handler;if(useHandlerCache){if(!this.handlers){this.handlers=new WeakMap}const handlers=this.handlers;if(handlers.has(command.constructor)){handler=handlers.get(command.constructor)}else{handler=command.resolveMiddleware(this.middlewareStack,this.config,options);handlers.set(command.constructor,handler)}}else{delete this.handlers;handler=command.resolveMiddleware(this.middlewareStack,this.config,options)}if(callback){handler(command).then(result=>callback(null,result.output),err=>callback(err)).catch(()=>{})}else{return handler(command).then(result=>result.output)}}destroy(){this.config?.requestHandler?.destroy?.();delete this.handlers}}const fromUtf8$4=input=>new TextEncoder().encode(input);const toUtf8$1=input=>{if(typeof input==="string"){return input}if(typeof input!=="object"||typeof input.byteOffset!=="number"||typeof input.byteLength!=="number"){throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.")}return new TextDecoder("utf-8").decode(input)};function transformToString(payload){let encoding=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"utf-8";if(encoding==="base64"){return toBase64(payload)}return toUtf8$1(payload)}function transformFromString(str,encoding){if(encoding==="base64"){return Uint8ArrayBlobAdapter.mutate(fromBase64(str))}return Uint8ArrayBlobAdapter.mutate(fromUtf8$4(str))}class Uint8ArrayBlobAdapter extends Uint8Array{static fromString(source){let encoding=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"utf-8";switch(typeof source){case"string":return transformFromString(source,encoding);default:throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`)}}static mutate(source){Object.setPrototypeOf(source,Uint8ArrayBlobAdapter.prototype);return source}transformToString(){let encoding=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"utf-8";return transformToString(this,encoding)}}for(let i=0;i<256;i++){let encodedByte=i.toString(16).toLowerCase();if(encodedByte.length===1){encodedByte=`0${encodedByte}`}}const collectBody=async function(){let streamBody=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Uint8Array;let context=arguments.length>1?arguments[1]:undefined;if(streamBody instanceof Uint8Array){return Uint8ArrayBlobAdapter.mutate(streamBody)}if(!streamBody){return Uint8ArrayBlobAdapter.mutate(new Uint8Array)}const fromContext=context.streamCollector(streamBody);return Uint8ArrayBlobAdapter.mutate(await fromContext)};class Command{constructor(){this.middlewareStack=constructStack()}static classBuilder(){return new ClassBuilder}resolveMiddlewareWithContext(clientStack,configuration,options,_ref3){let{middlewareFn,clientName,commandName,inputFilterSensitiveLog,outputFilterSensitiveLog,smithyContext,additionalContext,CommandCtor}=_ref3;for(const mw of middlewareFn.bind(this)(CommandCtor,clientStack,configuration,options)){this.middlewareStack.use(mw)}const stack=clientStack.concat(this.middlewareStack);const{logger}=configuration;const handlerExecutionContext={logger,clientName,commandName,inputFilterSensitiveLog,outputFilterSensitiveLog,[SMITHY_CONTEXT_KEY]:{commandInstance:this,...smithyContext},...additionalContext};const{requestHandler}=configuration;return stack.resolve(request=>requestHandler.handle(request.request,options||{}),handlerExecutionContext)}}class ClassBuilder{constructor(){this._init=()=>{};this._ep={};this._middlewareFn=()=>[];this._commandName="";this._clientName="";this._additionalContext={};this._smithyContext={};this._inputFilterSensitiveLog=_=>_;this._outputFilterSensitiveLog=_=>_;this._serializer=null;this._deserializer=null}init(cb){this._init=cb}ep(endpointParameterInstructions){this._ep=endpointParameterInstructions;return this}m(middlewareSupplier){this._middlewareFn=middlewareSupplier;return this}s(service,operation){let smithyContext=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};this._smithyContext={service,operation,...smithyContext};return this}c(){let additionalContext=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};this._additionalContext=additionalContext;return this}n(clientName,commandName){this._clientName=clientName;this._commandName=commandName;return this}f(){let inputFilter=arguments.length>0&&arguments[0]!==undefined?arguments[0]:_=>_;let outputFilter=arguments.length>1&&arguments[1]!==undefined?arguments[1]:_=>_;this._inputFilterSensitiveLog=inputFilter;this._outputFilterSensitiveLog=outputFilter;return this}ser(serializer){this._serializer=serializer;return this}de(deserializer){this._deserializer=deserializer;return this}build(){const closure=this;let CommandRef;return CommandRef=class extends Command{static getEndpointParameterInstructions(){return closure._ep}constructor(){for(var _len=arguments.length,_ref4=new Array(_len),_key=0;_key<_len;_key++){_ref4[_key]=arguments[_key]}let[input]=_ref4;super();this.serialize=closure._serializer;this.deserialize=closure._deserializer;this.input=input??{};closure._init(this)}resolveMiddleware(stack,configuration,options){return this.resolveMiddlewareWithContext(stack,configuration,options,{CommandCtor:CommandRef,middlewareFn:closure._middlewareFn,clientName:closure._clientName,commandName:closure._commandName,inputFilterSensitiveLog:closure._inputFilterSensitiveLog,outputFilterSensitiveLog:closure._outputFilterSensitiveLog,smithyContext:closure._smithyContext,additionalContext:closure._additionalContext})}}}}const SENSITIVE_STRING="***SensitiveInformation***";const expectNumber=value=>{if(value===null||value===undefined){return undefined}if(typeof value==="string"){const parsed=parseFloat(value);if(!Number.isNaN(parsed)){if(String(parsed)!==String(value)){logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`))}return parsed}}if(typeof value==="number"){return value}throw new TypeError(`Expected number, got ${typeof value}: ${value}`)};const expectNonNull=(value,location)=>{if(value===null||value===undefined){if(location){throw new TypeError(`Expected a non-null value for ${location}`)}throw new TypeError("Expected a non-null value")}return value};const expectString=value=>{if(value===null||value===undefined){return undefined}if(typeof value==="string"){return value}if(["boolean","number","bigint"].includes(typeof value)){logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));return String(value)}throw new TypeError(`Expected string, got ${typeof value}: ${value}`)};const strictParseDouble=value=>{if(typeof value=="string"){return expectNumber(parseNumber(value))}return expectNumber(value)};const NUMBER_REGEX=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;const parseNumber=value=>{const matches=value.match(NUMBER_REGEX);if(matches===null||matches[0].length!==value.length){throw new TypeError(`Expected real number, got implicit NaN`)}return parseFloat(value)};const stackTraceWarning=message=>{return String(new TypeError(message).stack||message).split("\n").slice(0,5).filter(s=>!s.includes("stackTraceWarning")).join("\n")};const logger={warn:console.warn};const parseEpochTimestamp=value=>{if(value===null||value===undefined){return undefined}let valueAsDouble;if(typeof value==="number"){valueAsDouble=value}else if(typeof value==="string"){valueAsDouble=strictParseDouble(value)}else if(typeof value==="object"&&value.tag===1){valueAsDouble=value.value}else{throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation")}if(Number.isNaN(valueAsDouble)||valueAsDouble===Infinity||valueAsDouble===-Infinity){throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics")}return new Date(Math.round(valueAsDouble*1000))};class ServiceException extends Error{constructor(options){super(options.message);Object.setPrototypeOf(this,ServiceException.prototype);this.name=options.name;this.$fault=options.$fault;this.$metadata=options.$metadata}}const decorateServiceException=function(exception){let additions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};Object.entries(additions).filter(_ref5=>{let[,v]=_ref5;return v!==undefined}).forEach(_ref6=>{let[k,v]=_ref6;if(exception[k]==undefined||exception[k]===""){exception[k]=v}});const message=exception.message||exception.Message||"UnknownError";exception.message=message;delete exception.Message;return exception};const throwDefaultError$1=_ref7=>{let{output,parsedBody,exceptionCtor,errorCode}=_ref7;const $metadata=deserializeMetadata$1(output);const statusCode=$metadata.httpStatusCode?$metadata.httpStatusCode+"":undefined;const response=new exceptionCtor({name:parsedBody?.code||parsedBody?.Code||errorCode||statusCode||"UnknownError",$fault:"client",$metadata});throw decorateServiceException(response,parsedBody)};const withBaseException=ExceptionCtor=>{return _ref8=>{let{output,parsedBody,errorCode}=_ref8;throwDefaultError$1({output,parsedBody,exceptionCtor:ExceptionCtor,errorCode})}};const deserializeMetadata$1=output=>({httpStatusCode:output.statusCode,requestId:output.headers["x-amzn-requestid"]??output.headers["x-amzn-request-id"]??output.headers["x-amz-request-id"],extendedRequestId:output.headers["x-amz-id-2"],cfId:output.headers["x-amz-cf-id"]});const loadConfigsForDefaultMode=mode=>{switch(mode){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:30000};default:return{}}};const getChecksumConfiguration=runtimeConfig=>{const checksumAlgorithms=[];for(const id in AlgorithmId){const algorithmId=AlgorithmId[id];if(runtimeConfig[algorithmId]===undefined){continue}checksumAlgorithms.push({algorithmId:()=>algorithmId,checksumConstructor:()=>runtimeConfig[algorithmId]})}return{_checksumAlgorithms:checksumAlgorithms,addChecksumAlgorithm(algo){this._checksumAlgorithms.push(algo)},checksumAlgorithms(){return this._checksumAlgorithms}}};const resolveChecksumRuntimeConfig=clientConfig=>{const runtimeConfig={};clientConfig.checksumAlgorithms().forEach(checksumAlgorithm=>{runtimeConfig[checksumAlgorithm.algorithmId()]=checksumAlgorithm.checksumConstructor()});return runtimeConfig};const getRetryConfiguration=runtimeConfig=>{let _retryStrategy=runtimeConfig.retryStrategy;return{setRetryStrategy(retryStrategy){_retryStrategy=retryStrategy},retryStrategy(){return _retryStrategy}}};const resolveRetryRuntimeConfig=retryStrategyConfiguration=>{const runtimeConfig={};runtimeConfig.retryStrategy=retryStrategyConfiguration.retryStrategy();return runtimeConfig};const getDefaultExtensionConfiguration=runtimeConfig=>{return{...getChecksumConfiguration(runtimeConfig),...getRetryConfiguration(runtimeConfig)}};const resolveDefaultRuntimeConfig=config=>{return{...resolveChecksumRuntimeConfig(config),...resolveRetryRuntimeConfig(config)}};const StringWrapper=function(){const Class=Object.getPrototypeOf(this).constructor;const Constructor=Function.bind.apply(String,[null,...arguments]);const instance=new Constructor;Object.setPrototypeOf(instance,Class.prototype);return instance};StringWrapper.prototype=Object.create(String.prototype,{constructor:{value:StringWrapper,enumerable:false,writable:true,configurable:true}});Object.setPrototypeOf(StringWrapper,String);class NoOpLogger{trace(){}debug(){}info(){}warn(){}error(){}}const take=(source,instructions)=>{const out={};for(const key in instructions){applyInstruction(out,source,instructions,key)}return out};const applyInstruction=(target,source,instructions,targetKey)=>{if(source!==null){let instruction=instructions[targetKey];if(typeof instruction==="function"){instruction=[,instruction]}const[filter=nonNullish,valueFn=pass,sourceKey=targetKey]=instruction;if(typeof filter==="function"&&filter(source[sourceKey])||typeof filter!=="function"&&!!filter){target[targetKey]=valueFn(source[sourceKey])}return}let[filter,value]=instructions[targetKey];if(typeof value==="function"){let _value;const defaultFilterPassed=filter===undefined&&(_value=value())!=null;const customFilterPassed=typeof filter==="function"&&!!filter(void 0)||typeof filter!=="function"&&!!filter;if(defaultFilterPassed){target[targetKey]=_value}else if(customFilterPassed){target[targetKey]=value()}}else{const defaultFilterPassed=filter===undefined&&value!=null;const customFilterPassed=typeof filter==="function"&&!!filter(value)||typeof filter!=="function"&&!!filter;if(defaultFilterPassed||customFilterPassed){target[targetKey]=value}}};const nonNullish=_=>_!=null;const pass=_=>_;const _json=obj=>{if(obj==null){return{}}if(Array.isArray(obj)){return obj.filter(_=>_!=null).map(_json)}if(typeof obj==="object"){const target={};for(const key of Object.keys(obj)){if(obj[key]==null){continue}target[key]=_json(obj[key])}return target}return obj};/******************************************************************************
4
+ class ProviderError extends Error{constructor(message){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;let logger;let tryNextLink=true;if(typeof options==="boolean"){logger=undefined;tryNextLink=options}else if(options!=null&&typeof options==="object"){logger=options.logger;tryNextLink=options.tryNextLink??true}super(message);this.name="ProviderError";this.tryNextLink=tryNextLink;Object.setPrototypeOf(this,ProviderError.prototype);logger?.debug?.(`@smithy/property-provider ${tryNextLink?"->":"(!)"} ${message}`)}static from(error){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;return Object.assign(new this(error.message,options),error)}}class CredentialsProviderError extends ProviderError{constructor(message){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;super(message,options);this.name="CredentialsProviderError";Object.setPrototypeOf(this,CredentialsProviderError.prototype)}}const memoize=(provider,isExpired,requiresRefresh)=>{let resolved;let pending;let hasResult;let isConstant=false;const coalesceProvider=async()=>{if(!pending){pending=provider()}try{resolved=await pending;hasResult=true;isConstant=false}finally{pending=undefined}return resolved};{return async options=>{if(!hasResult||options?.forceRefresh){resolved=await coalesceProvider()}return resolved}}};function resolveLogins(logins){return Promise.all(Object.keys(logins).reduce((arr,name)=>{const tokenOrProvider=logins[name];if(typeof tokenOrProvider==="string"){arr.push([name,tokenOrProvider])}else{arr.push(tokenOrProvider().then(token=>[name,token]))}return arr},[])).then(resolvedPairs=>resolvedPairs.reduce((logins,_ref)=>{let[key,value]=_ref;logins[key]=value;return logins},{}))}function fromCognitoIdentity(parameters){return async awsIdentityProperties=>{parameters.logger?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity");const{GetCredentialsForIdentityCommand,CognitoIdentityClient}=await Promise.resolve().then(function(){return loadCognitoIdentity});const fromConfigs=property=>parameters.clientConfig?.[property]??parameters.parentClientConfig?.[property]??awsIdentityProperties?.callerClientConfig?.[property];const{Credentials:{AccessKeyId=throwOnMissingAccessKeyId(parameters.logger),Expiration,SecretKey=throwOnMissingSecretKey(parameters.logger),SessionToken}=throwOnMissingCredentials(parameters.logger)}=await(parameters.client??new CognitoIdentityClient(Object.assign({},parameters.clientConfig??{},{region:fromConfigs("region"),profile:fromConfigs("profile")}))).send(new GetCredentialsForIdentityCommand({CustomRoleArn:parameters.customRoleArn,IdentityId:parameters.identityId,Logins:parameters.logins?await resolveLogins(parameters.logins):undefined}));return{identityId:parameters.identityId,accessKeyId:AccessKeyId,secretAccessKey:SecretKey,sessionToken:SessionToken,expiration:Expiration}}}function throwOnMissingAccessKeyId(logger){throw new CredentialsProviderError("Response from Amazon Cognito contained no access key ID",{logger})}function throwOnMissingCredentials(logger){throw new CredentialsProviderError("Response from Amazon Cognito contained no credentials",{logger})}function throwOnMissingSecretKey(logger){throw new CredentialsProviderError("Response from Amazon Cognito contained no secret key",{logger})}const STORE_NAME="IdentityIds";class IndexedDbStorage{dbName;constructor(){let dbName=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"aws:cognito-identity-ids";this.dbName=dbName}getItem(key){return this.withObjectStore("readonly",store=>{const req=store.get(key);return new Promise(resolve=>{req.onerror=()=>resolve(null);req.onsuccess=()=>resolve(req.result?req.result.value:null)})}).catch(()=>null)}removeItem(key){return this.withObjectStore("readwrite",store=>{const req=store.delete(key);return new Promise((resolve,reject)=>{req.onerror=()=>reject(req.error);req.onsuccess=()=>resolve()})})}setItem(id,value){return this.withObjectStore("readwrite",store=>{const req=store.put({id,value});return new Promise((resolve,reject)=>{req.onerror=()=>reject(req.error);req.onsuccess=()=>resolve()})})}getDb(){const openDbRequest=self.indexedDB.open(this.dbName,1);return new Promise((resolve,reject)=>{openDbRequest.onsuccess=()=>{resolve(openDbRequest.result)};openDbRequest.onerror=()=>{reject(openDbRequest.error)};openDbRequest.onblocked=()=>{reject(new Error("Unable to access DB"))};openDbRequest.onupgradeneeded=()=>{const db=openDbRequest.result;db.onerror=()=>{reject(new Error("Failed to create object store"))};db.createObjectStore(STORE_NAME,{keyPath:"id"})}})}withObjectStore(mode,action){return this.getDb().then(db=>{const tx=db.transaction(STORE_NAME,mode);tx.oncomplete=()=>db.close();return new Promise((resolve,reject)=>{tx.onerror=()=>reject(tx.error);resolve(action(tx.objectStore(STORE_NAME)))}).catch(err=>{db.close();throw err})})}}class InMemoryStorage{store;constructor(){let store=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};this.store=store}getItem(key){if(key in this.store){return this.store[key]}return null}removeItem(key){delete this.store[key]}setItem(key,value){this.store[key]=value}}const inMemoryStorage=new InMemoryStorage;function localStorage(){if(typeof self==="object"&&self.indexedDB){return new IndexedDbStorage}if(typeof window==="object"&&window.localStorage){return window.localStorage}return inMemoryStorage}function fromCognitoIdentityPool$1(_ref2){let{accountId,cache=localStorage(),client,clientConfig,customRoleArn,identityPoolId,logins,userIdentifier=!logins||Object.keys(logins).length===0?"ANONYMOUS":undefined,logger,parentClientConfig}=_ref2;logger?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity");const cacheKey=userIdentifier?`aws:cognito-identity-credentials:${identityPoolId}:${userIdentifier}`:undefined;let provider=async awsIdentityProperties=>{const{GetIdCommand,CognitoIdentityClient}=await Promise.resolve().then(function(){return loadCognitoIdentity});const fromConfigs=property=>clientConfig?.[property]??parentClientConfig?.[property]??awsIdentityProperties?.callerClientConfig?.[property];const _client=client??new CognitoIdentityClient(Object.assign({},clientConfig??{},{region:fromConfigs("region"),profile:fromConfigs("profile")}));let identityId=cacheKey&&(await cache.getItem(cacheKey));if(!identityId){const{IdentityId=throwOnMissingId(logger)}=await _client.send(new GetIdCommand({AccountId:accountId,IdentityPoolId:identityPoolId,Logins:logins?await resolveLogins(logins):undefined}));identityId=IdentityId;if(cacheKey){Promise.resolve(cache.setItem(cacheKey,identityId)).catch(()=>{})}}provider=fromCognitoIdentity({client:_client,customRoleArn,logins,identityId});return provider(awsIdentityProperties)};return awsIdentityProperties=>provider(awsIdentityProperties).catch(async err=>{if(cacheKey){Promise.resolve(cache.removeItem(cacheKey)).catch(()=>{})}throw err})}function throwOnMissingId(logger){throw new CredentialsProviderError("Response from Amazon Cognito contained no identity ID",{logger})}const fromCognitoIdentityPool=options=>fromCognitoIdentityPool$1({...options});const getHttpHandlerExtensionConfiguration=runtimeConfig=>{return{setHttpHandler(handler){runtimeConfig.httpHandler=handler},httpHandler(){return runtimeConfig.httpHandler},updateHttpClientConfig(key,value){runtimeConfig.httpHandler?.updateHttpClientConfig(key,value)},httpHandlerConfigs(){return runtimeConfig.httpHandler.httpHandlerConfigs()}}};const resolveHttpHandlerRuntimeConfig=httpHandlerExtensionConfiguration=>{return{httpHandler:httpHandlerExtensionConfiguration.httpHandler()}};var HttpAuthLocation;(function(HttpAuthLocation){HttpAuthLocation["HEADER"]="header";HttpAuthLocation["QUERY"]="query"})(HttpAuthLocation||(HttpAuthLocation={}));var HttpApiKeyAuthLocation;(function(HttpApiKeyAuthLocation){HttpApiKeyAuthLocation["HEADER"]="header";HttpApiKeyAuthLocation["QUERY"]="query"})(HttpApiKeyAuthLocation||(HttpApiKeyAuthLocation={}));var EndpointURLScheme;(function(EndpointURLScheme){EndpointURLScheme["HTTP"]="http";EndpointURLScheme["HTTPS"]="https"})(EndpointURLScheme||(EndpointURLScheme={}));var AlgorithmId;(function(AlgorithmId){AlgorithmId["MD5"]="md5";AlgorithmId["CRC32"]="crc32";AlgorithmId["CRC32C"]="crc32c";AlgorithmId["SHA1"]="sha1";AlgorithmId["SHA256"]="sha256"})(AlgorithmId||(AlgorithmId={}));var FieldPosition;(function(FieldPosition){FieldPosition[FieldPosition["HEADER"]=0]="HEADER";FieldPosition[FieldPosition["TRAILER"]=1]="TRAILER"})(FieldPosition||(FieldPosition={}));const SMITHY_CONTEXT_KEY="__smithy_context";var IniSectionType;(function(IniSectionType){IniSectionType["PROFILE"]="profile";IniSectionType["SSO_SESSION"]="sso-session";IniSectionType["SERVICES"]="services"})(IniSectionType||(IniSectionType={}));var RequestHandlerProtocol;(function(RequestHandlerProtocol){RequestHandlerProtocol["HTTP_0_9"]="http/0.9";RequestHandlerProtocol["HTTP_1_0"]="http/1.0";RequestHandlerProtocol["TDS_8_0"]="tds/8.0"})(RequestHandlerProtocol||(RequestHandlerProtocol={}));class HttpRequest{constructor(options){this.method=options.method||"GET";this.hostname=options.hostname||"localhost";this.port=options.port;this.query=options.query||{};this.headers=options.headers||{};this.body=options.body;this.protocol=options.protocol?options.protocol.slice(-1)!==":"?`${options.protocol}:`:options.protocol:"https:";this.path=options.path?options.path.charAt(0)!=="/"?`/${options.path}`:options.path:"/";this.username=options.username;this.password=options.password;this.fragment=options.fragment}static clone(request){const cloned=new HttpRequest({...request,headers:{...request.headers}});if(cloned.query){cloned.query=cloneQuery(cloned.query)}return cloned}static isInstance(request){if(!request){return false}const req=request;return"method"in req&&"protocol"in req&&"hostname"in req&&"path"in req&&typeof req["query"]==="object"&&typeof req["headers"]==="object"}clone(){return HttpRequest.clone(this)}}function cloneQuery(query){return Object.keys(query).reduce((carry,paramName)=>{const param=query[paramName];return{...carry,[paramName]:Array.isArray(param)?[...param]:param}},{})}class HttpResponse{constructor(options){this.statusCode=options.statusCode;this.reason=options.reason;this.headers=options.headers||{};this.body=options.body}static isInstance(response){if(!response)return false;const resp=response;return typeof resp.statusCode==="number"&&typeof resp.headers==="object"}}const escapeUri$1=uri=>encodeURIComponent(uri).replace(/[!'()*]/g,hexEncode$1);const hexEncode$1=c=>`%${c.charCodeAt(0).toString(16).toUpperCase()}`;function buildQueryString(query){const parts=[];for(let key of Object.keys(query).sort()){const value=query[key];key=escapeUri$1(key);if(Array.isArray(value)){for(let i=0,iLen=value.length;i<iLen;i++){parts.push(`${key}=${escapeUri$1(value[i])}`)}}else{let qsEntry=key;if(value||typeof value==="string"){qsEntry+=`=${escapeUri$1(value)}`}parts.push(qsEntry)}}return parts.join("&")}function createRequest(url,requestOptions){return new Request(url,requestOptions)}function requestTimeout(){let timeoutInMs=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;return new Promise((resolve,reject)=>{if(timeoutInMs){setTimeout(()=>{const timeoutError=new Error(`Request did not complete within ${timeoutInMs} ms`);timeoutError.name="TimeoutError";reject(timeoutError)},timeoutInMs)}})}const keepAliveSupport={supported:undefined};class FetchHttpHandler{static create(instanceOrOptions){if(typeof instanceOrOptions?.handle==="function"){return instanceOrOptions}return new FetchHttpHandler(instanceOrOptions)}constructor(options){if(typeof options==="function"){this.configProvider=options().then(opts=>opts||{})}else{this.config=options??{};this.configProvider=Promise.resolve(this.config)}if(keepAliveSupport.supported===undefined){keepAliveSupport.supported=Boolean(typeof Request!=="undefined"&&"keepalive"in createRequest("https://[::1]"))}}destroy(){}async handle(request){let{abortSignal}=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(!this.config){this.config=await this.configProvider}const requestTimeoutInMs=this.config.requestTimeout;const keepAlive=this.config.keepAlive===true;const credentials=this.config.credentials;if(abortSignal?.aborted){const abortError=new Error("Request aborted");abortError.name="AbortError";return Promise.reject(abortError)}let path=request.path;const queryString=buildQueryString(request.query||{});if(queryString){path+=`?${queryString}`}if(request.fragment){path+=`#${request.fragment}`}let auth="";if(request.username!=null||request.password!=null){const username=request.username??"";const password=request.password??"";auth=`${username}:${password}@`}const{port,method}=request;const url=`${request.protocol}//${auth}${request.hostname}${port?`:${port}`:""}${path}`;const body=method==="GET"||method==="HEAD"?undefined:request.body;const requestOptions={body,headers:new Headers(request.headers),method:method,credentials};if(this.config?.cache){requestOptions.cache=this.config.cache}if(body){requestOptions.duplex="half"}if(typeof AbortController!=="undefined"){requestOptions.signal=abortSignal}if(keepAliveSupport.supported){requestOptions.keepalive=keepAlive}if(typeof this.config.requestInit==="function"){Object.assign(requestOptions,this.config.requestInit(request))}let removeSignalEventListener=()=>{};const fetchRequest=createRequest(url,requestOptions);const raceOfPromises=[fetch(fetchRequest).then(response=>{const fetchHeaders=response.headers;const transformedHeaders={};for(const pair of fetchHeaders.entries()){transformedHeaders[pair[0]]=pair[1]}const hasReadableStream=response.body!=undefined;if(!hasReadableStream){return response.blob().then(body=>({response:new HttpResponse({headers:transformedHeaders,reason:response.statusText,statusCode:response.status,body})}))}return{response:new HttpResponse({headers:transformedHeaders,reason:response.statusText,statusCode:response.status,body:response.body})}}),requestTimeout(requestTimeoutInMs)];if(abortSignal){raceOfPromises.push(new Promise((resolve,reject)=>{const onAbort=()=>{const abortError=new Error("Request aborted");abortError.name="AbortError";reject(abortError)};if(typeof abortSignal.addEventListener==="function"){const signal=abortSignal;signal.addEventListener("abort",onAbort,{once:true});removeSignalEventListener=()=>signal.removeEventListener("abort",onAbort)}else{abortSignal.onabort=onAbort}}))}return Promise.race(raceOfPromises).finally(removeSignalEventListener)}updateHttpClientConfig(key,value){this.config=undefined;this.configProvider=this.configProvider.then(config=>{config[key]=value;return config})}httpHandlerConfigs(){return this.config??{}}}const alphabetByEncoding={};const alphabetByValue=new Array(64);for(let i=0,start="A".charCodeAt(0),limit="Z".charCodeAt(0);i+start<=limit;i++){const char=String.fromCharCode(i+start);alphabetByEncoding[char]=i;alphabetByValue[i]=char}for(let i=0,start="a".charCodeAt(0),limit="z".charCodeAt(0);i+start<=limit;i++){const char=String.fromCharCode(i+start);const index=i+26;alphabetByEncoding[char]=index;alphabetByValue[index]=char}for(let i=0;i<10;i++){alphabetByEncoding[i.toString(10)]=i+52;const char=i.toString(10);const index=i+52;alphabetByEncoding[char]=index;alphabetByValue[index]=char}alphabetByEncoding["+"]=62;alphabetByValue[62]="+";alphabetByEncoding["/"]=63;alphabetByValue[63]="/";const bitsPerLetter=6;const bitsPerByte=8;const maxLetterValue=63;const fromBase64=input=>{let totalByteLength=input.length/4*3;if(input.slice(-2)==="=="){totalByteLength-=2}else if(input.slice(-1)==="="){totalByteLength--}const out=new ArrayBuffer(totalByteLength);const dataView=new DataView(out);for(let i=0;i<input.length;i+=4){let bits=0;let bitLength=0;for(let j=i,limit=i+3;j<=limit;j++){if(input[j]!=="="){if(!(input[j]in alphabetByEncoding)){throw new TypeError(`Invalid character ${input[j]} in base64 string.`)}bits|=alphabetByEncoding[input[j]]<<(limit-j)*bitsPerLetter;bitLength+=bitsPerLetter}else{bits>>=bitsPerLetter}}const chunkOffset=i/4*3;bits>>=bitLength%bitsPerByte;const byteLength=Math.floor(bitLength/bitsPerByte);for(let k=0;k<byteLength;k++){const offset=(byteLength-k-1)*bitsPerByte;dataView.setUint8(chunkOffset+k,(bits&255<<offset)>>offset)}}return new Uint8Array(out)};const fromUtf8$5=input=>new TextEncoder().encode(input);function toBase64(_input){let input;if(typeof _input==="string"){input=fromUtf8$5(_input)}else{input=_input}const isArrayLike=typeof input==="object"&&typeof input.length==="number";const isUint8Array=typeof input==="object"&&typeof input.byteOffset==="number"&&typeof input.byteLength==="number";if(!isArrayLike&&!isUint8Array){throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.")}let str="";for(let i=0;i<input.length;i+=3){let bits=0;let bitLength=0;for(let j=i,limit=Math.min(i+3,input.length);j<limit;j++){bits|=input[j]<<(limit-j-1)*bitsPerByte;bitLength+=bitsPerByte}const bitClusterCount=Math.ceil(bitLength/bitsPerLetter);bits<<=bitClusterCount*bitsPerLetter-bitLength;for(let k=1;k<=bitClusterCount;k++){const offset=(bitClusterCount-k)*bitsPerLetter;str+=alphabetByValue[(bits&maxLetterValue<<offset)>>offset]}str+="==".slice(0,4-bitClusterCount)}return str}const streamCollector=async stream=>{if(typeof Blob==="function"&&stream instanceof Blob||stream.constructor?.name==="Blob"){if(Blob.prototype.arrayBuffer!==undefined){return new Uint8Array(await stream.arrayBuffer())}return collectBlob(stream)}return collectStream(stream)};async function collectBlob(blob){const base64=await readToBase64(blob);const arrayBuffer=fromBase64(base64);return new Uint8Array(arrayBuffer)}async function collectStream(stream){const chunks=[];const reader=stream.getReader();let isDone=false;let length=0;while(!isDone){const{done,value}=await reader.read();if(value){chunks.push(value);length+=value.length}isDone=done}const collected=new Uint8Array(length);let offset=0;for(const chunk of chunks){collected.set(chunk,offset);offset+=chunk.length}return collected}function readToBase64(blob){return new Promise((resolve,reject)=>{const reader=new FileReader;reader.onloadend=()=>{if(reader.readyState!==2){return reject(new Error("Reader aborted too early"))}const result=reader.result??"";const commaIndex=result.indexOf(",");const dataOffset=commaIndex>-1?commaIndex+1:result.length;resolve(result.substring(dataOffset))};reader.onabort=()=>reject(new Error("Read aborted"));reader.onerror=()=>reject(reader.error);reader.readAsDataURL(blob)})}const getAllAliases=(name,aliases)=>{const _aliases=[];if(name){_aliases.push(name)}if(aliases){for(const alias of aliases){_aliases.push(alias)}}return _aliases};const getMiddlewareNameWithAliases=(name,aliases)=>{return`${name||"anonymous"}${aliases&&aliases.length>0?` (a.k.a. ${aliases.join(",")})`:""}`};const constructStack=()=>{let absoluteEntries=[];let relativeEntries=[];let identifyOnResolve=false;const entriesNameSet=new Set;const sort=entries=>entries.sort((a,b)=>stepWeights[b.step]-stepWeights[a.step]||priorityWeights[b.priority||"normal"]-priorityWeights[a.priority||"normal"]);const removeByName=toRemove=>{let isRemoved=false;const filterCb=entry=>{const aliases=getAllAliases(entry.name,entry.aliases);if(aliases.includes(toRemove)){isRemoved=true;for(const alias of aliases){entriesNameSet.delete(alias)}return false}return true};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved};const removeByReference=toRemove=>{let isRemoved=false;const filterCb=entry=>{if(entry.middleware===toRemove){isRemoved=true;for(const alias of getAllAliases(entry.name,entry.aliases)){entriesNameSet.delete(alias)}return false}return true};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved};const cloneTo=toStack=>{absoluteEntries.forEach(entry=>{toStack.add(entry.middleware,{...entry})});relativeEntries.forEach(entry=>{toStack.addRelativeTo(entry.middleware,{...entry})});toStack.identifyOnResolve?.(stack.identifyOnResolve());return toStack};const expandRelativeMiddlewareList=from=>{const expandedMiddlewareList=[];from.before.forEach(entry=>{if(entry.before.length===0&&entry.after.length===0){expandedMiddlewareList.push(entry)}else{expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry))}});expandedMiddlewareList.push(from);from.after.reverse().forEach(entry=>{if(entry.before.length===0&&entry.after.length===0){expandedMiddlewareList.push(entry)}else{expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry))}});return expandedMiddlewareList};const getMiddlewareList=function(){let debug=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;const normalizedAbsoluteEntries=[];const normalizedRelativeEntries=[];const normalizedEntriesNameMap={};absoluteEntries.forEach(entry=>{const normalizedEntry={...entry,before:[],after:[]};for(const alias of getAllAliases(normalizedEntry.name,normalizedEntry.aliases)){normalizedEntriesNameMap[alias]=normalizedEntry}normalizedAbsoluteEntries.push(normalizedEntry)});relativeEntries.forEach(entry=>{const normalizedEntry={...entry,before:[],after:[]};for(const alias of getAllAliases(normalizedEntry.name,normalizedEntry.aliases)){normalizedEntriesNameMap[alias]=normalizedEntry}normalizedRelativeEntries.push(normalizedEntry)});normalizedRelativeEntries.forEach(entry=>{if(entry.toMiddleware){const toMiddleware=normalizedEntriesNameMap[entry.toMiddleware];if(toMiddleware===undefined){if(debug){return}throw new Error(`${entry.toMiddleware} is not found when adding `+`${getMiddlewareNameWithAliases(entry.name,entry.aliases)} `+`middleware ${entry.relation} ${entry.toMiddleware}`)}if(entry.relation==="after"){toMiddleware.after.push(entry)}if(entry.relation==="before"){toMiddleware.before.push(entry)}}});const mainChain=sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList,expandedMiddlewareList)=>{wholeList.push(...expandedMiddlewareList);return wholeList},[]);return mainChain};const stack={add:function(middleware){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const{name,override,aliases:_aliases}=options;const entry={step:"initialize",priority:"normal",middleware,...options};const aliases=getAllAliases(name,_aliases);if(aliases.length>0){if(aliases.some(alias=>entriesNameSet.has(alias))){if(!override)throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name,_aliases)}'`);for(const alias of aliases){const toOverrideIndex=absoluteEntries.findIndex(entry=>entry.name===alias||entry.aliases?.some(a=>a===alias));if(toOverrideIndex===-1){continue}const toOverride=absoluteEntries[toOverrideIndex];if(toOverride.step!==entry.step||entry.priority!==toOverride.priority){throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name,toOverride.aliases)}" middleware with `+`${toOverride.priority} priority in ${toOverride.step} step cannot `+`be overridden by "${getMiddlewareNameWithAliases(name,_aliases)}" middleware with `+`${entry.priority} priority in ${entry.step} step.`)}absoluteEntries.splice(toOverrideIndex,1)}}for(const alias of aliases){entriesNameSet.add(alias)}}absoluteEntries.push(entry)},addRelativeTo:(middleware,options)=>{const{name,override,aliases:_aliases}=options;const entry={middleware,...options};const aliases=getAllAliases(name,_aliases);if(aliases.length>0){if(aliases.some(alias=>entriesNameSet.has(alias))){if(!override)throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name,_aliases)}'`);for(const alias of aliases){const toOverrideIndex=relativeEntries.findIndex(entry=>entry.name===alias||entry.aliases?.some(a=>a===alias));if(toOverrideIndex===-1){continue}const toOverride=relativeEntries[toOverrideIndex];if(toOverride.toMiddleware!==entry.toMiddleware||toOverride.relation!==entry.relation){throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name,toOverride.aliases)}" middleware `+`${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden `+`by "${getMiddlewareNameWithAliases(name,_aliases)}" middleware ${entry.relation} `+`"${entry.toMiddleware}" middleware.`)}relativeEntries.splice(toOverrideIndex,1)}}for(const alias of aliases){entriesNameSet.add(alias)}}relativeEntries.push(entry)},clone:()=>cloneTo(constructStack()),use:plugin=>{plugin.applyToStack(stack)},remove:toRemove=>{if(typeof toRemove==="string")return removeByName(toRemove);else return removeByReference(toRemove)},removeByTag:toRemove=>{let isRemoved=false;const filterCb=entry=>{const{tags,name,aliases:_aliases}=entry;if(tags&&tags.includes(toRemove)){const aliases=getAllAliases(name,_aliases);for(const alias of aliases){entriesNameSet.delete(alias)}isRemoved=true;return false}return true};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved},concat:from=>{const cloned=cloneTo(constructStack());cloned.use(from);cloned.identifyOnResolve(identifyOnResolve||cloned.identifyOnResolve()||(from.identifyOnResolve?.()??false));return cloned},applyToStack:cloneTo,identify:()=>{return getMiddlewareList(true).map(mw=>{const step=mw.step??mw.relation+" "+mw.toMiddleware;return getMiddlewareNameWithAliases(mw.name,mw.aliases)+" - "+step})},identifyOnResolve(toggle){if(typeof toggle==="boolean")identifyOnResolve=toggle;return identifyOnResolve},resolve:(handler,context)=>{for(const middleware of getMiddlewareList().map(entry=>entry.middleware).reverse()){handler=middleware(handler,context)}if(identifyOnResolve){console.log(stack.identify())}return handler}};return stack};const stepWeights={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1};const priorityWeights={high:3,normal:2,low:1};class Client{constructor(config){this.config=config;this.middlewareStack=constructStack()}send(command,optionsOrCb,cb){const options=typeof optionsOrCb!=="function"?optionsOrCb:undefined;const callback=typeof optionsOrCb==="function"?optionsOrCb:cb;const useHandlerCache=options===undefined&&this.config.cacheMiddleware===true;let handler;if(useHandlerCache){if(!this.handlers){this.handlers=new WeakMap}const handlers=this.handlers;if(handlers.has(command.constructor)){handler=handlers.get(command.constructor)}else{handler=command.resolveMiddleware(this.middlewareStack,this.config,options);handlers.set(command.constructor,handler)}}else{delete this.handlers;handler=command.resolveMiddleware(this.middlewareStack,this.config,options)}if(callback){handler(command).then(result=>callback(null,result.output),err=>callback(err)).catch(()=>{})}else{return handler(command).then(result=>result.output)}}destroy(){this.config?.requestHandler?.destroy?.();delete this.handlers}}const fromUtf8$4=input=>new TextEncoder().encode(input);const toUtf8$1=input=>{if(typeof input==="string"){return input}if(typeof input!=="object"||typeof input.byteOffset!=="number"||typeof input.byteLength!=="number"){throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.")}return new TextDecoder("utf-8").decode(input)};function transformToString(payload){let encoding=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"utf-8";if(encoding==="base64"){return toBase64(payload)}return toUtf8$1(payload)}function transformFromString(str,encoding){if(encoding==="base64"){return Uint8ArrayBlobAdapter.mutate(fromBase64(str))}return Uint8ArrayBlobAdapter.mutate(fromUtf8$4(str))}class Uint8ArrayBlobAdapter extends Uint8Array{static fromString(source){let encoding=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"utf-8";switch(typeof source){case"string":return transformFromString(source,encoding);default:throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`)}}static mutate(source){Object.setPrototypeOf(source,Uint8ArrayBlobAdapter.prototype);return source}transformToString(){let encoding=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"utf-8";return transformToString(this,encoding)}}const SHORT_TO_HEX={};const HEX_TO_SHORT={};for(let i=0;i<256;i++){let encodedByte=i.toString(16).toLowerCase();if(encodedByte.length===1){encodedByte=`0${encodedByte}`}SHORT_TO_HEX[i]=encodedByte;HEX_TO_SHORT[encodedByte]=i}function fromHex(encoded){if(encoded.length%2!==0){throw new Error("Hex encoded strings must have an even number length")}const out=new Uint8Array(encoded.length/2);for(let i=0;i<encoded.length;i+=2){const encodedByte=encoded.slice(i,i+2).toLowerCase();if(encodedByte in HEX_TO_SHORT){out[i/2]=HEX_TO_SHORT[encodedByte]}else{throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`)}}return out}function toHex(bytes){let out="";for(let i=0;i<bytes.byteLength;i++){out+=SHORT_TO_HEX[bytes[i]]}return out}const collectBody=async function(){let streamBody=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Uint8Array;let context=arguments.length>1?arguments[1]:undefined;if(streamBody instanceof Uint8Array){return Uint8ArrayBlobAdapter.mutate(streamBody)}if(!streamBody){return Uint8ArrayBlobAdapter.mutate(new Uint8Array)}const fromContext=context.streamCollector(streamBody);return Uint8ArrayBlobAdapter.mutate(await fromContext)};class Command{constructor(){this.middlewareStack=constructStack()}static classBuilder(){return new ClassBuilder}resolveMiddlewareWithContext(clientStack,configuration,options,_ref3){let{middlewareFn,clientName,commandName,inputFilterSensitiveLog,outputFilterSensitiveLog,smithyContext,additionalContext,CommandCtor}=_ref3;for(const mw of middlewareFn.bind(this)(CommandCtor,clientStack,configuration,options)){this.middlewareStack.use(mw)}const stack=clientStack.concat(this.middlewareStack);const{logger}=configuration;const handlerExecutionContext={logger,clientName,commandName,inputFilterSensitiveLog,outputFilterSensitiveLog,[SMITHY_CONTEXT_KEY]:{commandInstance:this,...smithyContext},...additionalContext};const{requestHandler}=configuration;return stack.resolve(request=>requestHandler.handle(request.request,options||{}),handlerExecutionContext)}}class ClassBuilder{constructor(){this._init=()=>{};this._ep={};this._middlewareFn=()=>[];this._commandName="";this._clientName="";this._additionalContext={};this._smithyContext={};this._inputFilterSensitiveLog=_=>_;this._outputFilterSensitiveLog=_=>_;this._serializer=null;this._deserializer=null}init(cb){this._init=cb}ep(endpointParameterInstructions){this._ep=endpointParameterInstructions;return this}m(middlewareSupplier){this._middlewareFn=middlewareSupplier;return this}s(service,operation){let smithyContext=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};this._smithyContext={service,operation,...smithyContext};return this}c(){let additionalContext=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};this._additionalContext=additionalContext;return this}n(clientName,commandName){this._clientName=clientName;this._commandName=commandName;return this}f(){let inputFilter=arguments.length>0&&arguments[0]!==undefined?arguments[0]:_=>_;let outputFilter=arguments.length>1&&arguments[1]!==undefined?arguments[1]:_=>_;this._inputFilterSensitiveLog=inputFilter;this._outputFilterSensitiveLog=outputFilter;return this}ser(serializer){this._serializer=serializer;return this}de(deserializer){this._deserializer=deserializer;return this}build(){const closure=this;let CommandRef;return CommandRef=class extends Command{static getEndpointParameterInstructions(){return closure._ep}constructor(){for(var _len=arguments.length,_ref4=new Array(_len),_key=0;_key<_len;_key++){_ref4[_key]=arguments[_key]}let[input]=_ref4;super();this.serialize=closure._serializer;this.deserialize=closure._deserializer;this.input=input??{};closure._init(this)}resolveMiddleware(stack,configuration,options){return this.resolveMiddlewareWithContext(stack,configuration,options,{CommandCtor:CommandRef,middlewareFn:closure._middlewareFn,clientName:closure._clientName,commandName:closure._commandName,inputFilterSensitiveLog:closure._inputFilterSensitiveLog,outputFilterSensitiveLog:closure._outputFilterSensitiveLog,smithyContext:closure._smithyContext,additionalContext:closure._additionalContext})}}}}const SENSITIVE_STRING="***SensitiveInformation***";const expectNumber=value=>{if(value===null||value===undefined){return undefined}if(typeof value==="string"){const parsed=parseFloat(value);if(!Number.isNaN(parsed)){if(String(parsed)!==String(value)){logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`))}return parsed}}if(typeof value==="number"){return value}throw new TypeError(`Expected number, got ${typeof value}: ${value}`)};const expectNonNull=(value,location)=>{if(value===null||value===undefined){throw new TypeError("Expected a non-null value")}return value};const expectString=value=>{if(value===null||value===undefined){return undefined}if(typeof value==="string"){return value}if(["boolean","number","bigint"].includes(typeof value)){logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));return String(value)}throw new TypeError(`Expected string, got ${typeof value}: ${value}`)};const strictParseDouble=value=>{if(typeof value=="string"){return expectNumber(parseNumber(value))}return expectNumber(value)};const NUMBER_REGEX=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;const parseNumber=value=>{const matches=value.match(NUMBER_REGEX);if(matches===null||matches[0].length!==value.length){throw new TypeError(`Expected real number, got implicit NaN`)}return parseFloat(value)};const stackTraceWarning=message=>{return String(new TypeError(message).stack||message).split("\n").slice(0,5).filter(s=>!s.includes("stackTraceWarning")).join("\n")};const logger={warn:console.warn};const parseEpochTimestamp=value=>{if(value===null||value===undefined){return undefined}let valueAsDouble;if(typeof value==="number"){valueAsDouble=value}else if(typeof value==="string"){valueAsDouble=strictParseDouble(value)}else if(typeof value==="object"&&value.tag===1){valueAsDouble=value.value}else{throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation")}if(Number.isNaN(valueAsDouble)||valueAsDouble===Infinity||valueAsDouble===-Infinity){throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics")}return new Date(Math.round(valueAsDouble*1000))};class ServiceException extends Error{constructor(options){super(options.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype);this.name=options.name;this.$fault=options.$fault;this.$metadata=options.$metadata}static isInstance(value){if(!value)return false;const candidate=value;return ServiceException.prototype.isPrototypeOf(candidate)||Boolean(candidate.$fault)&&Boolean(candidate.$metadata)&&(candidate.$fault==="client"||candidate.$fault==="server")}static[Symbol.hasInstance](instance){if(!instance)return false;const candidate=instance;if(this===ServiceException){return ServiceException.isInstance(instance)}if(ServiceException.isInstance(instance)){if(candidate.name&&this.name){return this.prototype.isPrototypeOf(instance)||candidate.name===this.name}return this.prototype.isPrototypeOf(instance)}return false}}const decorateServiceException=function(exception){let additions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};Object.entries(additions).filter(_ref5=>{let[,v]=_ref5;return v!==undefined}).forEach(_ref6=>{let[k,v]=_ref6;if(exception[k]==undefined||exception[k]===""){exception[k]=v}});const message=exception.message||exception.Message||"UnknownError";exception.message=message;delete exception.Message;return exception};const throwDefaultError$1=_ref7=>{let{output,parsedBody,exceptionCtor,errorCode}=_ref7;const $metadata=deserializeMetadata$1(output);const statusCode=$metadata.httpStatusCode?$metadata.httpStatusCode+"":undefined;const response=new exceptionCtor({name:parsedBody?.code||parsedBody?.Code||errorCode||statusCode||"UnknownError",$fault:"client",$metadata});throw decorateServiceException(response,parsedBody)};const withBaseException=ExceptionCtor=>{return _ref8=>{let{output,parsedBody,errorCode}=_ref8;throwDefaultError$1({output,parsedBody,exceptionCtor:ExceptionCtor,errorCode})}};const deserializeMetadata$1=output=>({httpStatusCode:output.statusCode,requestId:output.headers["x-amzn-requestid"]??output.headers["x-amzn-request-id"]??output.headers["x-amz-request-id"],extendedRequestId:output.headers["x-amz-id-2"],cfId:output.headers["x-amz-cf-id"]});const loadConfigsForDefaultMode=mode=>{switch(mode){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:30000};default:return{}}};const getChecksumConfiguration=runtimeConfig=>{const checksumAlgorithms=[];for(const id in AlgorithmId){const algorithmId=AlgorithmId[id];if(runtimeConfig[algorithmId]===undefined){continue}checksumAlgorithms.push({algorithmId:()=>algorithmId,checksumConstructor:()=>runtimeConfig[algorithmId]})}return{addChecksumAlgorithm(algo){checksumAlgorithms.push(algo)},checksumAlgorithms(){return checksumAlgorithms}}};const resolveChecksumRuntimeConfig=clientConfig=>{const runtimeConfig={};clientConfig.checksumAlgorithms().forEach(checksumAlgorithm=>{runtimeConfig[checksumAlgorithm.algorithmId()]=checksumAlgorithm.checksumConstructor()});return runtimeConfig};const getRetryConfiguration=runtimeConfig=>{return{setRetryStrategy(retryStrategy){runtimeConfig.retryStrategy=retryStrategy},retryStrategy(){return runtimeConfig.retryStrategy}}};const resolveRetryRuntimeConfig=retryStrategyConfiguration=>{const runtimeConfig={};runtimeConfig.retryStrategy=retryStrategyConfiguration.retryStrategy();return runtimeConfig};const getDefaultExtensionConfiguration=runtimeConfig=>{return Object.assign(getChecksumConfiguration(runtimeConfig),getRetryConfiguration(runtimeConfig))};const resolveDefaultRuntimeConfig=config=>{return Object.assign(resolveChecksumRuntimeConfig(config),resolveRetryRuntimeConfig(config))};class NoOpLogger{trace(){}debug(){}info(){}warn(){}error(){}}const take=(source,instructions)=>{const out={};for(const key in instructions){applyInstruction(out,source,instructions,key)}return out};const applyInstruction=(target,source,instructions,targetKey)=>{if(source!==null){let instruction=instructions[targetKey];if(typeof instruction==="function"){instruction=[,instruction]}const[filter=nonNullish,valueFn=pass,sourceKey=targetKey]=instruction;if(typeof filter==="function"&&filter(source[sourceKey])||typeof filter!=="function"&&!!filter){target[targetKey]=valueFn(source[sourceKey])}return}let[filter,value]=instructions[targetKey];if(typeof value==="function"){let _value;const defaultFilterPassed=filter===undefined&&(_value=value())!=null;const customFilterPassed=typeof filter==="function"&&!!filter(void 0)||typeof filter!=="function"&&!!filter;if(defaultFilterPassed){target[targetKey]=_value}else if(customFilterPassed){target[targetKey]=value()}}else{const defaultFilterPassed=filter===undefined&&value!=null;const customFilterPassed=typeof filter==="function"&&!!filter(value)||typeof filter!=="function"&&!!filter;if(defaultFilterPassed||customFilterPassed){target[targetKey]=value}}};const nonNullish=_=>_!=null;const pass=_=>_;const _json=obj=>{if(obj==null){return{}}if(Array.isArray(obj)){return obj.filter(_=>_!=null).map(_json)}if(typeof obj==="object"){const target={};for(const key of Object.keys(obj)){if(obj[key]==null){continue}target[key]=_json(obj[key])}return target}return obj};const getSmithyContext=context=>context[SMITHY_CONTEXT_KEY]||(context[SMITHY_CONTEXT_KEY]={});const normalizeProvider$1=input=>{if(typeof input==="function")return input;const promisified=Promise.resolve(input);return()=>promisified};const resolveAuthOptions=(candidateAuthOptions,authSchemePreference)=>{if(!authSchemePreference||authSchemePreference.length===0){return candidateAuthOptions}const preferredAuthOptions=[];for(const preferredSchemeName of authSchemePreference){for(const candidateAuthOption of candidateAuthOptions){const candidateAuthSchemeName=candidateAuthOption.schemeId.split("#")[1];if(candidateAuthSchemeName===preferredSchemeName){preferredAuthOptions.push(candidateAuthOption)}}}for(const candidateAuthOption of candidateAuthOptions){if(!preferredAuthOptions.find(_ref9=>{let{schemeId}=_ref9;return schemeId===candidateAuthOption.schemeId})){preferredAuthOptions.push(candidateAuthOption)}}return preferredAuthOptions};function convertHttpAuthSchemesToMap(httpAuthSchemes){const map=new Map;for(const scheme of httpAuthSchemes){map.set(scheme.schemeId,scheme)}return map}const httpAuthSchemeMiddleware=(config,mwOptions)=>(next,context)=>async args=>{const options=config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config,context,args.input));const authSchemePreference=config.authSchemePreference?await config.authSchemePreference():[];const resolvedOptions=resolveAuthOptions(options,authSchemePreference);const authSchemes=convertHttpAuthSchemesToMap(config.httpAuthSchemes);const smithyContext=getSmithyContext(context);const failureReasons=[];for(const option of resolvedOptions){const scheme=authSchemes.get(option.schemeId);if(!scheme){failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);continue}const identityProvider=scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));if(!identityProvider){failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties={},signingProperties={}}=option.propertiesExtractor?.(config,context)||{};option.identityProperties=Object.assign(option.identityProperties||{},identityProperties);option.signingProperties=Object.assign(option.signingProperties||{},signingProperties);smithyContext.selectedHttpAuthScheme={httpAuthOption:option,identity:await identityProvider(option.identityProperties),signer:scheme.signer};break}if(!smithyContext.selectedHttpAuthScheme){throw new Error(failureReasons.join("\n"))}return next(args)};const httpAuthSchemeEndpointRuleSetMiddlewareOptions={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:true,relation:"before",toMiddleware:"endpointV2Middleware"};const getHttpAuthSchemeEndpointRuleSetPlugin=(config,_ref0)=>{let{httpAuthSchemeParametersProvider,identityProviderConfigProvider}=_ref0;return{applyToStack:clientStack=>{clientStack.addRelativeTo(httpAuthSchemeMiddleware(config,{httpAuthSchemeParametersProvider,identityProviderConfigProvider}),httpAuthSchemeEndpointRuleSetMiddlewareOptions)}}};const deserializerMiddleware=(options,deserializer)=>(next,context)=>async args=>{const{response}=await next(args);try{const parsed=await deserializer(response,options);return{response,output:parsed}}catch(error){Object.defineProperty(error,"$response",{value:response});if(!("$metadata"in error)){const hint=`Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;try{error.message+="\n "+hint}catch(e){if(!context.logger||context.logger?.constructor?.name==="NoOpLogger"){console.warn(hint)}else{context.logger?.warn?.(hint)}}if(typeof error.$responseBodyText!=="undefined"){if(error.$response){error.$response.body=error.$responseBodyText}}}throw error}};const serializerMiddleware=(options,serializer)=>(next,context)=>async args=>{const endpoint=context.endpointV2?.url&&options.urlParser?async()=>options.urlParser(context.endpointV2.url):options.endpoint;if(!endpoint){throw new Error("No valid endpoint provider available.")}const request=await serializer(args.input,{...options,endpoint});return next({...args,request})};const deserializerMiddlewareOption={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:true};const serializerMiddlewareOption={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:true};function getSerdePlugin(config,serializer,deserializer){return{applyToStack:commandStack=>{commandStack.add(deserializerMiddleware(config,deserializer),deserializerMiddlewareOption);commandStack.add(serializerMiddleware(config,serializer),serializerMiddlewareOption)}}}({toMiddleware:serializerMiddlewareOption.name});const defaultErrorHandler=signingProperties=>error=>{throw error};const defaultSuccessHandler=(httpResponse,signingProperties)=>{};const httpSigningMiddleware=config=>(next,context)=>async args=>{if(!HttpRequest.isInstance(args.request)){return next(args)}const smithyContext=getSmithyContext(context);const scheme=smithyContext.selectedHttpAuthScheme;if(!scheme){throw new Error(`No HttpAuthScheme was selected: unable to sign request`)}const{httpAuthOption:{signingProperties={}},identity,signer}=scheme;const output=await next({...args,request:await signer.sign(args.request,identity,signingProperties)}).catch((signer.errorHandler||defaultErrorHandler)(signingProperties));(signer.successHandler||defaultSuccessHandler)(output.response,signingProperties);return output};const httpSigningMiddlewareOptions={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:true,relation:"after",toMiddleware:"retryMiddleware"};const getHttpSigningPlugin=config=>({applyToStack:clientStack=>{clientStack.addRelativeTo(httpSigningMiddleware(),httpSigningMiddlewareOptions)}});const normalizeProvider=input=>{if(typeof input==="function")return input;const promisified=Promise.resolve(input);return()=>promisified};function setFeature$1(context,feature,value){if(!context.__smithy_context){context.__smithy_context={features:{}}}else if(!context.__smithy_context.features){context.__smithy_context.features={}}context.__smithy_context.features[feature]=value}class DefaultIdentityProviderConfig{constructor(config){this.authSchemes=new Map;for(const[key,value]of Object.entries(config)){if(value!==undefined){this.authSchemes.set(key,value)}}}getIdentityProvider(schemeId){return this.authSchemes.get(schemeId)}}class NoAuthSigner{async sign(httpRequest,identity,signingProperties){return httpRequest}}const createIsIdentityExpiredFunction=expirationMs=>identity=>doesIdentityRequireRefresh(identity)&&identity.expiration.getTime()-Date.now()<expirationMs;const EXPIRATION_MS=300000;const isIdentityExpired=createIsIdentityExpiredFunction(EXPIRATION_MS);const doesIdentityRequireRefresh=identity=>identity.expiration!==undefined;const memoizeIdentityProvider=(provider,isExpired,requiresRefresh)=>{if(provider===undefined){return undefined}const normalizedProvider=typeof provider!=="function"?async()=>Promise.resolve(provider):provider;let resolved;let pending;let hasResult;let isConstant=false;const coalesceProvider=async options=>{if(!pending){pending=normalizedProvider(options)}try{resolved=await pending;hasResult=true;isConstant=false}finally{pending=undefined}return resolved};if(isExpired===undefined){return async options=>{if(!hasResult||options?.forceRefresh){resolved=await coalesceProvider(options)}return resolved}}return async options=>{if(!hasResult||options?.forceRefresh){resolved=await coalesceProvider(options)}if(isConstant){return resolved}if(!requiresRefresh(resolved)){isConstant=true;return resolved}if(isExpired(resolved)){await coalesceProvider(options);return resolved}return resolved}};/******************************************************************************
5
5
  Copyright (c) Microsoft Corporation.
6
6
 
7
7
  Permission to use, copy, modify, and/or distribute this software for any
@@ -44,7 +44,7 @@ function isEmptyData(data){if(typeof data==="string"){return data.length===0}ret
44
44
  * the default is to expose this as an async method.
45
45
  * However, it can sometimes be useful to have a sync method.
46
46
  */Sha256.prototype.digest=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2/*return*/,this.digestSync()]})})};Sha256.prototype.reset=function(){this.hash=new RawSha256;if(this.secret){this.outer=new RawSha256;var inner=bufferFromSecret(this.secret);var outer=new Uint8Array(BLOCK_SIZE);outer.set(inner);for(var i=0;i<BLOCK_SIZE;i++){inner[i]^=54;outer[i]^=92}this.hash.update(inner);this.outer.update(outer);// overwrite the copied key in memory
47
- for(var i=0;i<inner.byteLength;i++){inner[i]=0}}};return Sha256}();function bufferFromSecret(secret){var input=convertToBuffer(secret);if(input.byteLength>BLOCK_SIZE){var bufferHash=new RawSha256;bufferHash.update(input);input=bufferHash.digest()}var buffer=new Uint8Array(BLOCK_SIZE);buffer.set(input);return buffer}const SHORT_TO_HEX$1={};for(let i=0;i<256;i++){let encodedByte=i.toString(16).toLowerCase();if(encodedByte.length===1){encodedByte=`0${encodedByte}`}SHORT_TO_HEX$1[i]=encodedByte}function toHex$1(bytes){let out="";for(let i=0;i<bytes.byteLength;i++){out+=SHORT_TO_HEX$1[bytes[i]]}return out}/*
47
+ for(var i=0;i<inner.byteLength;i++){inner[i]=0}}};return Sha256}();function bufferFromSecret(secret){var input=convertToBuffer(secret);if(input.byteLength>BLOCK_SIZE){var bufferHash=new RawSha256;bufferHash.update(input);input=bufferHash.digest()}var buffer=new Uint8Array(BLOCK_SIZE);buffer.set(input);return buffer}/*
48
48
  * This is a copied and modified file from https://github.com/aws-amplify/amplify-js/blob/b96a0eddb53e6cb14eac22a2f5d7e0d1039b22d6/packages/core/src/Signer/Signer.ts
49
49
  * which was last modified on 02/13/2024
50
50
  * as well as several classes from https://github.com/aws-amplify/amplify-js/blob/main/packages/core/src/clients/middleware/signing/signer/signatureV4
@@ -68,7 +68,7 @@ const EMPTY_HASH="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b8
68
68
  * @param presignable `Presignable` object containing at least a url to be presigned with authentication query params.
69
69
  * @param presignUrlOptions `PresignUrlOptions` object containing values used to construct the signature.
70
70
  * @returns A `URL` with authentication query params which can grant temporary access to AWS resources.
71
- */const presignUrl=(_ref9,_a)=>{let{body,method="GET",url}=_ref9;var options=__rest(_a,[]);const signingValues=getSigningValues(options);const{accessKeyId,credentialScope,longDate,sessionToken}=signingValues;// create the request to sign
71
+ */const presignUrl=(_ref1,_a)=>{let{body,method="GET",url}=_ref1;var options=__rest(_a,[]);const signingValues=getSigningValues(options);const{accessKeyId,credentialScope,longDate,sessionToken}=signingValues;// create the request to sign
72
72
  const presignedUrl=new URL(url);Object.entries(Object.assign({[ALGORITHM_QUERY_PARAM$1]:SHA256_ALGORITHM_IDENTIFIER,[CREDENTIAL_QUERY_PARAM$1]:`${accessKeyId}/${credentialScope}`,[AMZ_DATE_QUERY_PARAM$1]:longDate,[SIGNED_HEADERS_QUERY_PARAM$1]:HOST_HEADER},sessionToken&&{[TOKEN_QUERY_PARAM$1]:sessionToken})).forEach(_ref10=>{let[key,value]=_ref10;presignedUrl.searchParams.append(key,value)});const requestToSign={body,headers:{[HOST_HEADER]:url.host},method,url:presignedUrl};// calculate and add the signature to the url
73
73
  const signature=getSignature(requestToSign,signingValues);presignedUrl.searchParams.append(SIGNATURE_QUERY_PARAM$1,signature);return presignedUrl};/**
74
74
  * Extracts common values used for signing both requests and urls.
@@ -160,7 +160,8 @@ const signature=getHashedDataAsHex(getSigningKey$1(secretAccessKey,shortDate,sig
160
160
  * @returns List of headers included in canonical headers, separated by semicolons (;). This indicates which headers are
161
161
  * part of the signing process. Header names must use lowercase characters and must appear in alphabetical order.
162
162
  * @internal
163
- */const getSignedHeaders=headers=>Object.keys(headers).map(key=>key.toLowerCase()).sort().join(";");const getHashedPayload=body=>{// Modification - For our use-case, the body is always null,
163
+ */const getSignedHeaders=headers=>Object.keys(headers).map(key=>key.toLowerCase()).sort().join(";");// eslint-disable-next-line @typescript-eslint/no-unused-vars
164
+ const getHashedPayload=body=>{// Modification - For our use-case, the body is always null,
164
165
  // so we just return the EMPTY_HASH
165
166
  // return precalculated empty hash if body is undefined or null
166
167
  return EMPTY_HASH};/**
@@ -176,7 +177,7 @@ return EMPTY_HASH};/**
176
177
  * @param data Hashable `SourceData`.
177
178
  * @returns String using lowercase hexadecimal characters created from the data as input to a hash function.
178
179
  * @internal
179
- */const getHashedDataAsHex=(key,data)=>{const hashedData=getHashedData(key,data);return toHex$1(hashedData)};/**
180
+ */const getHashedDataAsHex=(key,data)=>{const hashedData=getHashedData(key,data);return toHex(hashedData)};/**
180
181
  * Returns a string to be signed.
181
182
  *
182
183
  * @param date Current date in the format 'YYYYMMDDThhmmssZ'.
@@ -208,7 +209,7 @@ return EMPTY_HASH};/**
208
209
  */async function withIdentityPoolId(identityPoolId,options){const region=identityPoolId.split(":")[0];const credentialsProvider=fromCognitoIdentityPool(Object.assign(Object.assign({},options||{}),{identityPoolId,clientConfig:Object.assign(Object.assign({},options&&options.clientConfig?options.clientConfig:{}),{region})}));let credentials;async function refreshCredentials(){credentials=await credentialsProvider();let timeToRefresh=3600000;// default to 1 hour if credentials does not have expiration field
209
210
  if(credentials.expiration){timeToRefresh=credentials.expiration.getTime()-new Date().getTime()}// timeToRefresh minus 1 minute to give some time for the actual refresh to happen.
210
211
  setTimeout(refreshCredentials,timeToRefresh-60000)}await refreshCredentials();const clientConfig={credentials:credentialsProvider,region:region};return{getMapAuthenticationOptions:()=>({transformRequest:(url,resourceType)=>{// Only sign Amazon Location Service URLs
211
- if(url.match(/^https:\/\/maps\.(geo|geo-fips)\.[a-z0-9-]+\.(amazonaws\.com)/)){const urlObj=new URL(url);// Split the pathname into parts, using the filter(Boolean) to ignore any empty parts,
212
+ if(url.match(/^https:\/\/maps\.(geo|geo-fips)\.[a-z0-9-]+\.(amazonaws\.com|api\.aws)/)){const urlObj=new URL(url);// Split the pathname into parts, using the filter(Boolean) to ignore any empty parts,
212
213
  // since the first item will be empty because the pathname looks like:
213
214
  // /v2/styles/Standard/descriptor
214
215
  const pathParts=urlObj.pathname.split("/").filter(Boolean);// The signing service name for the standalone Maps SDK is "geo-maps"
@@ -226,16 +227,16 @@ serviceName="geo"}return{url:Signer.signUrl(url,region,serviceName,{access_key:c
226
227
  */function withAPIKey(apiKey,region){const clientConfig={signer:{sign:async requestToSign=>{var _a;// APIKey in the command can override the APIKey set by auth helper.
227
228
  requestToSign.query=Object.assign({key:apiKey},(_a=requestToSign.query)!==null&&_a!==void 0?_a:{});return requestToSign}},// Empty value to avoid calling the default credential providers chain
228
229
  credentials:async()=>({})};// Include the region, if it was supplied
229
- if(region){clientConfig.region=region}return{getLocationClientConfig:()=>clientConfig,getClientConfig:()=>clientConfig}}function resolveHostHeaderConfig(input){return input}const hostHeaderMiddleware=options=>next=>async args=>{if(!HttpRequest.isInstance(args.request))return next(args);const{request}=args;const{handlerProtocol=""}=options.requestHandler.metadata||{};if(handlerProtocol.indexOf("h2")>=0&&!request.headers[":authority"]){delete request.headers["host"];request.headers[":authority"]=request.hostname+(request.port?":"+request.port:"")}else if(!request.headers["host"]){let host=request.hostname;if(request.port!=null)host+=`:${request.port}`;request.headers["host"]=host}return next(args)};const hostHeaderMiddlewareOptions={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:true};const getHostHeaderPlugin=options=>({applyToStack:clientStack=>{clientStack.add(hostHeaderMiddleware(options),hostHeaderMiddlewareOptions)}});const loggerMiddleware=()=>(next,context)=>async args=>{try{const response=await next(args);const{clientName,commandName,logger,dynamoDbDocumentClientOptions={}}=context;const{overrideInputFilterSensitiveLog,overrideOutputFilterSensitiveLog}=dynamoDbDocumentClientOptions;const inputFilterSensitiveLog=overrideInputFilterSensitiveLog??context.inputFilterSensitiveLog;const outputFilterSensitiveLog=overrideOutputFilterSensitiveLog??context.outputFilterSensitiveLog;const{$metadata,...outputWithoutMetadata}=response.output;logger?.info?.({clientName,commandName,input:inputFilterSensitiveLog(args.input),output:outputFilterSensitiveLog(outputWithoutMetadata),metadata:$metadata});return response}catch(error){const{clientName,commandName,logger,dynamoDbDocumentClientOptions={}}=context;const{overrideInputFilterSensitiveLog}=dynamoDbDocumentClientOptions;const inputFilterSensitiveLog=overrideInputFilterSensitiveLog??context.inputFilterSensitiveLog;logger?.error?.({clientName,commandName,input:inputFilterSensitiveLog(args.input),error,metadata:error.$metadata});throw error}};const loggerMiddlewareOptions={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:true};const getLoggerPlugin=options=>({applyToStack:clientStack=>{clientStack.add(loggerMiddleware(),loggerMiddlewareOptions)}});const TRACE_ID_HEADER_NAME="X-Amzn-Trace-Id";const ENV_LAMBDA_FUNCTION_NAME="AWS_LAMBDA_FUNCTION_NAME";const ENV_TRACE_ID="_X_AMZN_TRACE_ID";const recursionDetectionMiddleware=options=>next=>async args=>{const{request}=args;if(!HttpRequest.isInstance(request)||options.runtime!=="node"||request.headers.hasOwnProperty(TRACE_ID_HEADER_NAME)){return next(args)}const functionName=process.env[ENV_LAMBDA_FUNCTION_NAME];const traceId=process.env[ENV_TRACE_ID];const nonEmptyString=str=>typeof str==="string"&&str.length>0;if(nonEmptyString(functionName)&&nonEmptyString(traceId)){request.headers[TRACE_ID_HEADER_NAME]=traceId}return next({...args,request})};const addRecursionDetectionMiddlewareOptions={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:true,priority:"low"};const getRecursionDetectionPlugin=options=>({applyToStack:clientStack=>{clientStack.add(recursionDetectionMiddleware(options),addRecursionDetectionMiddlewareOptions)}});const getSmithyContext=context=>context[SMITHY_CONTEXT_KEY]||(context[SMITHY_CONTEXT_KEY]={});const normalizeProvider$1=input=>{if(typeof input==="function")return input;const promisified=Promise.resolve(input);return()=>promisified};function convertHttpAuthSchemesToMap(httpAuthSchemes){const map=new Map;for(const scheme of httpAuthSchemes){map.set(scheme.schemeId,scheme)}return map}const httpAuthSchemeMiddleware=(config,mwOptions)=>(next,context)=>async args=>{const options=config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config,context,args.input));const authSchemes=convertHttpAuthSchemesToMap(config.httpAuthSchemes);const smithyContext=getSmithyContext(context);const failureReasons=[];for(const option of options){const scheme=authSchemes.get(option.schemeId);if(!scheme){failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);continue}const identityProvider=scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));if(!identityProvider){failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties={},signingProperties={}}=option.propertiesExtractor?.(config,context)||{};option.identityProperties=Object.assign(option.identityProperties||{},identityProperties);option.signingProperties=Object.assign(option.signingProperties||{},signingProperties);smithyContext.selectedHttpAuthScheme={httpAuthOption:option,identity:await identityProvider(option.identityProperties),signer:scheme.signer};break}if(!smithyContext.selectedHttpAuthScheme){throw new Error(failureReasons.join("\n"))}return next(args)};const httpAuthSchemeEndpointRuleSetMiddlewareOptions={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:true,relation:"before",toMiddleware:"endpointV2Middleware"};const getHttpAuthSchemeEndpointRuleSetPlugin=(config,_ref18)=>{let{httpAuthSchemeParametersProvider,identityProviderConfigProvider}=_ref18;return{applyToStack:clientStack=>{clientStack.addRelativeTo(httpAuthSchemeMiddleware(config,{httpAuthSchemeParametersProvider,identityProviderConfigProvider}),httpAuthSchemeEndpointRuleSetMiddlewareOptions)}}};const deserializerMiddleware=(options,deserializer)=>next=>async args=>{const{response}=await next(args);try{const parsed=await deserializer(response,options);return{response,output:parsed}}catch(error){Object.defineProperty(error,"$response",{value:response});if(!("$metadata"in error)){const hint=`Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;error.message+="\n "+hint;if(typeof error.$responseBodyText!=="undefined"){if(error.$response){error.$response.body=error.$responseBodyText}}}throw error}};const serializerMiddleware=(options,serializer)=>(next,context)=>async args=>{const endpoint=context.endpointV2?.url&&options.urlParser?async()=>options.urlParser(context.endpointV2.url):options.endpoint;if(!endpoint){throw new Error("No valid endpoint provider available.")}const request=await serializer(args.input,{...options,endpoint});return next({...args,request})};const deserializerMiddlewareOption={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:true};const serializerMiddlewareOption={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:true};function getSerdePlugin(config,serializer,deserializer){return{applyToStack:commandStack=>{commandStack.add(deserializerMiddleware(config,deserializer),deserializerMiddlewareOption);commandStack.add(serializerMiddleware(config,serializer),serializerMiddlewareOption)}}}({step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:true,relation:"before",toMiddleware:serializerMiddlewareOption.name});const defaultErrorHandler=signingProperties=>error=>{throw error};const defaultSuccessHandler=(httpResponse,signingProperties)=>{};const httpSigningMiddleware=config=>(next,context)=>async args=>{if(!HttpRequest.isInstance(args.request)){return next(args)}const smithyContext=getSmithyContext(context);const scheme=smithyContext.selectedHttpAuthScheme;if(!scheme){throw new Error(`No HttpAuthScheme was selected: unable to sign request`)}const{httpAuthOption:{signingProperties={}},identity,signer}=scheme;const output=await next({...args,request:await signer.sign(args.request,identity,signingProperties)}).catch((signer.errorHandler||defaultErrorHandler)(signingProperties));(signer.successHandler||defaultSuccessHandler)(output.response,signingProperties);return output};const httpSigningMiddlewareOptions={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:true,relation:"after",toMiddleware:"retryMiddleware"};const getHttpSigningPlugin=config=>({applyToStack:clientStack=>{clientStack.addRelativeTo(httpSigningMiddleware(),httpSigningMiddlewareOptions)}});const normalizeProvider=input=>{if(typeof input==="function")return input;const promisified=Promise.resolve(input);return()=>promisified};function setFeature$1(context,feature,value){if(!context.__smithy_context){context.__smithy_context={features:{}}}else if(!context.__smithy_context.features){context.__smithy_context.features={}}context.__smithy_context.features[feature]=value}class DefaultIdentityProviderConfig{constructor(config){this.authSchemes=new Map;for(const[key,value]of Object.entries(config)){if(value!==undefined){this.authSchemes.set(key,value)}}}getIdentityProvider(schemeId){return this.authSchemes.get(schemeId)}}class NoAuthSigner{async sign(httpRequest,identity,signingProperties){return httpRequest}}const createIsIdentityExpiredFunction=expirationMs=>identity=>doesIdentityRequireRefresh(identity)&&identity.expiration.getTime()-Date.now()<expirationMs;const EXPIRATION_MS=300000;const isIdentityExpired=createIsIdentityExpiredFunction(EXPIRATION_MS);const doesIdentityRequireRefresh=identity=>identity.expiration!==undefined;const memoizeIdentityProvider=(provider,isExpired,requiresRefresh)=>{if(provider===undefined){return undefined}const normalizedProvider=typeof provider!=="function"?async()=>Promise.resolve(provider):provider;let resolved;let pending;let hasResult;let isConstant=false;const coalesceProvider=async options=>{if(!pending){pending=normalizedProvider(options)}try{resolved=await pending;hasResult=true;isConstant=false}finally{pending=undefined}return resolved};if(isExpired===undefined){return async options=>{if(!hasResult||options?.forceRefresh){resolved=await coalesceProvider(options)}return resolved}}return async options=>{if(!hasResult||options?.forceRefresh){resolved=await coalesceProvider(options)}if(isConstant){return resolved}if(!requiresRefresh(resolved)){isConstant=true;return resolved}if(isExpired(resolved)){await coalesceProvider(options);return resolved}return resolved}};const DEFAULT_UA_APP_ID=undefined;function isValidUserAgentAppId(appId){if(appId===undefined){return true}return typeof appId==="string"&&appId.length<=50}function resolveUserAgentConfig(input){const normalizedAppIdProvider=normalizeProvider(input.userAgentAppId??DEFAULT_UA_APP_ID);return{...input,customUserAgent:typeof input.customUserAgent==="string"?[[input.customUserAgent]]:input.customUserAgent,userAgentAppId:async()=>{const appId=await normalizedAppIdProvider();if(!isValidUserAgentAppId(appId)){const logger=input.logger?.constructor?.name==="NoOpLogger"||!input.logger?console:input.logger;if(typeof appId!=="string"){logger?.warn("userAgentAppId must be a string or undefined.")}else if(appId.length>50){logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}}return appId}}}class EndpointCache{constructor(_ref19){let{size,params}=_ref19;this.data=new Map;this.parameters=[];this.capacity=size??50;if(params){this.parameters=params}}get(endpointParams,resolver){const key=this.hash(endpointParams);if(key===false){return resolver()}if(!this.data.has(key)){if(this.data.size>this.capacity+10){const keys=this.data.keys();let i=0;while(true){const{value,done}=keys.next();this.data.delete(value);if(done||++i>10){break}}}this.data.set(key,resolver())}return this.data.get(key)}size(){return this.data.size}hash(endpointParams){let buffer="";const{parameters}=this;if(parameters.length===0){return false}for(const param of parameters){const val=String(endpointParams[param]??"");if(val.includes("|;")){return false}buffer+=val+"|;"}return buffer}}const IP_V4_REGEX=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}$`);const isIpAddress=value=>IP_V4_REGEX.test(value)||value.startsWith("[")&&value.endsWith("]");const VALID_HOST_LABEL_REGEX=new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);const isValidHostLabel=function(value){let allowSubDomains=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!allowSubDomains){return VALID_HOST_LABEL_REGEX.test(value)}const labels=value.split(".");for(const label of labels){if(!isValidHostLabel(label)){return false}}return true};const customEndpointFunctions={};const debugId="endpoints";function toDebugString(input){if(typeof input!=="object"||input==null){return input}if("ref"in input){return`$${toDebugString(input.ref)}`}if("fn"in input){return`${input.fn}(${(input.argv||[]).map(toDebugString).join(", ")})`}return JSON.stringify(input,null,2)}class EndpointError extends Error{constructor(message){super(message);this.name="EndpointError"}}const booleanEquals=(value1,value2)=>value1===value2;const getAttrPathList=path=>{const parts=path.split(".");const pathList=[];for(const part of parts){const squareBracketIndex=part.indexOf("[");if(squareBracketIndex!==-1){if(part.indexOf("]")!==part.length-1){throw new EndpointError(`Path: '${path}' does not end with ']'`)}const arrayIndex=part.slice(squareBracketIndex+1,-1);if(Number.isNaN(parseInt(arrayIndex))){throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`)}if(squareBracketIndex!==0){pathList.push(part.slice(0,squareBracketIndex))}pathList.push(arrayIndex)}else{pathList.push(part)}}return pathList};const getAttr=(value,path)=>getAttrPathList(path).reduce((acc,index)=>{if(typeof acc!=="object"){throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`)}else if(Array.isArray(acc)){return acc[parseInt(index)]}return acc[index]},value);const isSet=value=>value!=null;const not=value=>!value;const DEFAULT_PORTS={[EndpointURLScheme.HTTP]:80,[EndpointURLScheme.HTTPS]:443};const parseURL=value=>{const whatwgURL=(()=>{try{if(value instanceof URL){return value}if(typeof value==="object"&&"hostname"in value){const{hostname,port,protocol="",path="",query={}}=value;const url=new URL(`${protocol}//${hostname}${port?`:${port}`:""}${path}`);url.search=Object.entries(query).map(_ref20=>{let[k,v]=_ref20;return`${k}=${v}`}).join("&");return url}return new URL(value)}catch(error){return null}})();if(!whatwgURL){console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);return null}const urlString=whatwgURL.href;const{host,hostname,pathname,protocol,search}=whatwgURL;if(search){return null}const scheme=protocol.slice(0,-1);if(!Object.values(EndpointURLScheme).includes(scheme)){return null}const isIp=isIpAddress(hostname);const inputContainsDefaultPort=urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`)||typeof value==="string"&&value.includes(`${host}:${DEFAULT_PORTS[scheme]}`);const authority=`${host}${inputContainsDefaultPort?`:${DEFAULT_PORTS[scheme]}`:``}`;return{scheme,authority,path:pathname,normalizedPath:pathname.endsWith("/")?pathname:`${pathname}/`,isIp}};const stringEquals=(value1,value2)=>value1===value2;const substring=(input,start,stop,reverse)=>{if(start>=stop||input.length<stop){return null}if(!reverse){return input.substring(start,stop)}return input.substring(input.length-stop,input.length-start)};const uriEncode=value=>encodeURIComponent(value).replace(/[!*'()]/g,c=>`%${c.charCodeAt(0).toString(16).toUpperCase()}`);const endpointFunctions={booleanEquals,getAttr,isSet,isValidHostLabel,not,parseURL,stringEquals,substring,uriEncode};const evaluateTemplate=(template,options)=>{const evaluatedTemplateArr=[];const templateContext={...options.endpointParams,...options.referenceRecord};let currentIndex=0;while(currentIndex<template.length){const openingBraceIndex=template.indexOf("{",currentIndex);if(openingBraceIndex===-1){evaluatedTemplateArr.push(template.slice(currentIndex));break}evaluatedTemplateArr.push(template.slice(currentIndex,openingBraceIndex));const closingBraceIndex=template.indexOf("}",openingBraceIndex);if(closingBraceIndex===-1){evaluatedTemplateArr.push(template.slice(openingBraceIndex));break}if(template[openingBraceIndex+1]==="{"&&template[closingBraceIndex+1]==="}"){evaluatedTemplateArr.push(template.slice(openingBraceIndex+1,closingBraceIndex));currentIndex=closingBraceIndex+2}const parameterName=template.substring(openingBraceIndex+1,closingBraceIndex);if(parameterName.includes("#")){const[refName,attrName]=parameterName.split("#");evaluatedTemplateArr.push(getAttr(templateContext[refName],attrName))}else{evaluatedTemplateArr.push(templateContext[parameterName])}currentIndex=closingBraceIndex+1}return evaluatedTemplateArr.join("")};const getReferenceValue=(_ref21,options)=>{let{ref}=_ref21;const referenceRecord={...options.endpointParams,...options.referenceRecord};return referenceRecord[ref]};const evaluateExpression=(obj,keyName,options)=>{if(typeof obj==="string"){return evaluateTemplate(obj,options)}else if(obj["fn"]){return callFunction(obj,options)}else if(obj["ref"]){return getReferenceValue(obj,options)}throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`)};const callFunction=(_ref22,options)=>{let{fn,argv}=_ref22;const evaluatedArgs=argv.map(arg=>["boolean","number"].includes(typeof arg)?arg:evaluateExpression(arg,"arg",options));const fnSegments=fn.split(".");if(fnSegments[0]in customEndpointFunctions&&fnSegments[1]!=null){return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs)}return endpointFunctions[fn](...evaluatedArgs)};const evaluateCondition=(_ref23,options)=>{let{assign,...fnArgs}=_ref23;if(assign&&assign in options.referenceRecord){throw new EndpointError(`'${assign}' is already defined in Reference Record.`)}const value=callFunction(fnArgs,options);options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);return{result:value===""?true:!!value,...(assign!=null&&{toAssign:{name:assign,value}})}};const evaluateConditions=function(){let conditions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];let options=arguments.length>1?arguments[1]:undefined;const conditionsReferenceRecord={};for(const condition of conditions){const{result,toAssign}=evaluateCondition(condition,{...options,referenceRecord:{...options.referenceRecord,...conditionsReferenceRecord}});if(!result){return{result}}if(toAssign){conditionsReferenceRecord[toAssign.name]=toAssign.value;options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`)}}return{result:true,referenceRecord:conditionsReferenceRecord}};const getEndpointHeaders=(headers,options)=>Object.entries(headers).reduce((acc,_ref24)=>{let[headerKey,headerVal]=_ref24;return{...acc,[headerKey]:headerVal.map(headerValEntry=>{const processedExpr=evaluateExpression(headerValEntry,"Header value entry",options);if(typeof processedExpr!=="string"){throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`)}return processedExpr})}},{});const getEndpointProperty=(property,options)=>{if(Array.isArray(property)){return property.map(propertyEntry=>getEndpointProperty(propertyEntry,options))}switch(typeof property){case"string":return evaluateTemplate(property,options);case"object":if(property===null){throw new EndpointError(`Unexpected endpoint property: ${property}`)}return getEndpointProperties(property,options);case"boolean":return property;default:throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`)}};const getEndpointProperties=(properties,options)=>Object.entries(properties).reduce((acc,_ref25)=>{let[propertyKey,propertyVal]=_ref25;return{...acc,[propertyKey]:getEndpointProperty(propertyVal,options)}},{});const getEndpointUrl=(endpointUrl,options)=>{const expression=evaluateExpression(endpointUrl,"Endpoint URL",options);if(typeof expression==="string"){try{return new URL(expression)}catch(error){console.error(`Failed to construct URL with ${expression}`,error);throw error}}throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`)};const evaluateEndpointRule=(endpointRule,options)=>{const{conditions,endpoint}=endpointRule;const{result,referenceRecord}=evaluateConditions(conditions,options);if(!result){return}const endpointRuleOptions={...options,referenceRecord:{...options.referenceRecord,...referenceRecord}};const{url,properties,headers}=endpoint;options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`);return{...(headers!=undefined&&{headers:getEndpointHeaders(headers,endpointRuleOptions)}),...(properties!=undefined&&{properties:getEndpointProperties(properties,endpointRuleOptions)}),url:getEndpointUrl(url,endpointRuleOptions)}};const evaluateErrorRule=(errorRule,options)=>{const{conditions,error}=errorRule;const{result,referenceRecord}=evaluateConditions(conditions,options);if(!result){return}throw new EndpointError(evaluateExpression(error,"Error",{...options,referenceRecord:{...options.referenceRecord,...referenceRecord}}))};const evaluateTreeRule=(treeRule,options)=>{const{conditions,rules}=treeRule;const{result,referenceRecord}=evaluateConditions(conditions,options);if(!result){return}return evaluateRules(rules,{...options,referenceRecord:{...options.referenceRecord,...referenceRecord}})};const evaluateRules=(rules,options)=>{for(const rule of rules){if(rule.type==="endpoint"){const endpointOrUndefined=evaluateEndpointRule(rule,options);if(endpointOrUndefined){return endpointOrUndefined}}else if(rule.type==="error"){evaluateErrorRule(rule,options)}else if(rule.type==="tree"){const endpointOrUndefined=evaluateTreeRule(rule,options);if(endpointOrUndefined){return endpointOrUndefined}}else{throw new EndpointError(`Unknown endpoint rule: ${rule}`)}}throw new EndpointError(`Rules evaluation failed`)};const resolveEndpoint=(ruleSetObject,options)=>{const{endpointParams,logger}=options;const{parameters,rules}=ruleSetObject;options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);const paramsWithDefault=Object.entries(parameters).filter(_ref26=>{let[,v]=_ref26;return v.default!=null}).map(_ref27=>{let[k,v]=_ref27;return[k,v.default]});if(paramsWithDefault.length>0){for(const[paramKey,paramDefaultValue]of paramsWithDefault){endpointParams[paramKey]=endpointParams[paramKey]??paramDefaultValue}}const requiredParams=Object.entries(parameters).filter(_ref28=>{let[,v]=_ref28;return v.required}).map(_ref29=>{let[k]=_ref29;return k});for(const requiredParam of requiredParams){if(endpointParams[requiredParam]==null){throw new EndpointError(`Missing required parameter: '${requiredParam}'`)}}const endpoint=evaluateRules(rules,{endpointParams,logger,referenceRecord:{}});options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);return endpoint};const isVirtualHostableS3Bucket=function(value){let allowSubDomains=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(allowSubDomains){for(const label of value.split(".")){if(!isVirtualHostableS3Bucket(label)){return false}}return true}if(!isValidHostLabel(value)){return false}if(value.length<3||value.length>63){return false}if(value!==value.toLowerCase()){return false}if(isIpAddress(value)){return false}return true};const ARN_DELIMITER=":";const RESOURCE_DELIMITER="/";const parseArn=value=>{const segments=value.split(ARN_DELIMITER);if(segments.length<6)return null;const[arn,partition,service,region,accountId,...resourcePath]=segments;if(arn!=="arn"||partition===""||service===""||resourcePath.join(ARN_DELIMITER)==="")return null;const resourceId=resourcePath.map(resource=>resource.split(RESOURCE_DELIMITER)).flat();return{partition,service,region,accountId,resourceId}};var partitions=[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:true,supportsFIPS:true},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:true,supportsFIPS:true},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:true,supportsFIPS:true},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:false,supportsFIPS:true},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:false,supportsFIPS:true},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:false,supportsFIPS:true},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:false,supportsFIPS:true},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{}}];var version$1="1.1";var partitionsInfo={partitions:partitions,version:version$1};let selectedPartitionsInfo=partitionsInfo;const partition=value=>{const{partitions}=selectedPartitionsInfo;for(const partition of partitions){const{regions,outputs}=partition;for(const[region,regionData]of Object.entries(regions)){if(region===value){return{...outputs,...regionData}}}}for(const partition of partitions){const{regionRegex,outputs}=partition;if(new RegExp(regionRegex).test(value)){return{...outputs}}}const DEFAULT_PARTITION=partitions.find(partition=>partition.id==="aws");if(!DEFAULT_PARTITION){throw new Error("Provided region was not found in the partition array or regex,"+" and default partition with id 'aws' doesn't exist.")}return{...DEFAULT_PARTITION.outputs}};const awsEndpointFunctions={isVirtualHostableS3Bucket:isVirtualHostableS3Bucket,parseArn:parseArn,partition:partition};customEndpointFunctions.aws=awsEndpointFunctions;function setCredentialFeature(credentials,feature,value){if(!credentials.$source){credentials.$source={}}credentials.$source[feature]=value;return credentials}function setFeature(context,feature,value){if(!context.__aws_sdk_context){context.__aws_sdk_context={features:{}}}else if(!context.__aws_sdk_context.features){context.__aws_sdk_context.features={}}context.__aws_sdk_context.features[feature]=value}const getDateHeader=response=>HttpResponse.isInstance(response)?response.headers?.date??response.headers?.Date:undefined;const getSkewCorrectedDate=systemClockOffset=>new Date(Date.now()+systemClockOffset);const isClockSkewed=(clockTime,systemClockOffset)=>Math.abs(getSkewCorrectedDate(systemClockOffset).getTime()-clockTime)>=300000;const getUpdatedSystemClockOffset=(clockTime,currentSystemClockOffset)=>{const clockTimeInMs=Date.parse(clockTime);if(isClockSkewed(clockTimeInMs,currentSystemClockOffset)){return clockTimeInMs-Date.now()}return currentSystemClockOffset};const throwSigningPropertyError=(name,property)=>{if(!property){throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`)}return property};const validateSigningProperties=async signingProperties=>{const context=throwSigningPropertyError("context",signingProperties.context);const config=throwSigningPropertyError("config",signingProperties.config);const authScheme=context.endpointV2?.properties?.authSchemes?.[0];const signerFunction=throwSigningPropertyError("signer",config.signer);const signer=await signerFunction(authScheme);const signingRegion=signingProperties?.signingRegion;const signingRegionSet=signingProperties?.signingRegionSet;const signingName=signingProperties?.signingName;return{config,signer,signingRegion,signingRegionSet,signingName}};class AwsSdkSigV4Signer{async sign(httpRequest,identity,signingProperties){if(!HttpRequest.isInstance(httpRequest)){throw new Error("The request is not an instance of `HttpRequest` and cannot be signed")}const validatedProps=await validateSigningProperties(signingProperties);const{config,signer}=validatedProps;let{signingRegion,signingName}=validatedProps;const handlerExecutionContext=signingProperties.context;if(handlerExecutionContext?.authSchemes?.length??0>1){const[first,second]=handlerExecutionContext.authSchemes;if(first?.name==="sigv4a"&&second?.name==="sigv4"){signingRegion=second?.signingRegion??signingRegion;signingName=second?.signingName??signingName}}const signedRequest=await signer.sign(httpRequest,{signingDate:getSkewCorrectedDate(config.systemClockOffset),signingRegion:signingRegion,signingService:signingName});return signedRequest}errorHandler(signingProperties){return error=>{const serverTime=error.ServerTime??getDateHeader(error.$response);if(serverTime){const config=throwSigningPropertyError("config",signingProperties.config);const initialSystemClockOffset=config.systemClockOffset;config.systemClockOffset=getUpdatedSystemClockOffset(serverTime,config.systemClockOffset);const clockSkewCorrected=config.systemClockOffset!==initialSystemClockOffset;if(clockSkewCorrected&&error.$metadata){error.$metadata.clockSkewCorrected=true}}throw error}}successHandler(httpResponse,signingProperties){const dateHeader=getDateHeader(httpResponse);if(dateHeader){const config=throwSigningPropertyError("config",signingProperties.config);config.systemClockOffset=getUpdatedSystemClockOffset(dateHeader,config.systemClockOffset)}}}const SHORT_TO_HEX={};const HEX_TO_SHORT={};for(let i=0;i<256;i++){let encodedByte=i.toString(16).toLowerCase();if(encodedByte.length===1){encodedByte=`0${encodedByte}`}SHORT_TO_HEX[i]=encodedByte;HEX_TO_SHORT[encodedByte]=i}function fromHex(encoded){if(encoded.length%2!==0){throw new Error("Hex encoded strings must have an even number length")}const out=new Uint8Array(encoded.length/2);for(let i=0;i<encoded.length;i+=2){const encodedByte=encoded.slice(i,i+2).toLowerCase();if(encodedByte in HEX_TO_SHORT){out[i/2]=HEX_TO_SHORT[encodedByte]}else{throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`)}}return out}function toHex(bytes){let out="";for(let i=0;i<bytes.byteLength;i++){out+=SHORT_TO_HEX[bytes[i]]}return out}const fromUtf8$1=input=>new TextEncoder().encode(input);const toUint8Array=data=>{if(typeof data==="string"){return fromUtf8$1(data)}if(ArrayBuffer.isView(data)){return new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT)}return new Uint8Array(data)};const ALGORITHM_QUERY_PARAM="X-Amz-Algorithm";const CREDENTIAL_QUERY_PARAM="X-Amz-Credential";const AMZ_DATE_QUERY_PARAM="X-Amz-Date";const SIGNED_HEADERS_QUERY_PARAM="X-Amz-SignedHeaders";const EXPIRES_QUERY_PARAM="X-Amz-Expires";const SIGNATURE_QUERY_PARAM="X-Amz-Signature";const TOKEN_QUERY_PARAM="X-Amz-Security-Token";const AUTH_HEADER="authorization";const AMZ_DATE_HEADER=AMZ_DATE_QUERY_PARAM.toLowerCase();const DATE_HEADER="date";const GENERATED_HEADERS=[AUTH_HEADER,AMZ_DATE_HEADER,DATE_HEADER];const SIGNATURE_HEADER=SIGNATURE_QUERY_PARAM.toLowerCase();const SHA256_HEADER="x-amz-content-sha256";const TOKEN_HEADER=TOKEN_QUERY_PARAM.toLowerCase();const ALWAYS_UNSIGNABLE_HEADERS={authorization:true,"cache-control":true,connection:true,expect:true,from:true,"keep-alive":true,"max-forwards":true,pragma:true,referer:true,te:true,trailer:true,"transfer-encoding":true,upgrade:true,"user-agent":true,"x-amzn-trace-id":true};const PROXY_HEADER_PATTERN=/^proxy-/;const SEC_HEADER_PATTERN=/^sec-/;const ALGORITHM_IDENTIFIER="AWS4-HMAC-SHA256";const EVENT_ALGORITHM_IDENTIFIER="AWS4-HMAC-SHA256-PAYLOAD";const UNSIGNED_PAYLOAD="UNSIGNED-PAYLOAD";const MAX_CACHE_SIZE=50;const KEY_TYPE_IDENTIFIER="aws4_request";const MAX_PRESIGNED_TTL=60*60*24*7;const signingKeyCache={};const cacheQueue=[];const createScope=(shortDate,region,service)=>`${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;const getSigningKey=async(sha256Constructor,credentials,shortDate,region,service)=>{const credsHash=await hmac(sha256Constructor,credentials.secretAccessKey,credentials.accessKeyId);const cacheKey=`${shortDate}:${region}:${service}:${toHex(credsHash)}:${credentials.sessionToken}`;if(cacheKey in signingKeyCache){return signingKeyCache[cacheKey]}cacheQueue.push(cacheKey);while(cacheQueue.length>MAX_CACHE_SIZE){delete signingKeyCache[cacheQueue.shift()]}let key=`AWS4${credentials.secretAccessKey}`;for(const signable of[shortDate,region,service,KEY_TYPE_IDENTIFIER]){key=await hmac(sha256Constructor,key,signable)}return signingKeyCache[cacheKey]=key};const hmac=(ctor,secret,data)=>{const hash=new ctor(secret);hash.update(toUint8Array(data));return hash.digest()};const getCanonicalHeaders=(_ref30,unsignableHeaders,signableHeaders)=>{let{headers}=_ref30;const canonical={};for(const headerName of Object.keys(headers).sort()){if(headers[headerName]==undefined){continue}const canonicalHeaderName=headerName.toLowerCase();if(canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS||unsignableHeaders?.has(canonicalHeaderName)||PROXY_HEADER_PATTERN.test(canonicalHeaderName)||SEC_HEADER_PATTERN.test(canonicalHeaderName)){if(!signableHeaders||signableHeaders&&!signableHeaders.has(canonicalHeaderName)){continue}}canonical[canonicalHeaderName]=headers[headerName].trim().replace(/\s+/g," ")}return canonical};const getCanonicalQuery=_ref31=>{let{query={}}=_ref31;const keys=[];const serialized={};for(const key of Object.keys(query)){if(key.toLowerCase()===SIGNATURE_HEADER){continue}const encodedKey=escapeUri$1(key);keys.push(encodedKey);const value=query[key];if(typeof value==="string"){serialized[encodedKey]=`${encodedKey}=${escapeUri$1(value)}`}else if(Array.isArray(value)){serialized[encodedKey]=value.slice(0).reduce((encoded,value)=>encoded.concat([`${encodedKey}=${escapeUri$1(value)}`]),[]).sort().join("&")}}return keys.sort().map(key=>serialized[key]).filter(serialized=>serialized).join("&")};const isArrayBuffer=arg=>typeof ArrayBuffer==="function"&&arg instanceof ArrayBuffer||Object.prototype.toString.call(arg)==="[object ArrayBuffer]";const getPayloadHash=async(_ref32,hashConstructor)=>{let{headers,body}=_ref32;for(const headerName of Object.keys(headers)){if(headerName.toLowerCase()===SHA256_HEADER){return headers[headerName]}}if(body==undefined){return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}else if(typeof body==="string"||ArrayBuffer.isView(body)||isArrayBuffer(body)){const hashCtor=new hashConstructor;hashCtor.update(toUint8Array(body));return toHex(await hashCtor.digest())}return UNSIGNED_PAYLOAD};class HeaderFormatter{format(headers){const chunks=[];for(const headerName of Object.keys(headers)){const bytes=fromUtf8$1(headerName);chunks.push(Uint8Array.from([bytes.byteLength]),bytes,this.formatHeaderValue(headers[headerName]))}const out=new Uint8Array(chunks.reduce((carry,bytes)=>carry+bytes.byteLength,0));let position=0;for(const chunk of chunks){out.set(chunk,position);position+=chunk.byteLength}return out}formatHeaderValue(header){switch(header.type){case"boolean":return Uint8Array.from([header.value?0:1]);case"byte":return Uint8Array.from([2,header.value]);case"short":const shortView=new DataView(new ArrayBuffer(3));shortView.setUint8(0,3);shortView.setInt16(1,header.value,false);return new Uint8Array(shortView.buffer);case"integer":const intView=new DataView(new ArrayBuffer(5));intView.setUint8(0,4);intView.setInt32(1,header.value,false);return new Uint8Array(intView.buffer);case"long":const longBytes=new Uint8Array(9);longBytes[0]=5;longBytes.set(header.value.bytes,1);return longBytes;case"binary":const binView=new DataView(new ArrayBuffer(3+header.value.byteLength));binView.setUint8(0,6);binView.setUint16(1,header.value.byteLength,false);const binBytes=new Uint8Array(binView.buffer);binBytes.set(header.value,3);return binBytes;case"string":const utf8Bytes=fromUtf8$1(header.value);const strView=new DataView(new ArrayBuffer(3+utf8Bytes.byteLength));strView.setUint8(0,7);strView.setUint16(1,utf8Bytes.byteLength,false);const strBytes=new Uint8Array(strView.buffer);strBytes.set(utf8Bytes,3);return strBytes;case"timestamp":const tsBytes=new Uint8Array(9);tsBytes[0]=8;tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes,1);return tsBytes;case"uuid":if(!UUID_PATTERN.test(header.value)){throw new Error(`Invalid UUID received: ${header.value}`)}const uuidBytes=new Uint8Array(17);uuidBytes[0]=9;uuidBytes.set(fromHex(header.value.replace(/\-/g,"")),1);return uuidBytes}}}var HEADER_VALUE_TYPE;(function(HEADER_VALUE_TYPE){HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolTrue"]=0]="boolTrue";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolFalse"]=1]="boolFalse";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byte"]=2]="byte";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["short"]=3]="short";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["integer"]=4]="integer";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["long"]=5]="long";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byteArray"]=6]="byteArray";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["string"]=7]="string";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["timestamp"]=8]="timestamp";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["uuid"]=9]="uuid"})(HEADER_VALUE_TYPE||(HEADER_VALUE_TYPE={}));const UUID_PATTERN=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Int64{constructor(bytes){this.bytes=bytes;if(bytes.byteLength!==8){throw new Error("Int64 buffers must be exactly 8 bytes")}}static fromNumber(number){if(number>9223372036854776000||number<-9223372036854776000){throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`)}const bytes=new Uint8Array(8);for(let i=7,remaining=Math.abs(Math.round(number));i>-1&&remaining>0;i--,remaining/=256){bytes[i]=remaining}if(number<0){negate(bytes)}return new Int64(bytes)}valueOf(){const bytes=this.bytes.slice(0);const negative=bytes[0]&128;if(negative){negate(bytes)}return parseInt(toHex(bytes),16)*(negative?-1:1)}toString(){return String(this.valueOf())}}function negate(bytes){for(let i=0;i<8;i++){bytes[i]^=255}for(let i=7;i>-1;i--){bytes[i]++;if(bytes[i]!==0)break}}const hasHeader=(soughtHeader,headers)=>{soughtHeader=soughtHeader.toLowerCase();for(const headerName of Object.keys(headers)){if(soughtHeader===headerName.toLowerCase()){return true}}return false};const moveHeadersToQuery=function(request){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const{headers,query={}}=HttpRequest.clone(request);for(const name of Object.keys(headers)){const lname=name.toLowerCase();if(lname.slice(0,6)==="x-amz-"&&!options.unhoistableHeaders?.has(lname)||options.hoistableHeaders?.has(lname)){query[name]=headers[name];delete headers[name]}}return{...request,headers,query}};const prepareRequest=request=>{request=HttpRequest.clone(request);for(const headerName of Object.keys(request.headers)){if(GENERATED_HEADERS.indexOf(headerName.toLowerCase())>-1){delete request.headers[headerName]}}return request};const iso8601=time=>toDate(time).toISOString().replace(/\.\d{3}Z$/,"Z");const toDate=time=>{if(typeof time==="number"){return new Date(time*1000)}if(typeof time==="string"){if(Number(time)){return new Date(Number(time)*1000)}return new Date(time)}return time};class SignatureV4{constructor(_ref33){let{applyChecksum,credentials,region,service,sha256,uriEscapePath=true}=_ref33;this.headerFormatter=new HeaderFormatter;this.service=service;this.sha256=sha256;this.uriEscapePath=uriEscapePath;this.applyChecksum=typeof applyChecksum==="boolean"?applyChecksum:true;this.regionProvider=normalizeProvider$1(region);this.credentialProvider=normalizeProvider$1(credentials)}async presign(originalRequest){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const{signingDate=new Date,expiresIn=3600,unsignableHeaders,unhoistableHeaders,signableHeaders,hoistableHeaders,signingRegion,signingService}=options;const credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=signingRegion??(await this.regionProvider());const{longDate,shortDate}=formatDate(signingDate);if(expiresIn>MAX_PRESIGNED_TTL){return Promise.reject("Signature version 4 presigned URLs"+" must have an expiration date less than one week in"+" the future")}const scope=createScope(shortDate,region,signingService??this.service);const request=moveHeadersToQuery(prepareRequest(originalRequest),{unhoistableHeaders,hoistableHeaders});if(credentials.sessionToken){request.query[TOKEN_QUERY_PARAM]=credentials.sessionToken}request.query[ALGORITHM_QUERY_PARAM]=ALGORITHM_IDENTIFIER;request.query[CREDENTIAL_QUERY_PARAM]=`${credentials.accessKeyId}/${scope}`;request.query[AMZ_DATE_QUERY_PARAM]=longDate;request.query[EXPIRES_QUERY_PARAM]=expiresIn.toString(10);const canonicalHeaders=getCanonicalHeaders(request,unsignableHeaders,signableHeaders);request.query[SIGNED_HEADERS_QUERY_PARAM]=getCanonicalHeaderList(canonicalHeaders);request.query[SIGNATURE_QUERY_PARAM]=await this.getSignature(longDate,scope,this.getSigningKey(credentials,region,shortDate,signingService),this.createCanonicalRequest(request,canonicalHeaders,await getPayloadHash(originalRequest,this.sha256)));return request}async sign(toSign,options){if(typeof toSign==="string"){return this.signString(toSign,options)}else if(toSign.headers&&toSign.payload){return this.signEvent(toSign,options)}else if(toSign.message){return this.signMessage(toSign,options)}else{return this.signRequest(toSign,options)}}async signEvent(_ref34,_ref35){let{headers,payload}=_ref34;let{signingDate=new Date,priorSignature,signingRegion,signingService}=_ref35;const region=signingRegion??(await this.regionProvider());const{shortDate,longDate}=formatDate(signingDate);const scope=createScope(shortDate,region,signingService??this.service);const hashedPayload=await getPayloadHash({headers:{},body:payload},this.sha256);const hash=new this.sha256;hash.update(headers);const hashedHeaders=toHex(await hash.digest());const stringToSign=[EVENT_ALGORITHM_IDENTIFIER,longDate,scope,priorSignature,hashedHeaders,hashedPayload].join("\n");return this.signString(stringToSign,{signingDate,signingRegion:region,signingService})}async signMessage(signableMessage,_ref36){let{signingDate=new Date,signingRegion,signingService}=_ref36;const promise=this.signEvent({headers:this.headerFormatter.format(signableMessage.message.headers),payload:signableMessage.message.body},{signingDate,signingRegion,signingService,priorSignature:signableMessage.priorSignature});return promise.then(signature=>{return{message:signableMessage.message,signature}})}async signString(stringToSign){let{signingDate=new Date,signingRegion,signingService}=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=signingRegion??(await this.regionProvider());const{shortDate}=formatDate(signingDate);const hash=new this.sha256(await this.getSigningKey(credentials,region,shortDate,signingService));hash.update(toUint8Array(stringToSign));return toHex(await hash.digest())}async signRequest(requestToSign){let{signingDate=new Date,signableHeaders,unsignableHeaders,signingRegion,signingService}=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=signingRegion??(await this.regionProvider());const request=prepareRequest(requestToSign);const{longDate,shortDate}=formatDate(signingDate);const scope=createScope(shortDate,region,signingService??this.service);request.headers[AMZ_DATE_HEADER]=longDate;if(credentials.sessionToken){request.headers[TOKEN_HEADER]=credentials.sessionToken}const payloadHash=await getPayloadHash(request,this.sha256);if(!hasHeader(SHA256_HEADER,request.headers)&&this.applyChecksum){request.headers[SHA256_HEADER]=payloadHash}const canonicalHeaders=getCanonicalHeaders(request,unsignableHeaders,signableHeaders);const signature=await this.getSignature(longDate,scope,this.getSigningKey(credentials,region,shortDate,signingService),this.createCanonicalRequest(request,canonicalHeaders,payloadHash));request.headers[AUTH_HEADER]=`${ALGORITHM_IDENTIFIER} `+`Credential=${credentials.accessKeyId}/${scope}, `+`SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, `+`Signature=${signature}`;return request}createCanonicalRequest(request,canonicalHeaders,payloadHash){const sortedHeaders=Object.keys(canonicalHeaders).sort();return`${request.method}
230
+ if(region){clientConfig.region=region}return{getLocationClientConfig:()=>clientConfig,getClientConfig:()=>clientConfig}}function resolveHostHeaderConfig(input){return input}const hostHeaderMiddleware=options=>next=>async args=>{if(!HttpRequest.isInstance(args.request))return next(args);const{request}=args;const{handlerProtocol=""}=options.requestHandler.metadata||{};if(handlerProtocol.indexOf("h2")>=0&&!request.headers[":authority"]){delete request.headers["host"];request.headers[":authority"]=request.hostname+(request.port?":"+request.port:"")}else if(!request.headers["host"]){let host=request.hostname;if(request.port!=null)host+=`:${request.port}`;request.headers["host"]=host}return next(args)};const hostHeaderMiddlewareOptions={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:true};const getHostHeaderPlugin=options=>({applyToStack:clientStack=>{clientStack.add(hostHeaderMiddleware(options),hostHeaderMiddlewareOptions)}});const loggerMiddleware=()=>(next,context)=>async args=>{try{const response=await next(args);const{clientName,commandName,logger,dynamoDbDocumentClientOptions={}}=context;const{overrideInputFilterSensitiveLog,overrideOutputFilterSensitiveLog}=dynamoDbDocumentClientOptions;const inputFilterSensitiveLog=overrideInputFilterSensitiveLog??context.inputFilterSensitiveLog;const outputFilterSensitiveLog=overrideOutputFilterSensitiveLog??context.outputFilterSensitiveLog;const{$metadata,...outputWithoutMetadata}=response.output;logger?.info?.({clientName,commandName,input:inputFilterSensitiveLog(args.input),output:outputFilterSensitiveLog(outputWithoutMetadata),metadata:$metadata});return response}catch(error){const{clientName,commandName,logger,dynamoDbDocumentClientOptions={}}=context;const{overrideInputFilterSensitiveLog}=dynamoDbDocumentClientOptions;const inputFilterSensitiveLog=overrideInputFilterSensitiveLog??context.inputFilterSensitiveLog;logger?.error?.({clientName,commandName,input:inputFilterSensitiveLog(args.input),error,metadata:error.$metadata});throw error}};const loggerMiddlewareOptions={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:true};const getLoggerPlugin=options=>({applyToStack:clientStack=>{clientStack.add(loggerMiddleware(),loggerMiddlewareOptions)}});const TRACE_ID_HEADER_NAME="X-Amzn-Trace-Id";const ENV_LAMBDA_FUNCTION_NAME="AWS_LAMBDA_FUNCTION_NAME";const ENV_TRACE_ID="_X_AMZN_TRACE_ID";const recursionDetectionMiddleware=options=>next=>async args=>{const{request}=args;if(!HttpRequest.isInstance(request)||options.runtime!=="node"){return next(args)}const traceIdHeader=Object.keys(request.headers??{}).find(h=>h.toLowerCase()===TRACE_ID_HEADER_NAME.toLowerCase())??TRACE_ID_HEADER_NAME;if(request.headers.hasOwnProperty(traceIdHeader)){return next(args)}const functionName=process.env[ENV_LAMBDA_FUNCTION_NAME];const traceId=process.env[ENV_TRACE_ID];const nonEmptyString=str=>typeof str==="string"&&str.length>0;if(nonEmptyString(functionName)&&nonEmptyString(traceId)){request.headers[TRACE_ID_HEADER_NAME]=traceId}return next({...args,request})};const addRecursionDetectionMiddlewareOptions={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:true,priority:"low"};const getRecursionDetectionPlugin=options=>({applyToStack:clientStack=>{clientStack.add(recursionDetectionMiddleware(options),addRecursionDetectionMiddlewareOptions)}});const DEFAULT_UA_APP_ID=undefined;function isValidUserAgentAppId(appId){if(appId===undefined){return true}return typeof appId==="string"&&appId.length<=50}function resolveUserAgentConfig(input){const normalizedAppIdProvider=normalizeProvider(input.userAgentAppId??DEFAULT_UA_APP_ID);const{customUserAgent}=input;return Object.assign(input,{customUserAgent:typeof customUserAgent==="string"?[[customUserAgent]]:customUserAgent,userAgentAppId:async()=>{const appId=await normalizedAppIdProvider();if(!isValidUserAgentAppId(appId)){const logger=input.logger?.constructor?.name==="NoOpLogger"||!input.logger?console:input.logger;if(typeof appId!=="string"){logger?.warn("userAgentAppId must be a string or undefined.")}else if(appId.length>50){logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}}return appId}})}class EndpointCache{constructor(_ref18){let{size,params}=_ref18;this.data=new Map;this.parameters=[];this.capacity=size??50;if(params){this.parameters=params}}get(endpointParams,resolver){const key=this.hash(endpointParams);if(key===false){return resolver()}if(!this.data.has(key)){if(this.data.size>this.capacity+10){const keys=this.data.keys();let i=0;while(true){const{value,done}=keys.next();this.data.delete(value);if(done||++i>10){break}}}this.data.set(key,resolver())}return this.data.get(key)}size(){return this.data.size}hash(endpointParams){let buffer="";const{parameters}=this;if(parameters.length===0){return false}for(const param of parameters){const val=String(endpointParams[param]??"");if(val.includes("|;")){return false}buffer+=val+"|;"}return buffer}}const IP_V4_REGEX=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}$`);const isIpAddress=value=>IP_V4_REGEX.test(value)||value.startsWith("[")&&value.endsWith("]");const VALID_HOST_LABEL_REGEX=new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);const isValidHostLabel=function(value){let allowSubDomains=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!allowSubDomains){return VALID_HOST_LABEL_REGEX.test(value)}const labels=value.split(".");for(const label of labels){if(!isValidHostLabel(label)){return false}}return true};const customEndpointFunctions={};const debugId="endpoints";function toDebugString(input){if(typeof input!=="object"||input==null){return input}if("ref"in input){return`$${toDebugString(input.ref)}`}if("fn"in input){return`${input.fn}(${(input.argv||[]).map(toDebugString).join(", ")})`}return JSON.stringify(input,null,2)}class EndpointError extends Error{constructor(message){super(message);this.name="EndpointError"}}const booleanEquals=(value1,value2)=>value1===value2;const getAttrPathList=path=>{const parts=path.split(".");const pathList=[];for(const part of parts){const squareBracketIndex=part.indexOf("[");if(squareBracketIndex!==-1){if(part.indexOf("]")!==part.length-1){throw new EndpointError(`Path: '${path}' does not end with ']'`)}const arrayIndex=part.slice(squareBracketIndex+1,-1);if(Number.isNaN(parseInt(arrayIndex))){throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`)}if(squareBracketIndex!==0){pathList.push(part.slice(0,squareBracketIndex))}pathList.push(arrayIndex)}else{pathList.push(part)}}return pathList};const getAttr=(value,path)=>getAttrPathList(path).reduce((acc,index)=>{if(typeof acc!=="object"){throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`)}else if(Array.isArray(acc)){return acc[parseInt(index)]}return acc[index]},value);const isSet=value=>value!=null;const not=value=>!value;const DEFAULT_PORTS={[EndpointURLScheme.HTTP]:80,[EndpointURLScheme.HTTPS]:443};const parseURL=value=>{const whatwgURL=(()=>{try{if(value instanceof URL){return value}if(typeof value==="object"&&"hostname"in value){const{hostname,port,protocol="",path="",query={}}=value;const url=new URL(`${protocol}//${hostname}${port?`:${port}`:""}${path}`);url.search=Object.entries(query).map(_ref19=>{let[k,v]=_ref19;return`${k}=${v}`}).join("&");return url}return new URL(value)}catch(error){return null}})();if(!whatwgURL){console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);return null}const urlString=whatwgURL.href;const{host,hostname,pathname,protocol,search}=whatwgURL;if(search){return null}const scheme=protocol.slice(0,-1);if(!Object.values(EndpointURLScheme).includes(scheme)){return null}const isIp=isIpAddress(hostname);const inputContainsDefaultPort=urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`)||typeof value==="string"&&value.includes(`${host}:${DEFAULT_PORTS[scheme]}`);const authority=`${host}${inputContainsDefaultPort?`:${DEFAULT_PORTS[scheme]}`:``}`;return{scheme,authority,path:pathname,normalizedPath:pathname.endsWith("/")?pathname:`${pathname}/`,isIp}};const stringEquals=(value1,value2)=>value1===value2;const substring=(input,start,stop,reverse)=>{if(start>=stop||input.length<stop){return null}if(!reverse){return input.substring(start,stop)}return input.substring(input.length-stop,input.length-start)};const uriEncode=value=>encodeURIComponent(value).replace(/[!*'()]/g,c=>`%${c.charCodeAt(0).toString(16).toUpperCase()}`);const endpointFunctions={booleanEquals,getAttr,isSet,isValidHostLabel,not,parseURL,stringEquals,substring,uriEncode};const evaluateTemplate=(template,options)=>{const evaluatedTemplateArr=[];const templateContext={...options.endpointParams,...options.referenceRecord};let currentIndex=0;while(currentIndex<template.length){const openingBraceIndex=template.indexOf("{",currentIndex);if(openingBraceIndex===-1){evaluatedTemplateArr.push(template.slice(currentIndex));break}evaluatedTemplateArr.push(template.slice(currentIndex,openingBraceIndex));const closingBraceIndex=template.indexOf("}",openingBraceIndex);if(closingBraceIndex===-1){evaluatedTemplateArr.push(template.slice(openingBraceIndex));break}if(template[openingBraceIndex+1]==="{"&&template[closingBraceIndex+1]==="}"){evaluatedTemplateArr.push(template.slice(openingBraceIndex+1,closingBraceIndex));currentIndex=closingBraceIndex+2}const parameterName=template.substring(openingBraceIndex+1,closingBraceIndex);if(parameterName.includes("#")){const[refName,attrName]=parameterName.split("#");evaluatedTemplateArr.push(getAttr(templateContext[refName],attrName))}else{evaluatedTemplateArr.push(templateContext[parameterName])}currentIndex=closingBraceIndex+1}return evaluatedTemplateArr.join("")};const getReferenceValue=(_ref20,options)=>{let{ref}=_ref20;const referenceRecord={...options.endpointParams,...options.referenceRecord};return referenceRecord[ref]};const evaluateExpression=(obj,keyName,options)=>{if(typeof obj==="string"){return evaluateTemplate(obj,options)}else if(obj["fn"]){return callFunction(obj,options)}else if(obj["ref"]){return getReferenceValue(obj,options)}throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`)};const callFunction=(_ref21,options)=>{let{fn,argv}=_ref21;const evaluatedArgs=argv.map(arg=>["boolean","number"].includes(typeof arg)?arg:evaluateExpression(arg,"arg",options));const fnSegments=fn.split(".");if(fnSegments[0]in customEndpointFunctions&&fnSegments[1]!=null){return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs)}return endpointFunctions[fn](...evaluatedArgs)};const evaluateCondition=(_ref22,options)=>{let{assign,...fnArgs}=_ref22;if(assign&&assign in options.referenceRecord){throw new EndpointError(`'${assign}' is already defined in Reference Record.`)}const value=callFunction(fnArgs,options);options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);return{result:value===""?true:!!value,...(assign!=null&&{toAssign:{name:assign,value}})}};const evaluateConditions=function(){let conditions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];let options=arguments.length>1?arguments[1]:undefined;const conditionsReferenceRecord={};for(const condition of conditions){const{result,toAssign}=evaluateCondition(condition,{...options,referenceRecord:{...options.referenceRecord,...conditionsReferenceRecord}});if(!result){return{result}}if(toAssign){conditionsReferenceRecord[toAssign.name]=toAssign.value;options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`)}}return{result:true,referenceRecord:conditionsReferenceRecord}};const getEndpointHeaders=(headers,options)=>Object.entries(headers).reduce((acc,_ref23)=>{let[headerKey,headerVal]=_ref23;return{...acc,[headerKey]:headerVal.map(headerValEntry=>{const processedExpr=evaluateExpression(headerValEntry,"Header value entry",options);if(typeof processedExpr!=="string"){throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`)}return processedExpr})}},{});const getEndpointProperty=(property,options)=>{if(Array.isArray(property)){return property.map(propertyEntry=>getEndpointProperty(propertyEntry,options))}switch(typeof property){case"string":return evaluateTemplate(property,options);case"object":if(property===null){throw new EndpointError(`Unexpected endpoint property: ${property}`)}return getEndpointProperties(property,options);case"boolean":return property;default:throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`)}};const getEndpointProperties=(properties,options)=>Object.entries(properties).reduce((acc,_ref24)=>{let[propertyKey,propertyVal]=_ref24;return{...acc,[propertyKey]:getEndpointProperty(propertyVal,options)}},{});const getEndpointUrl=(endpointUrl,options)=>{const expression=evaluateExpression(endpointUrl,"Endpoint URL",options);if(typeof expression==="string"){try{return new URL(expression)}catch(error){console.error(`Failed to construct URL with ${expression}`,error);throw error}}throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`)};const evaluateEndpointRule=(endpointRule,options)=>{const{conditions,endpoint}=endpointRule;const{result,referenceRecord}=evaluateConditions(conditions,options);if(!result){return}const endpointRuleOptions={...options,referenceRecord:{...options.referenceRecord,...referenceRecord}};const{url,properties,headers}=endpoint;options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`);return{...(headers!=undefined&&{headers:getEndpointHeaders(headers,endpointRuleOptions)}),...(properties!=undefined&&{properties:getEndpointProperties(properties,endpointRuleOptions)}),url:getEndpointUrl(url,endpointRuleOptions)}};const evaluateErrorRule=(errorRule,options)=>{const{conditions,error}=errorRule;const{result,referenceRecord}=evaluateConditions(conditions,options);if(!result){return}throw new EndpointError(evaluateExpression(error,"Error",{...options,referenceRecord:{...options.referenceRecord,...referenceRecord}}))};const evaluateTreeRule=(treeRule,options)=>{const{conditions,rules}=treeRule;const{result,referenceRecord}=evaluateConditions(conditions,options);if(!result){return}return evaluateRules(rules,{...options,referenceRecord:{...options.referenceRecord,...referenceRecord}})};const evaluateRules=(rules,options)=>{for(const rule of rules){if(rule.type==="endpoint"){const endpointOrUndefined=evaluateEndpointRule(rule,options);if(endpointOrUndefined){return endpointOrUndefined}}else if(rule.type==="error"){evaluateErrorRule(rule,options)}else if(rule.type==="tree"){const endpointOrUndefined=evaluateTreeRule(rule,options);if(endpointOrUndefined){return endpointOrUndefined}}else{throw new EndpointError(`Unknown endpoint rule: ${rule}`)}}throw new EndpointError(`Rules evaluation failed`)};const resolveEndpoint=(ruleSetObject,options)=>{const{endpointParams,logger}=options;const{parameters,rules}=ruleSetObject;options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);const paramsWithDefault=Object.entries(parameters).filter(_ref25=>{let[,v]=_ref25;return v.default!=null}).map(_ref26=>{let[k,v]=_ref26;return[k,v.default]});if(paramsWithDefault.length>0){for(const[paramKey,paramDefaultValue]of paramsWithDefault){endpointParams[paramKey]=endpointParams[paramKey]??paramDefaultValue}}const requiredParams=Object.entries(parameters).filter(_ref27=>{let[,v]=_ref27;return v.required}).map(_ref28=>{let[k]=_ref28;return k});for(const requiredParam of requiredParams){if(endpointParams[requiredParam]==null){throw new EndpointError(`Missing required parameter: '${requiredParam}'`)}}const endpoint=evaluateRules(rules,{endpointParams,logger,referenceRecord:{}});options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);return endpoint};const isVirtualHostableS3Bucket=function(value){let allowSubDomains=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(allowSubDomains){for(const label of value.split(".")){if(!isVirtualHostableS3Bucket(label)){return false}}return true}if(!isValidHostLabel(value)){return false}if(value.length<3||value.length>63){return false}if(value!==value.toLowerCase()){return false}if(isIpAddress(value)){return false}return true};const ARN_DELIMITER=":";const RESOURCE_DELIMITER="/";const parseArn=value=>{const segments=value.split(ARN_DELIMITER);if(segments.length<6)return null;const[arn,partition,service,region,accountId,...resourcePath]=segments;if(arn!=="arn"||partition===""||service===""||resourcePath.join(ARN_DELIMITER)==="")return null;const resourceId=resourcePath.map(resource=>resource.split(RESOURCE_DELIMITER)).flat();return{partition,service,region,accountId,resourceId}};var partitions=[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:true,supportsFIPS:true},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)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"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)"},"mx-central-1":{description:"Mexico (Central)"},"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:true,supportsFIPS:true},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:true,supportsFIPS:true},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:false,supportsFIPS:true},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:false,supportsFIPS:true},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:false,supportsFIPS:true},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"AWS ISOE (Europe) global region"},"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:false,supportsFIPS:true},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"AWS ISOF global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"amazonaws.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:false,supportsFIPS:true},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"EU (Germany)"}}}];var partitionsInfo={partitions:partitions};let selectedPartitionsInfo=partitionsInfo;const partition=value=>{const{partitions}=selectedPartitionsInfo;for(const partition of partitions){const{regions,outputs}=partition;for(const[region,regionData]of Object.entries(regions)){if(region===value){return{...outputs,...regionData}}}}for(const partition of partitions){const{regionRegex,outputs}=partition;if(new RegExp(regionRegex).test(value)){return{...outputs}}}const DEFAULT_PARTITION=partitions.find(partition=>partition.id==="aws");if(!DEFAULT_PARTITION){throw new Error("Provided region was not found in the partition array or regex,"+" and default partition with id 'aws' doesn't exist.")}return{...DEFAULT_PARTITION.outputs}};const awsEndpointFunctions={isVirtualHostableS3Bucket:isVirtualHostableS3Bucket,parseArn:parseArn,partition:partition};customEndpointFunctions.aws=awsEndpointFunctions;function setCredentialFeature(credentials,feature,value){if(!credentials.$source){credentials.$source={}}credentials.$source[feature]=value;return credentials}function setFeature(context,feature,value){if(!context.__aws_sdk_context){context.__aws_sdk_context={features:{}}}else if(!context.__aws_sdk_context.features){context.__aws_sdk_context.features={}}context.__aws_sdk_context.features[feature]=value}const getDateHeader=response=>HttpResponse.isInstance(response)?response.headers?.date??response.headers?.Date:undefined;const getSkewCorrectedDate=systemClockOffset=>new Date(Date.now()+systemClockOffset);const isClockSkewed=(clockTime,systemClockOffset)=>Math.abs(getSkewCorrectedDate(systemClockOffset).getTime()-clockTime)>=300000;const getUpdatedSystemClockOffset=(clockTime,currentSystemClockOffset)=>{const clockTimeInMs=Date.parse(clockTime);if(isClockSkewed(clockTimeInMs,currentSystemClockOffset)){return clockTimeInMs-Date.now()}return currentSystemClockOffset};const throwSigningPropertyError=(name,property)=>{if(!property){throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`)}return property};const validateSigningProperties=async signingProperties=>{const context=throwSigningPropertyError("context",signingProperties.context);const config=throwSigningPropertyError("config",signingProperties.config);const authScheme=context.endpointV2?.properties?.authSchemes?.[0];const signerFunction=throwSigningPropertyError("signer",config.signer);const signer=await signerFunction(authScheme);const signingRegion=signingProperties?.signingRegion;const signingRegionSet=signingProperties?.signingRegionSet;const signingName=signingProperties?.signingName;return{config,signer,signingRegion,signingRegionSet,signingName}};class AwsSdkSigV4Signer{async sign(httpRequest,identity,signingProperties){if(!HttpRequest.isInstance(httpRequest)){throw new Error("The request is not an instance of `HttpRequest` and cannot be signed")}const validatedProps=await validateSigningProperties(signingProperties);const{config,signer}=validatedProps;let{signingRegion,signingName}=validatedProps;const handlerExecutionContext=signingProperties.context;if(handlerExecutionContext?.authSchemes?.length??0>1){const[first,second]=handlerExecutionContext.authSchemes;if(first?.name==="sigv4a"&&second?.name==="sigv4"){signingRegion=second?.signingRegion??signingRegion;signingName=second?.signingName??signingName}}const signedRequest=await signer.sign(httpRequest,{signingDate:getSkewCorrectedDate(config.systemClockOffset),signingRegion:signingRegion,signingService:signingName});return signedRequest}errorHandler(signingProperties){return error=>{const serverTime=error.ServerTime??getDateHeader(error.$response);if(serverTime){const config=throwSigningPropertyError("config",signingProperties.config);const initialSystemClockOffset=config.systemClockOffset;config.systemClockOffset=getUpdatedSystemClockOffset(serverTime,config.systemClockOffset);const clockSkewCorrected=config.systemClockOffset!==initialSystemClockOffset;if(clockSkewCorrected&&error.$metadata){error.$metadata.clockSkewCorrected=true}}throw error}}successHandler(httpResponse,signingProperties){const dateHeader=getDateHeader(httpResponse);if(dateHeader){const config=throwSigningPropertyError("config",signingProperties.config);config.systemClockOffset=getUpdatedSystemClockOffset(dateHeader,config.systemClockOffset)}}}const fromUtf8$1=input=>new TextEncoder().encode(input);const toUint8Array=data=>{if(typeof data==="string"){return fromUtf8$1(data)}if(ArrayBuffer.isView(data)){return new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT)}return new Uint8Array(data)};const ALGORITHM_QUERY_PARAM="X-Amz-Algorithm";const CREDENTIAL_QUERY_PARAM="X-Amz-Credential";const AMZ_DATE_QUERY_PARAM="X-Amz-Date";const SIGNED_HEADERS_QUERY_PARAM="X-Amz-SignedHeaders";const EXPIRES_QUERY_PARAM="X-Amz-Expires";const SIGNATURE_QUERY_PARAM="X-Amz-Signature";const TOKEN_QUERY_PARAM="X-Amz-Security-Token";const AUTH_HEADER="authorization";const AMZ_DATE_HEADER=AMZ_DATE_QUERY_PARAM.toLowerCase();const DATE_HEADER="date";const GENERATED_HEADERS=[AUTH_HEADER,AMZ_DATE_HEADER,DATE_HEADER];const SIGNATURE_HEADER=SIGNATURE_QUERY_PARAM.toLowerCase();const SHA256_HEADER="x-amz-content-sha256";const TOKEN_HEADER=TOKEN_QUERY_PARAM.toLowerCase();const ALWAYS_UNSIGNABLE_HEADERS={authorization:true,"cache-control":true,connection:true,expect:true,from:true,"keep-alive":true,"max-forwards":true,pragma:true,referer:true,te:true,trailer:true,"transfer-encoding":true,upgrade:true,"user-agent":true,"x-amzn-trace-id":true};const PROXY_HEADER_PATTERN=/^proxy-/;const SEC_HEADER_PATTERN=/^sec-/;const ALGORITHM_IDENTIFIER="AWS4-HMAC-SHA256";const EVENT_ALGORITHM_IDENTIFIER="AWS4-HMAC-SHA256-PAYLOAD";const UNSIGNED_PAYLOAD="UNSIGNED-PAYLOAD";const MAX_CACHE_SIZE=50;const KEY_TYPE_IDENTIFIER="aws4_request";const MAX_PRESIGNED_TTL=60*60*24*7;const signingKeyCache={};const cacheQueue=[];const createScope=(shortDate,region,service)=>`${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;const getSigningKey=async(sha256Constructor,credentials,shortDate,region,service)=>{const credsHash=await hmac(sha256Constructor,credentials.secretAccessKey,credentials.accessKeyId);const cacheKey=`${shortDate}:${region}:${service}:${toHex(credsHash)}:${credentials.sessionToken}`;if(cacheKey in signingKeyCache){return signingKeyCache[cacheKey]}cacheQueue.push(cacheKey);while(cacheQueue.length>MAX_CACHE_SIZE){delete signingKeyCache[cacheQueue.shift()]}let key=`AWS4${credentials.secretAccessKey}`;for(const signable of[shortDate,region,service,KEY_TYPE_IDENTIFIER]){key=await hmac(sha256Constructor,key,signable)}return signingKeyCache[cacheKey]=key};const hmac=(ctor,secret,data)=>{const hash=new ctor(secret);hash.update(toUint8Array(data));return hash.digest()};const getCanonicalHeaders=(_ref29,unsignableHeaders,signableHeaders)=>{let{headers}=_ref29;const canonical={};for(const headerName of Object.keys(headers).sort()){if(headers[headerName]==undefined){continue}const canonicalHeaderName=headerName.toLowerCase();if(canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS||unsignableHeaders?.has(canonicalHeaderName)||PROXY_HEADER_PATTERN.test(canonicalHeaderName)||SEC_HEADER_PATTERN.test(canonicalHeaderName)){if(!signableHeaders||signableHeaders&&!signableHeaders.has(canonicalHeaderName)){continue}}canonical[canonicalHeaderName]=headers[headerName].trim().replace(/\s+/g," ")}return canonical};const isArrayBuffer=arg=>typeof ArrayBuffer==="function"&&arg instanceof ArrayBuffer||Object.prototype.toString.call(arg)==="[object ArrayBuffer]";const getPayloadHash=async(_ref30,hashConstructor)=>{let{headers,body}=_ref30;for(const headerName of Object.keys(headers)){if(headerName.toLowerCase()===SHA256_HEADER){return headers[headerName]}}if(body==undefined){return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}else if(typeof body==="string"||ArrayBuffer.isView(body)||isArrayBuffer(body)){const hashCtor=new hashConstructor;hashCtor.update(toUint8Array(body));return toHex(await hashCtor.digest())}return UNSIGNED_PAYLOAD};class HeaderFormatter{format(headers){const chunks=[];for(const headerName of Object.keys(headers)){const bytes=fromUtf8$1(headerName);chunks.push(Uint8Array.from([bytes.byteLength]),bytes,this.formatHeaderValue(headers[headerName]))}const out=new Uint8Array(chunks.reduce((carry,bytes)=>carry+bytes.byteLength,0));let position=0;for(const chunk of chunks){out.set(chunk,position);position+=chunk.byteLength}return out}formatHeaderValue(header){switch(header.type){case"boolean":return Uint8Array.from([header.value?0:1]);case"byte":return Uint8Array.from([2,header.value]);case"short":const shortView=new DataView(new ArrayBuffer(3));shortView.setUint8(0,3);shortView.setInt16(1,header.value,false);return new Uint8Array(shortView.buffer);case"integer":const intView=new DataView(new ArrayBuffer(5));intView.setUint8(0,4);intView.setInt32(1,header.value,false);return new Uint8Array(intView.buffer);case"long":const longBytes=new Uint8Array(9);longBytes[0]=5;longBytes.set(header.value.bytes,1);return longBytes;case"binary":const binView=new DataView(new ArrayBuffer(3+header.value.byteLength));binView.setUint8(0,6);binView.setUint16(1,header.value.byteLength,false);const binBytes=new Uint8Array(binView.buffer);binBytes.set(header.value,3);return binBytes;case"string":const utf8Bytes=fromUtf8$1(header.value);const strView=new DataView(new ArrayBuffer(3+utf8Bytes.byteLength));strView.setUint8(0,7);strView.setUint16(1,utf8Bytes.byteLength,false);const strBytes=new Uint8Array(strView.buffer);strBytes.set(utf8Bytes,3);return strBytes;case"timestamp":const tsBytes=new Uint8Array(9);tsBytes[0]=8;tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes,1);return tsBytes;case"uuid":if(!UUID_PATTERN.test(header.value)){throw new Error(`Invalid UUID received: ${header.value}`)}const uuidBytes=new Uint8Array(17);uuidBytes[0]=9;uuidBytes.set(fromHex(header.value.replace(/\-/g,"")),1);return uuidBytes}}}var HEADER_VALUE_TYPE;(function(HEADER_VALUE_TYPE){HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolTrue"]=0]="boolTrue";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["boolFalse"]=1]="boolFalse";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byte"]=2]="byte";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["short"]=3]="short";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["integer"]=4]="integer";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["long"]=5]="long";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["byteArray"]=6]="byteArray";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["string"]=7]="string";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["timestamp"]=8]="timestamp";HEADER_VALUE_TYPE[HEADER_VALUE_TYPE["uuid"]=9]="uuid"})(HEADER_VALUE_TYPE||(HEADER_VALUE_TYPE={}));const UUID_PATTERN=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Int64{constructor(bytes){this.bytes=bytes;if(bytes.byteLength!==8){throw new Error("Int64 buffers must be exactly 8 bytes")}}static fromNumber(number){if(number>9223372036854776000||number<-9223372036854776e3){throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`)}const bytes=new Uint8Array(8);for(let i=7,remaining=Math.abs(Math.round(number));i>-1&&remaining>0;i--,remaining/=256){bytes[i]=remaining}if(number<0){negate(bytes)}return new Int64(bytes)}valueOf(){const bytes=this.bytes.slice(0);const negative=bytes[0]&128;if(negative){negate(bytes)}return parseInt(toHex(bytes),16)*(negative?-1:1)}toString(){return String(this.valueOf())}}function negate(bytes){for(let i=0;i<8;i++){bytes[i]^=255}for(let i=7;i>-1;i--){bytes[i]++;if(bytes[i]!==0)break}}const hasHeader=(soughtHeader,headers)=>{soughtHeader=soughtHeader.toLowerCase();for(const headerName of Object.keys(headers)){if(soughtHeader===headerName.toLowerCase()){return true}}return false};const moveHeadersToQuery=function(request){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const{headers,query={}}=HttpRequest.clone(request);for(const name of Object.keys(headers)){const lname=name.toLowerCase();if(lname.slice(0,6)==="x-amz-"&&!options.unhoistableHeaders?.has(lname)||options.hoistableHeaders?.has(lname)){query[name]=headers[name];delete headers[name]}}return{...request,headers,query}};const prepareRequest=request=>{request=HttpRequest.clone(request);for(const headerName of Object.keys(request.headers)){if(GENERATED_HEADERS.indexOf(headerName.toLowerCase())>-1){delete request.headers[headerName]}}return request};const getCanonicalQuery=_ref31=>{let{query={}}=_ref31;const keys=[];const serialized={};for(const key of Object.keys(query)){if(key.toLowerCase()===SIGNATURE_HEADER){continue}const encodedKey=escapeUri$1(key);keys.push(encodedKey);const value=query[key];if(typeof value==="string"){serialized[encodedKey]=`${encodedKey}=${escapeUri$1(value)}`}else if(Array.isArray(value)){serialized[encodedKey]=value.slice(0).reduce((encoded,value)=>encoded.concat([`${encodedKey}=${escapeUri$1(value)}`]),[]).sort().join("&")}}return keys.sort().map(key=>serialized[key]).filter(serialized=>serialized).join("&")};const iso8601=time=>toDate(time).toISOString().replace(/\.\d{3}Z$/,"Z");const toDate=time=>{if(typeof time==="number"){return new Date(time*1000)}if(typeof time==="string"){if(Number(time)){return new Date(Number(time)*1000)}return new Date(time)}return time};class SignatureV4Base{constructor(_ref32){let{applyChecksum,credentials,region,service,sha256,uriEscapePath=true}=_ref32;this.service=service;this.sha256=sha256;this.uriEscapePath=uriEscapePath;this.applyChecksum=typeof applyChecksum==="boolean"?applyChecksum:true;this.regionProvider=normalizeProvider$1(region);this.credentialProvider=normalizeProvider$1(credentials)}createCanonicalRequest(request,canonicalHeaders,payloadHash){const sortedHeaders=Object.keys(canonicalHeaders).sort();return`${request.method}
230
231
  ${this.getCanonicalPath(request)}
231
232
  ${getCanonicalQuery(request)}
232
233
  ${sortedHeaders.map(name=>`${name}:${canonicalHeaders[name]}`).join("\n")}
233
234
 
234
235
  ${sortedHeaders.join(";")}
235
- ${payloadHash}`}async createStringToSign(longDate,credentialScope,canonicalRequest){const hash=new this.sha256;hash.update(toUint8Array(canonicalRequest));const hashedRequest=await hash.digest();return`${ALGORITHM_IDENTIFIER}
236
+ ${payloadHash}`}async createStringToSign(longDate,credentialScope,canonicalRequest,algorithmIdentifier){const hash=new this.sha256;hash.update(toUint8Array(canonicalRequest));const hashedRequest=await hash.digest();return`${algorithmIdentifier}
236
237
  ${longDate}
237
238
  ${credentialScope}
238
- ${toHex(hashedRequest)}`}getCanonicalPath(_ref37){let{path}=_ref37;if(this.uriEscapePath){const normalizedPathSegments=[];for(const pathSegment of path.split("/")){if(pathSegment?.length===0)continue;if(pathSegment===".")continue;if(pathSegment===".."){normalizedPathSegments.pop()}else{normalizedPathSegments.push(pathSegment)}}const normalizedPath=`${path?.startsWith("/")?"/":""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length>0&&path?.endsWith("/")?"/":""}`;const doubleEncoded=escapeUri$1(normalizedPath);return doubleEncoded.replace(/%2F/g,"/")}return path}async getSignature(longDate,credentialScope,keyPromise,canonicalRequest){const stringToSign=await this.createStringToSign(longDate,credentialScope,canonicalRequest);const hash=new this.sha256(await keyPromise);hash.update(toUint8Array(stringToSign));return toHex(await hash.digest())}getSigningKey(credentials,region,shortDate,service){return getSigningKey(this.sha256,credentials,shortDate,region,service||this.service)}validateResolvedCredentials(credentials){if(typeof credentials!=="object"||typeof credentials.accessKeyId!=="string"||typeof credentials.secretAccessKey!=="string"){throw new Error("Resolved credential object is not valid")}}}const formatDate=now=>{const longDate=iso8601(now).replace(/[\-:]/g,"");return{longDate,shortDate:longDate.slice(0,8)}};const getCanonicalHeaderList=headers=>Object.keys(headers).sort().join(";");const resolveAwsSdkSigV4Config=config=>{let isUserSupplied=false;let normalizedCreds;if(config.credentials){isUserSupplied=true;normalizedCreds=memoizeIdentityProvider(config.credentials,isIdentityExpired,doesIdentityRequireRefresh)}if(!normalizedCreds){if(config.credentialDefaultProvider){normalizedCreds=normalizeProvider(config.credentialDefaultProvider(Object.assign({},config,{parentClientConfig:config})))}else{normalizedCreds=async()=>{throw new Error("`credentials` is missing")}}}const{signingEscapePath=true,systemClockOffset=config.systemClockOffset||0,sha256}=config;let signer;if(config.signer){signer=normalizeProvider(config.signer)}else if(config.regionInfoProvider){signer=()=>normalizeProvider(config.region)().then(async region=>[(await config.regionInfoProvider(region,{useFipsEndpoint:await config.useFipsEndpoint(),useDualstackEndpoint:await config.useDualstackEndpoint()}))||{},region]).then(_ref38=>{let[regionInfo,region]=_ref38;const{signingRegion,signingService}=regionInfo;config.signingRegion=config.signingRegion||signingRegion||region;config.signingName=config.signingName||signingService||config.serviceId;const params={...config,credentials:normalizedCreds,region:config.signingRegion,service:config.signingName,sha256,uriEscapePath:signingEscapePath};const SignerCtor=config.signerConstructor||SignatureV4;return new SignerCtor(params)})}else{signer=async authScheme=>{authScheme=Object.assign({},{name:"sigv4",signingName:config.signingName||config.defaultSigningName,signingRegion:await normalizeProvider(config.region)(),properties:{}},authScheme);const signingRegion=authScheme.signingRegion;const signingService=authScheme.signingName;config.signingRegion=config.signingRegion||signingRegion;config.signingName=config.signingName||signingService||config.serviceId;const params={...config,credentials:normalizedCreds,region:config.signingRegion,service:config.signingName,sha256,uriEscapePath:signingEscapePath};const SignerCtor=config.signerConstructor||SignatureV4;return new SignerCtor(params)}}return{...config,systemClockOffset,signingEscapePath,credentials:isUserSupplied?async()=>normalizedCreds().then(creds=>setCredentialFeature(creds,"CREDENTIALS_CODE","e")):normalizedCreds,signer}};const collectBodyString=(streamBody,context)=>collectBody(streamBody,context).then(body=>context.utf8Encoder(body));const parseJsonBody=(streamBody,context)=>collectBodyString(streamBody,context).then(encoded=>{if(encoded.length){try{return JSON.parse(encoded)}catch(e){if(e?.name==="SyntaxError"){Object.defineProperty(e,"$responseBodyText",{value:encoded})}throw e}}return{}});const parseJsonErrorBody=async(errorBody,context)=>{const value=await parseJsonBody(errorBody,context);value.message=value.message??value.Message;return value};const loadRestJsonErrorCode=(output,data)=>{const findKey=(object,key)=>Object.keys(object).find(k=>k.toLowerCase()===key.toLowerCase());const sanitizeErrorCode=rawValue=>{let cleanValue=rawValue;if(typeof cleanValue==="number"){cleanValue=cleanValue.toString()}if(cleanValue.indexOf(",")>=0){cleanValue=cleanValue.split(",")[0]}if(cleanValue.indexOf(":")>=0){cleanValue=cleanValue.split(":")[0]}if(cleanValue.indexOf("#")>=0){cleanValue=cleanValue.split("#")[1]}return cleanValue};const headerKey=findKey(output.headers,"x-amzn-errortype");if(headerKey!==undefined){return sanitizeErrorCode(output.headers[headerKey])}if(data.code!==undefined){return sanitizeErrorCode(data.code)}if(data["__type"]!==undefined){return sanitizeErrorCode(data["__type"])}};var commonjsGlobal=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}const ACCOUNT_ID_ENDPOINT_REGEX=/\d{12}\.ddb/;async function checkFeatures(context,config,args){const request=args.request;if(request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"){setFeature(context,"PROTOCOL_RPC_V2_CBOR","M")}if(typeof config.retryStrategy==="function"){const retryStrategy=await config.retryStrategy();if(typeof retryStrategy.acquireInitialRetryToken==="function"){if(retryStrategy.constructor?.name?.includes("Adaptive")){setFeature(context,"RETRY_MODE_ADAPTIVE","F")}else{setFeature(context,"RETRY_MODE_STANDARD","E")}}else{setFeature(context,"RETRY_MODE_LEGACY","D")}}if(typeof config.accountIdEndpointMode==="function"){const endpointV2=context.endpointV2;if(String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)){setFeature(context,"ACCOUNT_ID_ENDPOINT","O")}switch(await config.accountIdEndpointMode?.()){case"disabled":setFeature(context,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":setFeature(context,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":setFeature(context,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const identity=context.__smithy_context?.selectedHttpAuthScheme?.identity;if(identity?.$source){const credentials=identity;if(credentials.accountId){setFeature(context,"RESOLVED_ACCOUNT_ID","T")}for(const[key,value]of Object.entries(credentials.$source??{})){setFeature(context,key,value)}}}const USER_AGENT="user-agent";const X_AMZ_USER_AGENT="x-amz-user-agent";const SPACE=" ";const UA_NAME_SEPARATOR="/";const UA_NAME_ESCAPE_REGEX=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;const UA_VALUE_ESCAPE_REGEX=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;const UA_ESCAPE_CHAR="-";const BYTE_LIMIT=1024;function encodeFeatures(features){let buffer="";for(const key in features){const val=features[key];if(buffer.length+val.length+1<=BYTE_LIMIT){if(buffer.length){buffer+=","+val}else{buffer+=val}continue}break}return buffer}const userAgentMiddleware=options=>(next,context)=>async args=>{const{request}=args;if(!HttpRequest.isInstance(request)){return next(args)}const{headers}=request;const userAgent=context?.userAgent?.map(escapeUserAgent)||[];const defaultUserAgent=(await options.defaultUserAgentProvider()).map(escapeUserAgent);await checkFeatures(context,options,args);const awsContext=context;defaultUserAgent.push(`m/${encodeFeatures(Object.assign({},context.__smithy_context?.features,awsContext.__aws_sdk_context?.features))}`);const customUserAgent=options?.customUserAgent?.map(escapeUserAgent)||[];const appId=await options.userAgentAppId();if(appId){defaultUserAgent.push(escapeUserAgent([`app/${appId}`]))}const sdkUserAgentValue=[].concat([...defaultUserAgent,...userAgent,...customUserAgent]).join(SPACE);const normalUAValue=[...defaultUserAgent.filter(section=>section.startsWith("aws-sdk-")),...customUserAgent].join(SPACE);if(options.runtime!=="browser"){if(normalUAValue){headers[X_AMZ_USER_AGENT]=headers[X_AMZ_USER_AGENT]?`${headers[USER_AGENT]} ${normalUAValue}`:normalUAValue}headers[USER_AGENT]=sdkUserAgentValue}else{headers[X_AMZ_USER_AGENT]=sdkUserAgentValue}return next({...args,request})};const escapeUserAgent=userAgentPair=>{const name=userAgentPair[0].split(UA_NAME_SEPARATOR).map(part=>part.replace(UA_NAME_ESCAPE_REGEX,UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR);const version=userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX,UA_ESCAPE_CHAR);const prefixSeparatorIndex=name.indexOf(UA_NAME_SEPARATOR);const prefix=name.substring(0,prefixSeparatorIndex);let uaName=name.substring(prefixSeparatorIndex+1);if(prefix==="api"){uaName=uaName.toLowerCase()}return[prefix,uaName,version].filter(item=>item&&item.length>0).reduce((acc,item,index)=>{switch(index){case 0:return item;case 1:return`${acc}/${item}`;default:return`${acc}#${item}`}},"")};const getUserAgentMiddlewareOptions={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:true};const getUserAgentPlugin=config=>({applyToStack:clientStack=>{clientStack.add(userAgentMiddleware(config),getUserAgentMiddlewareOptions)}});var SelectorType;(function(SelectorType){SelectorType["ENV"]="env";SelectorType["CONFIG"]="shared config entry"})(SelectorType||(SelectorType={}));const DEFAULT_USE_DUALSTACK_ENDPOINT=false;const DEFAULT_USE_FIPS_ENDPOINT=false;const isFipsRegion=region=>typeof region==="string"&&(region.startsWith("fips-")||region.endsWith("-fips"));const getRealRegion=region=>isFipsRegion(region)?["fips-aws-global","aws-fips"].includes(region)?"us-east-1":region.replace(/fips-(dkr-|prod-)?|-fips/,""):region;const resolveRegionConfig=input=>{const{region,useFipsEndpoint}=input;if(!region){throw new Error("Region is missing")}return{...input,region:async()=>{if(typeof region==="string"){return getRealRegion(region)}const providedRegion=await region();return getRealRegion(providedRegion)},useFipsEndpoint:async()=>{const providedRegion=typeof region==="string"?region:await region();if(isFipsRegion(providedRegion)){return true}return typeof useFipsEndpoint!=="function"?Promise.resolve(!!useFipsEndpoint):useFipsEndpoint()}}};const CONTENT_LENGTH_HEADER="content-length";function contentLengthMiddleware(bodyLengthChecker){return next=>async args=>{const request=args.request;if(HttpRequest.isInstance(request)){const{body,headers}=request;if(body&&Object.keys(headers).map(str=>str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER)===-1){try{const length=bodyLengthChecker(body);request.headers={...request.headers,[CONTENT_LENGTH_HEADER]:String(length)}}catch(error){}}}return next({...args,request})}}const contentLengthMiddlewareOptions={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:true};const getContentLengthPlugin=options=>({applyToStack:clientStack=>{clientStack.add(contentLengthMiddleware(options.bodyLengthChecker),contentLengthMiddlewareOptions)}});const resolveParamsForS3=async endpointParams=>{const bucket=endpointParams?.Bucket||"";if(typeof endpointParams.Bucket==="string"){endpointParams.Bucket=bucket.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))}if(isArnBucketName(bucket)){if(endpointParams.ForcePathStyle===true){throw new Error("Path-style addressing cannot be used with ARN buckets")}}else if(!isDnsCompatibleBucketName(bucket)||bucket.indexOf(".")!==-1&&!String(endpointParams.Endpoint).startsWith("http:")||bucket.toLowerCase()!==bucket||bucket.length<3){endpointParams.ForcePathStyle=true}if(endpointParams.DisableMultiRegionAccessPoints){endpointParams.disableMultiRegionAccessPoints=true;endpointParams.DisableMRAP=true}return endpointParams};const DOMAIN_PATTERN=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;const IP_ADDRESS_PATTERN=/(\d+\.){3}\d+/;const DOTS_PATTERN=/\.\./;const isDnsCompatibleBucketName=bucketName=>DOMAIN_PATTERN.test(bucketName)&&!IP_ADDRESS_PATTERN.test(bucketName)&&!DOTS_PATTERN.test(bucketName);const isArnBucketName=bucketName=>{const[arn,partition,service,,,bucket]=bucketName.split(":");const isArn=arn==="arn"&&bucketName.split(":").length>=6;const isValidArn=Boolean(isArn&&partition&&service&&bucket);if(isArn&&!isValidArn){throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`)}return isValidArn};const createConfigValueProvider=(configKey,canonicalEndpointParamKey,config)=>{const configProvider=async()=>{const configValue=config[configKey]??config[canonicalEndpointParamKey];if(typeof configValue==="function"){return configValue()}return configValue};if(configKey==="credentialScope"||canonicalEndpointParamKey==="CredentialScope"){return async()=>{const credentials=typeof config.credentials==="function"?await config.credentials():config.credentials;const configValue=credentials?.credentialScope??credentials?.CredentialScope;return configValue}}if(configKey==="accountId"||canonicalEndpointParamKey==="AccountId"){return async()=>{const credentials=typeof config.credentials==="function"?await config.credentials():config.credentials;const configValue=credentials?.accountId??credentials?.AccountId;return configValue}}if(configKey==="endpoint"||canonicalEndpointParamKey==="endpoint"){return async()=>{const endpoint=await configProvider();if(endpoint&&typeof endpoint==="object"){if("url"in endpoint){return endpoint.url.href}if("hostname"in endpoint){const{protocol,hostname,port,path}=endpoint;return`${protocol}//${hostname}${port?":"+port:""}${path}`}}return endpoint}}return configProvider};const getEndpointFromConfig=async serviceId=>undefined;function parseQueryString(querystring){const query={};querystring=querystring.replace(/^\?/,"");if(querystring){for(const pair of querystring.split("&")){let[key,value=null]=pair.split("=");key=decodeURIComponent(key);if(value){value=decodeURIComponent(value)}if(!(key in query)){query[key]=value}else if(Array.isArray(query[key])){query[key].push(value)}else{query[key]=[query[key],value]}}}return query}const parseUrl=url=>{if(typeof url==="string"){return parseUrl(new URL(url))}const{hostname,pathname,port,protocol,search}=url;let query;if(search){query=parseQueryString(search)}return{hostname,port:port?parseInt(port):undefined,protocol,path:pathname,query}};const toEndpointV1=endpoint=>{if(typeof endpoint==="object"){if("url"in endpoint){return parseUrl(endpoint.url)}return endpoint}return parseUrl(endpoint)};const getEndpointFromInstructions=async(commandInput,instructionsSupplier,clientConfig,context)=>{if(!clientConfig.endpoint){let endpointFromConfig;if(clientConfig.serviceConfiguredEndpoint){endpointFromConfig=await clientConfig.serviceConfiguredEndpoint()}else{endpointFromConfig=await getEndpointFromConfig(clientConfig.serviceId)}if(endpointFromConfig){clientConfig.endpoint=()=>Promise.resolve(toEndpointV1(endpointFromConfig))}}const endpointParams=await resolveParams(commandInput,instructionsSupplier,clientConfig);if(typeof clientConfig.endpointProvider!=="function"){throw new Error("config.endpointProvider is not set.")}const endpoint=clientConfig.endpointProvider(endpointParams,context);return endpoint};const resolveParams=async(commandInput,instructionsSupplier,clientConfig)=>{const endpointParams={};const instructions=instructionsSupplier?.getEndpointParameterInstructions?.()||{};for(const[name,instruction]of Object.entries(instructions)){switch(instruction.type){case"staticContextParams":endpointParams[name]=instruction.value;break;case"contextParams":endpointParams[name]=commandInput[instruction.name];break;case"clientContextParams":case"builtInParams":endpointParams[name]=await createConfigValueProvider(instruction.name,name,clientConfig)();break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(instruction))}}if(Object.keys(instructions).length===0){Object.assign(endpointParams,clientConfig)}if(String(clientConfig.serviceId).toLowerCase()==="s3"){await resolveParamsForS3(endpointParams)}return endpointParams};const endpointMiddleware=_ref39=>{let{config,instructions}=_ref39;return(next,context)=>async args=>{if(config.endpoint){setFeature$1(context,"ENDPOINT_OVERRIDE","N")}const endpoint=await getEndpointFromInstructions(args.input,{getEndpointParameterInstructions(){return instructions}},{...config},context);context.endpointV2=endpoint;context.authSchemes=endpoint.properties?.authSchemes;const authScheme=context.authSchemes?.[0];if(authScheme){context["signing_region"]=authScheme.signingRegion;context["signing_service"]=authScheme.signingName;const smithyContext=getSmithyContext(context);const httpAuthOption=smithyContext?.selectedHttpAuthScheme?.httpAuthOption;if(httpAuthOption){httpAuthOption.signingProperties=Object.assign(httpAuthOption.signingProperties||{},{signing_region:authScheme.signingRegion,signingRegion:authScheme.signingRegion,signing_service:authScheme.signingName,signingName:authScheme.signingName,signingRegionSet:authScheme.signingRegionSet},authScheme.properties)}}return next({...args})}};const endpointMiddlewareOptions={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:true,relation:"before",toMiddleware:serializerMiddlewareOption.name};const getEndpointPlugin=(config,instructions)=>({applyToStack:clientStack=>{clientStack.addRelativeTo(endpointMiddleware({config,instructions}),endpointMiddlewareOptions)}});const resolveEndpointConfig=input=>{const tls=input.tls??true;const{endpoint}=input;const customEndpointProvider=endpoint!=null?async()=>toEndpointV1(await normalizeProvider$1(endpoint)()):undefined;const isCustomEndpoint=!!endpoint;const resolvedConfig={...input,endpoint:customEndpointProvider,tls,isCustomEndpoint,useDualstackEndpoint:normalizeProvider$1(input.useDualstackEndpoint??false),useFipsEndpoint:normalizeProvider$1(input.useFipsEndpoint??false)};let configuredEndpointPromise=undefined;resolvedConfig.serviceConfiguredEndpoint=async()=>{if(input.serviceId&&!configuredEndpointPromise){configuredEndpointPromise=getEndpointFromConfig(input.serviceId)}return configuredEndpointPromise};return resolvedConfig};var RETRY_MODES;(function(RETRY_MODES){RETRY_MODES["STANDARD"]="standard";RETRY_MODES["ADAPTIVE"]="adaptive"})(RETRY_MODES||(RETRY_MODES={}));const DEFAULT_MAX_ATTEMPTS=3;const DEFAULT_RETRY_MODE=RETRY_MODES.STANDARD;const THROTTLING_ERROR_CODES=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"];const TRANSIENT_ERROR_CODES=["TimeoutError","RequestTimeout","RequestTimeoutException"];const TRANSIENT_ERROR_STATUS_CODES=[500,502,503,504];const NODEJS_TIMEOUT_ERROR_CODES=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"];const isClockSkewCorrectedError=error=>error.$metadata?.clockSkewCorrected;const isThrottlingError=error=>error.$metadata?.httpStatusCode===429||THROTTLING_ERROR_CODES.includes(error.name)||error.$retryable?.throttling==true;const isTransientError=error=>isClockSkewCorrectedError(error)||TRANSIENT_ERROR_CODES.includes(error.name)||NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code||"")||TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode||0);const isServerError=error=>{if(error.$metadata?.httpStatusCode!==undefined){const statusCode=error.$metadata.httpStatusCode;if(500<=statusCode&&statusCode<=599&&!isTransientError(error)){return true}return false}return false};class DefaultRateLimiter{constructor(options){this.currentCapacity=0;this.enabled=false;this.lastMaxRate=0;this.measuredTxRate=0;this.requestCount=0;this.lastTimestamp=0;this.timeWindow=0;this.beta=options?.beta??0.7;this.minCapacity=options?.minCapacity??1;this.minFillRate=options?.minFillRate??0.5;this.scaleConstant=options?.scaleConstant??0.4;this.smooth=options?.smooth??0.8;const currentTimeInSeconds=this.getCurrentTimeInSeconds();this.lastThrottleTime=currentTimeInSeconds;this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds());this.fillRate=this.minFillRate;this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1000}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(amount){if(!this.enabled){return}this.refillTokenBucket();if(amount>this.currentCapacity){const delay=(amount-this.currentCapacity)/this.fillRate*1000;await new Promise(resolve=>setTimeout(resolve,delay))}this.currentCapacity=this.currentCapacity-amount}refillTokenBucket(){const timestamp=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=timestamp;return}const fillAmount=(timestamp-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+fillAmount);this.lastTimestamp=timestamp}updateClientSendingRate(response){let calculatedRate;this.updateMeasuredRate();if(isThrottlingError(response)){const rateToUse=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=rateToUse;this.calculateTimeWindow();this.lastThrottleTime=this.getCurrentTimeInSeconds();calculatedRate=this.cubicThrottle(rateToUse);this.enableTokenBucket()}else{this.calculateTimeWindow();calculatedRate=this.cubicSuccess(this.getCurrentTimeInSeconds())}const newRate=Math.min(calculatedRate,2*this.measuredTxRate);this.updateTokenBucketRate(newRate)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(rateToUse){return this.getPrecise(rateToUse*this.beta)}cubicSuccess(timestamp){return this.getPrecise(this.scaleConstant*Math.pow(timestamp-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=true}updateTokenBucketRate(newRate){this.refillTokenBucket();this.fillRate=Math.max(newRate,this.minFillRate);this.maxCapacity=Math.max(newRate,this.minCapacity);this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){const t=this.getCurrentTimeInSeconds();const timeBucket=Math.floor(t*2)/2;this.requestCount++;if(timeBucket>this.lastTxRateBucket){const currentRate=this.requestCount/(timeBucket-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(currentRate*this.smooth+this.measuredTxRate*(1-this.smooth));this.requestCount=0;this.lastTxRateBucket=timeBucket}}getPrecise(num){return parseFloat(num.toFixed(8))}}const DEFAULT_RETRY_DELAY_BASE=100;const MAXIMUM_RETRY_DELAY=20*1000;const THROTTLING_RETRY_DELAY_BASE=500;const INITIAL_RETRY_TOKENS=500;const RETRY_COST=5;const TIMEOUT_RETRY_COST=10;const NO_RETRY_INCREMENT=1;const INVOCATION_ID_HEADER="amz-sdk-invocation-id";const REQUEST_HEADER="amz-sdk-request";const getDefaultRetryBackoffStrategy=()=>{let delayBase=DEFAULT_RETRY_DELAY_BASE;const computeNextBackoffDelay=attempts=>{return Math.floor(Math.min(MAXIMUM_RETRY_DELAY,Math.random()*2**attempts*delayBase))};const setDelayBase=delay=>{delayBase=delay};return{computeNextBackoffDelay,setDelayBase}};const createDefaultRetryToken=_ref40=>{let{retryDelay,retryCount,retryCost}=_ref40;const getRetryCount=()=>retryCount;const getRetryDelay=()=>Math.min(MAXIMUM_RETRY_DELAY,retryDelay);const getRetryCost=()=>retryCost;return{getRetryCount,getRetryDelay,getRetryCost}};class StandardRetryStrategy{constructor(maxAttempts){this.maxAttempts=maxAttempts;this.mode=RETRY_MODES.STANDARD;this.capacity=INITIAL_RETRY_TOKENS;this.retryBackoffStrategy=getDefaultRetryBackoffStrategy();this.maxAttemptsProvider=typeof maxAttempts==="function"?maxAttempts:async()=>maxAttempts}async acquireInitialRetryToken(retryTokenScope){return createDefaultRetryToken({retryDelay:DEFAULT_RETRY_DELAY_BASE,retryCount:0})}async refreshRetryTokenForRetry(token,errorInfo){const maxAttempts=await this.getMaxAttempts();if(this.shouldRetry(token,errorInfo,maxAttempts)){const errorType=errorInfo.errorType;this.retryBackoffStrategy.setDelayBase(errorType==="THROTTLING"?THROTTLING_RETRY_DELAY_BASE:DEFAULT_RETRY_DELAY_BASE);const delayFromErrorType=this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());const retryDelay=errorInfo.retryAfterHint?Math.max(errorInfo.retryAfterHint.getTime()-Date.now()||0,delayFromErrorType):delayFromErrorType;const capacityCost=this.getCapacityCost(errorType);this.capacity-=capacityCost;return createDefaultRetryToken({retryDelay,retryCount:token.getRetryCount()+1,retryCost:capacityCost})}throw new Error("No retry token available")}recordSuccess(token){this.capacity=Math.max(INITIAL_RETRY_TOKENS,this.capacity+(token.getRetryCost()??NO_RETRY_INCREMENT))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(error){console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);return DEFAULT_MAX_ATTEMPTS}}shouldRetry(tokenToRenew,errorInfo,maxAttempts){const attempts=tokenToRenew.getRetryCount()+1;return attempts<maxAttempts&&this.capacity>=this.getCapacityCost(errorInfo.errorType)&&this.isRetryableError(errorInfo.errorType)}getCapacityCost(errorType){return errorType==="TRANSIENT"?TIMEOUT_RETRY_COST:RETRY_COST}isRetryableError(errorType){return errorType==="THROTTLING"||errorType==="TRANSIENT"}}class AdaptiveRetryStrategy{constructor(maxAttemptsProvider,options){this.maxAttemptsProvider=maxAttemptsProvider;this.mode=RETRY_MODES.ADAPTIVE;const{rateLimiter}=options??{};this.rateLimiter=rateLimiter??new DefaultRateLimiter;this.standardRetryStrategy=new StandardRetryStrategy(maxAttemptsProvider)}async acquireInitialRetryToken(retryTokenScope){await this.rateLimiter.getSendToken();return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope)}async refreshRetryTokenForRetry(tokenToRenew,errorInfo){this.rateLimiter.updateClientSendingRate(errorInfo);return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew,errorInfo)}recordSuccess(token){this.rateLimiter.updateClientSendingRate({});this.standardRetryStrategy.recordSuccess(token)}}// Unique ID creation requires a high quality random # generator. In the browser we therefore
239
+ ${toHex(hashedRequest)}`}getCanonicalPath(_ref33){let{path}=_ref33;if(this.uriEscapePath){const normalizedPathSegments=[];for(const pathSegment of path.split("/")){if(pathSegment?.length===0)continue;if(pathSegment===".")continue;if(pathSegment===".."){normalizedPathSegments.pop()}else{normalizedPathSegments.push(pathSegment)}}const normalizedPath=`${path?.startsWith("/")?"/":""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length>0&&path?.endsWith("/")?"/":""}`;const doubleEncoded=escapeUri$1(normalizedPath);return doubleEncoded.replace(/%2F/g,"/")}return path}validateResolvedCredentials(credentials){if(typeof credentials!=="object"||typeof credentials.accessKeyId!=="string"||typeof credentials.secretAccessKey!=="string"){throw new Error("Resolved credential object is not valid")}}formatDate(now){const longDate=iso8601(now).replace(/[\-:]/g,"");return{longDate,shortDate:longDate.slice(0,8)}}getCanonicalHeaderList(headers){return Object.keys(headers).sort().join(";")}}class SignatureV4 extends SignatureV4Base{constructor(_ref34){let{applyChecksum,credentials,region,service,sha256,uriEscapePath=true}=_ref34;super({applyChecksum,credentials,region,service,sha256,uriEscapePath});this.headerFormatter=new HeaderFormatter}async presign(originalRequest){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const{signingDate=new Date,expiresIn=3600,unsignableHeaders,unhoistableHeaders,signableHeaders,hoistableHeaders,signingRegion,signingService}=options;const credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=signingRegion??(await this.regionProvider());const{longDate,shortDate}=this.formatDate(signingDate);if(expiresIn>MAX_PRESIGNED_TTL){return Promise.reject("Signature version 4 presigned URLs"+" must have an expiration date less than one week in"+" the future")}const scope=createScope(shortDate,region,signingService??this.service);const request=moveHeadersToQuery(prepareRequest(originalRequest),{unhoistableHeaders,hoistableHeaders});if(credentials.sessionToken){request.query[TOKEN_QUERY_PARAM]=credentials.sessionToken}request.query[ALGORITHM_QUERY_PARAM]=ALGORITHM_IDENTIFIER;request.query[CREDENTIAL_QUERY_PARAM]=`${credentials.accessKeyId}/${scope}`;request.query[AMZ_DATE_QUERY_PARAM]=longDate;request.query[EXPIRES_QUERY_PARAM]=expiresIn.toString(10);const canonicalHeaders=getCanonicalHeaders(request,unsignableHeaders,signableHeaders);request.query[SIGNED_HEADERS_QUERY_PARAM]=this.getCanonicalHeaderList(canonicalHeaders);request.query[SIGNATURE_QUERY_PARAM]=await this.getSignature(longDate,scope,this.getSigningKey(credentials,region,shortDate,signingService),this.createCanonicalRequest(request,canonicalHeaders,await getPayloadHash(originalRequest,this.sha256)));return request}async sign(toSign,options){if(typeof toSign==="string"){return this.signString(toSign,options)}else if(toSign.headers&&toSign.payload){return this.signEvent(toSign,options)}else if(toSign.message){return this.signMessage(toSign,options)}else{return this.signRequest(toSign,options)}}async signEvent(_ref35,_ref36){let{headers,payload}=_ref35;let{signingDate=new Date,priorSignature,signingRegion,signingService}=_ref36;const region=signingRegion??(await this.regionProvider());const{shortDate,longDate}=this.formatDate(signingDate);const scope=createScope(shortDate,region,signingService??this.service);const hashedPayload=await getPayloadHash({headers:{},body:payload},this.sha256);const hash=new this.sha256;hash.update(headers);const hashedHeaders=toHex(await hash.digest());const stringToSign=[EVENT_ALGORITHM_IDENTIFIER,longDate,scope,priorSignature,hashedHeaders,hashedPayload].join("\n");return this.signString(stringToSign,{signingDate,signingRegion:region,signingService})}async signMessage(signableMessage,_ref37){let{signingDate=new Date,signingRegion,signingService}=_ref37;const promise=this.signEvent({headers:this.headerFormatter.format(signableMessage.message.headers),payload:signableMessage.message.body},{signingDate,signingRegion,signingService,priorSignature:signableMessage.priorSignature});return promise.then(signature=>{return{message:signableMessage.message,signature}})}async signString(stringToSign){let{signingDate=new Date,signingRegion,signingService}=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=signingRegion??(await this.regionProvider());const{shortDate}=this.formatDate(signingDate);const hash=new this.sha256(await this.getSigningKey(credentials,region,shortDate,signingService));hash.update(toUint8Array(stringToSign));return toHex(await hash.digest())}async signRequest(requestToSign){let{signingDate=new Date,signableHeaders,unsignableHeaders,signingRegion,signingService}=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=signingRegion??(await this.regionProvider());const request=prepareRequest(requestToSign);const{longDate,shortDate}=this.formatDate(signingDate);const scope=createScope(shortDate,region,signingService??this.service);request.headers[AMZ_DATE_HEADER]=longDate;if(credentials.sessionToken){request.headers[TOKEN_HEADER]=credentials.sessionToken}const payloadHash=await getPayloadHash(request,this.sha256);if(!hasHeader(SHA256_HEADER,request.headers)&&this.applyChecksum){request.headers[SHA256_HEADER]=payloadHash}const canonicalHeaders=getCanonicalHeaders(request,unsignableHeaders,signableHeaders);const signature=await this.getSignature(longDate,scope,this.getSigningKey(credentials,region,shortDate,signingService),this.createCanonicalRequest(request,canonicalHeaders,payloadHash));request.headers[AUTH_HEADER]=`${ALGORITHM_IDENTIFIER} `+`Credential=${credentials.accessKeyId}/${scope}, `+`SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, `+`Signature=${signature}`;return request}async getSignature(longDate,credentialScope,keyPromise,canonicalRequest){const stringToSign=await this.createStringToSign(longDate,credentialScope,canonicalRequest,ALGORITHM_IDENTIFIER);const hash=new this.sha256(await keyPromise);hash.update(toUint8Array(stringToSign));return toHex(await hash.digest())}getSigningKey(credentials,region,shortDate,service){return getSigningKey(this.sha256,credentials,shortDate,region,service||this.service)}}const resolveAwsSdkSigV4Config=config=>{let inputCredentials=config.credentials;let isUserSupplied=!!config.credentials;let resolvedCredentials=undefined;Object.defineProperty(config,"credentials",{set(credentials){if(credentials&&credentials!==inputCredentials&&credentials!==resolvedCredentials){isUserSupplied=true}inputCredentials=credentials;const memoizedProvider=normalizeCredentialProvider(config,{credentials:inputCredentials,credentialDefaultProvider:config.credentialDefaultProvider});const boundProvider=bindCallerConfig(config,memoizedProvider);if(isUserSupplied&&!boundProvider.attributed){resolvedCredentials=async options=>boundProvider(options).then(creds=>setCredentialFeature(creds,"CREDENTIALS_CODE","e"));resolvedCredentials.memoized=boundProvider.memoized;resolvedCredentials.configBound=boundProvider.configBound;resolvedCredentials.attributed=true}else{resolvedCredentials=boundProvider}},get(){return resolvedCredentials},enumerable:true,configurable:true});config.credentials=inputCredentials;const{signingEscapePath=true,systemClockOffset=config.systemClockOffset||0,sha256}=config;let signer;if(config.signer){signer=normalizeProvider(config.signer)}else if(config.regionInfoProvider){signer=()=>normalizeProvider(config.region)().then(async region=>[(await config.regionInfoProvider(region,{useFipsEndpoint:await config.useFipsEndpoint(),useDualstackEndpoint:await config.useDualstackEndpoint()}))||{},region]).then(_ref38=>{let[regionInfo,region]=_ref38;const{signingRegion,signingService}=regionInfo;config.signingRegion=config.signingRegion||signingRegion||region;config.signingName=config.signingName||signingService||config.serviceId;const params={...config,credentials:config.credentials,region:config.signingRegion,service:config.signingName,sha256,uriEscapePath:signingEscapePath};const SignerCtor=config.signerConstructor||SignatureV4;return new SignerCtor(params)})}else{signer=async authScheme=>{authScheme=Object.assign({},{name:"sigv4",signingName:config.signingName||config.defaultSigningName,signingRegion:await normalizeProvider(config.region)(),properties:{}},authScheme);const signingRegion=authScheme.signingRegion;const signingService=authScheme.signingName;config.signingRegion=config.signingRegion||signingRegion;config.signingName=config.signingName||signingService||config.serviceId;const params={...config,credentials:config.credentials,region:config.signingRegion,service:config.signingName,sha256,uriEscapePath:signingEscapePath};const SignerCtor=config.signerConstructor||SignatureV4;return new SignerCtor(params)}}const resolvedConfig=Object.assign(config,{systemClockOffset,signingEscapePath,signer});return resolvedConfig};function normalizeCredentialProvider(config,_ref39){let{credentials,credentialDefaultProvider}=_ref39;let credentialsProvider;if(credentials){if(!credentials?.memoized){credentialsProvider=memoizeIdentityProvider(credentials,isIdentityExpired,doesIdentityRequireRefresh)}else{credentialsProvider=credentials}}else{if(credentialDefaultProvider){credentialsProvider=normalizeProvider(credentialDefaultProvider(Object.assign({},config,{parentClientConfig:config})))}else{credentialsProvider=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")}}}credentialsProvider.memoized=true;return credentialsProvider}function bindCallerConfig(config,credentialsProvider){if(credentialsProvider.configBound){return credentialsProvider}const fn=async options=>credentialsProvider({...options,callerClientConfig:config});fn.memoized=credentialsProvider.memoized;fn.configBound=true;return fn}const collectBodyString=(streamBody,context)=>collectBody(streamBody,context).then(body=>context.utf8Encoder(body));const parseJsonBody=(streamBody,context)=>collectBodyString(streamBody,context).then(encoded=>{if(encoded.length){try{return JSON.parse(encoded)}catch(e){if(e?.name==="SyntaxError"){Object.defineProperty(e,"$responseBodyText",{value:encoded})}throw e}}return{}});const parseJsonErrorBody=async(errorBody,context)=>{const value=await parseJsonBody(errorBody,context);value.message=value.message??value.Message;return value};const loadRestJsonErrorCode=(output,data)=>{const findKey=(object,key)=>Object.keys(object).find(k=>k.toLowerCase()===key.toLowerCase());const sanitizeErrorCode=rawValue=>{let cleanValue=rawValue;if(typeof cleanValue==="number"){cleanValue=cleanValue.toString()}if(cleanValue.indexOf(",")>=0){cleanValue=cleanValue.split(",")[0]}if(cleanValue.indexOf(":")>=0){cleanValue=cleanValue.split(":")[0]}if(cleanValue.indexOf("#")>=0){cleanValue=cleanValue.split("#")[1]}return cleanValue};const headerKey=findKey(output.headers,"x-amzn-errortype");if(headerKey!==undefined){return sanitizeErrorCode(output.headers[headerKey])}if(data.code!==undefined){return sanitizeErrorCode(data.code)}if(data["__type"]!==undefined){return sanitizeErrorCode(data["__type"])}};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}const ACCOUNT_ID_ENDPOINT_REGEX=/\d{12}\.ddb/;async function checkFeatures(context,config,args){const request=args.request;if(request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"){setFeature(context,"PROTOCOL_RPC_V2_CBOR","M")}if(typeof config.retryStrategy==="function"){const retryStrategy=await config.retryStrategy();if(typeof retryStrategy.acquireInitialRetryToken==="function"){if(retryStrategy.constructor?.name?.includes("Adaptive")){setFeature(context,"RETRY_MODE_ADAPTIVE","F")}else{setFeature(context,"RETRY_MODE_STANDARD","E")}}else{setFeature(context,"RETRY_MODE_LEGACY","D")}}if(typeof config.accountIdEndpointMode==="function"){const endpointV2=context.endpointV2;if(String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)){setFeature(context,"ACCOUNT_ID_ENDPOINT","O")}switch(await config.accountIdEndpointMode?.()){case"disabled":setFeature(context,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":setFeature(context,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":setFeature(context,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const identity=context.__smithy_context?.selectedHttpAuthScheme?.identity;if(identity?.$source){const credentials=identity;if(credentials.accountId){setFeature(context,"RESOLVED_ACCOUNT_ID","T")}for(const[key,value]of Object.entries(credentials.$source??{})){setFeature(context,key,value)}}}const USER_AGENT="user-agent";const X_AMZ_USER_AGENT="x-amz-user-agent";const SPACE=" ";const UA_NAME_SEPARATOR="/";const UA_NAME_ESCAPE_REGEX=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;const UA_VALUE_ESCAPE_REGEX=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;const UA_ESCAPE_CHAR="-";const BYTE_LIMIT=1024;function encodeFeatures(features){let buffer="";for(const key in features){const val=features[key];if(buffer.length+val.length+1<=BYTE_LIMIT){if(buffer.length){buffer+=","+val}else{buffer+=val}continue}break}return buffer}const userAgentMiddleware=options=>(next,context)=>async args=>{const{request}=args;if(!HttpRequest.isInstance(request)){return next(args)}const{headers}=request;const userAgent=context?.userAgent?.map(escapeUserAgent)||[];const defaultUserAgent=(await options.defaultUserAgentProvider()).map(escapeUserAgent);await checkFeatures(context,options,args);const awsContext=context;defaultUserAgent.push(`m/${encodeFeatures(Object.assign({},context.__smithy_context?.features,awsContext.__aws_sdk_context?.features))}`);const customUserAgent=options?.customUserAgent?.map(escapeUserAgent)||[];const appId=await options.userAgentAppId();if(appId){defaultUserAgent.push(escapeUserAgent([`app/${appId}`]))}const sdkUserAgentValue=[].concat([...defaultUserAgent,...userAgent,...customUserAgent]).join(SPACE);const normalUAValue=[...defaultUserAgent.filter(section=>section.startsWith("aws-sdk-")),...customUserAgent].join(SPACE);if(options.runtime!=="browser"){if(normalUAValue){headers[X_AMZ_USER_AGENT]=headers[X_AMZ_USER_AGENT]?`${headers[USER_AGENT]} ${normalUAValue}`:normalUAValue}headers[USER_AGENT]=sdkUserAgentValue}else{headers[X_AMZ_USER_AGENT]=sdkUserAgentValue}return next({...args,request})};const escapeUserAgent=userAgentPair=>{const name=userAgentPair[0].split(UA_NAME_SEPARATOR).map(part=>part.replace(UA_NAME_ESCAPE_REGEX,UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR);const version=userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX,UA_ESCAPE_CHAR);const prefixSeparatorIndex=name.indexOf(UA_NAME_SEPARATOR);const prefix=name.substring(0,prefixSeparatorIndex);let uaName=name.substring(prefixSeparatorIndex+1);if(prefix==="api"){uaName=uaName.toLowerCase()}return[prefix,uaName,version].filter(item=>item&&item.length>0).reduce((acc,item,index)=>{switch(index){case 0:return item;case 1:return`${acc}/${item}`;default:return`${acc}#${item}`}},"")};const getUserAgentMiddlewareOptions={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:true};const getUserAgentPlugin=config=>({applyToStack:clientStack=>{clientStack.add(userAgentMiddleware(config),getUserAgentMiddlewareOptions)}});var SelectorType;(function(SelectorType){SelectorType["ENV"]="env";SelectorType["CONFIG"]="shared config entry"})(SelectorType||(SelectorType={}));const DEFAULT_USE_DUALSTACK_ENDPOINT=false;const DEFAULT_USE_FIPS_ENDPOINT=false;const isFipsRegion=region=>typeof region==="string"&&(region.startsWith("fips-")||region.endsWith("-fips"));const getRealRegion=region=>isFipsRegion(region)?["fips-aws-global","aws-fips"].includes(region)?"us-east-1":region.replace(/fips-(dkr-|prod-)?|-fips/,""):region;const resolveRegionConfig=input=>{const{region,useFipsEndpoint}=input;if(!region){throw new Error("Region is missing")}return Object.assign(input,{region:async()=>{if(typeof region==="string"){return getRealRegion(region)}const providedRegion=await region();return getRealRegion(providedRegion)},useFipsEndpoint:async()=>{const providedRegion=typeof region==="string"?region:await region();if(isFipsRegion(providedRegion)){return true}return typeof useFipsEndpoint!=="function"?Promise.resolve(!!useFipsEndpoint):useFipsEndpoint()}})};const CONTENT_LENGTH_HEADER="content-length";function contentLengthMiddleware(bodyLengthChecker){return next=>async args=>{const request=args.request;if(HttpRequest.isInstance(request)){const{body,headers}=request;if(body&&Object.keys(headers).map(str=>str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER)===-1){try{const length=bodyLengthChecker(body);request.headers={...request.headers,[CONTENT_LENGTH_HEADER]:String(length)}}catch(error){}}}return next({...args,request})}}const contentLengthMiddlewareOptions={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:true};const getContentLengthPlugin=options=>({applyToStack:clientStack=>{clientStack.add(contentLengthMiddleware(options.bodyLengthChecker),contentLengthMiddlewareOptions)}});const resolveParamsForS3=async endpointParams=>{const bucket=endpointParams?.Bucket||"";if(typeof endpointParams.Bucket==="string"){endpointParams.Bucket=bucket.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))}if(isArnBucketName(bucket)){if(endpointParams.ForcePathStyle===true){throw new Error("Path-style addressing cannot be used with ARN buckets")}}else if(!isDnsCompatibleBucketName(bucket)||bucket.indexOf(".")!==-1&&!String(endpointParams.Endpoint).startsWith("http:")||bucket.toLowerCase()!==bucket||bucket.length<3){endpointParams.ForcePathStyle=true}if(endpointParams.DisableMultiRegionAccessPoints){endpointParams.disableMultiRegionAccessPoints=true;endpointParams.DisableMRAP=true}return endpointParams};const DOMAIN_PATTERN=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;const IP_ADDRESS_PATTERN=/(\d+\.){3}\d+/;const DOTS_PATTERN=/\.\./;const isDnsCompatibleBucketName=bucketName=>DOMAIN_PATTERN.test(bucketName)&&!IP_ADDRESS_PATTERN.test(bucketName)&&!DOTS_PATTERN.test(bucketName);const isArnBucketName=bucketName=>{const[arn,partition,service,,,bucket]=bucketName.split(":");const isArn=arn==="arn"&&bucketName.split(":").length>=6;const isValidArn=Boolean(isArn&&partition&&service&&bucket);if(isArn&&!isValidArn){throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`)}return isValidArn};const createConfigValueProvider=(configKey,canonicalEndpointParamKey,config)=>{const configProvider=async()=>{const configValue=config[configKey]??config[canonicalEndpointParamKey];if(typeof configValue==="function"){return configValue()}return configValue};if(configKey==="credentialScope"||canonicalEndpointParamKey==="CredentialScope"){return async()=>{const credentials=typeof config.credentials==="function"?await config.credentials():config.credentials;const configValue=credentials?.credentialScope??credentials?.CredentialScope;return configValue}}if(configKey==="accountId"||canonicalEndpointParamKey==="AccountId"){return async()=>{const credentials=typeof config.credentials==="function"?await config.credentials():config.credentials;const configValue=credentials?.accountId??credentials?.AccountId;return configValue}}if(configKey==="endpoint"||canonicalEndpointParamKey==="endpoint"){return async()=>{const endpoint=await configProvider();if(endpoint&&typeof endpoint==="object"){if("url"in endpoint){return endpoint.url.href}if("hostname"in endpoint){const{protocol,hostname,port,path}=endpoint;return`${protocol}//${hostname}${port?":"+port:""}${path}`}}return endpoint}}return configProvider};const getEndpointFromConfig=async serviceId=>undefined;function parseQueryString(querystring){const query={};querystring=querystring.replace(/^\?/,"");if(querystring){for(const pair of querystring.split("&")){let[key,value=null]=pair.split("=");key=decodeURIComponent(key);if(value){value=decodeURIComponent(value)}if(!(key in query)){query[key]=value}else if(Array.isArray(query[key])){query[key].push(value)}else{query[key]=[query[key],value]}}}return query}const parseUrl=url=>{if(typeof url==="string"){return parseUrl(new URL(url))}const{hostname,pathname,port,protocol,search}=url;let query;if(search){query=parseQueryString(search)}return{hostname,port:port?parseInt(port):undefined,protocol,path:pathname,query}};const toEndpointV1=endpoint=>{if(typeof endpoint==="object"){if("url"in endpoint){return parseUrl(endpoint.url)}return endpoint}return parseUrl(endpoint)};const getEndpointFromInstructions=async(commandInput,instructionsSupplier,clientConfig,context)=>{if(!clientConfig.endpoint){let endpointFromConfig;if(clientConfig.serviceConfiguredEndpoint){endpointFromConfig=await clientConfig.serviceConfiguredEndpoint()}else{endpointFromConfig=await getEndpointFromConfig(clientConfig.serviceId)}if(endpointFromConfig){clientConfig.endpoint=()=>Promise.resolve(toEndpointV1(endpointFromConfig))}}const endpointParams=await resolveParams(commandInput,instructionsSupplier,clientConfig);if(typeof clientConfig.endpointProvider!=="function"){throw new Error("config.endpointProvider is not set.")}const endpoint=clientConfig.endpointProvider(endpointParams,context);return endpoint};const resolveParams=async(commandInput,instructionsSupplier,clientConfig)=>{const endpointParams={};const instructions=instructionsSupplier?.getEndpointParameterInstructions?.()||{};for(const[name,instruction]of Object.entries(instructions)){switch(instruction.type){case"staticContextParams":endpointParams[name]=instruction.value;break;case"contextParams":endpointParams[name]=commandInput[instruction.name];break;case"clientContextParams":case"builtInParams":endpointParams[name]=await createConfigValueProvider(instruction.name,name,clientConfig)();break;case"operationContextParams":endpointParams[name]=instruction.get(commandInput);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(instruction))}}if(Object.keys(instructions).length===0){Object.assign(endpointParams,clientConfig)}if(String(clientConfig.serviceId).toLowerCase()==="s3"){await resolveParamsForS3(endpointParams)}return endpointParams};const endpointMiddleware=_ref40=>{let{config,instructions}=_ref40;return(next,context)=>async args=>{if(config.endpoint){setFeature$1(context,"ENDPOINT_OVERRIDE","N")}const endpoint=await getEndpointFromInstructions(args.input,{getEndpointParameterInstructions(){return instructions}},{...config},context);context.endpointV2=endpoint;context.authSchemes=endpoint.properties?.authSchemes;const authScheme=context.authSchemes?.[0];if(authScheme){context["signing_region"]=authScheme.signingRegion;context["signing_service"]=authScheme.signingName;const smithyContext=getSmithyContext(context);const httpAuthOption=smithyContext?.selectedHttpAuthScheme?.httpAuthOption;if(httpAuthOption){httpAuthOption.signingProperties=Object.assign(httpAuthOption.signingProperties||{},{signing_region:authScheme.signingRegion,signingRegion:authScheme.signingRegion,signing_service:authScheme.signingName,signingName:authScheme.signingName,signingRegionSet:authScheme.signingRegionSet},authScheme.properties)}}return next({...args})}};const endpointMiddlewareOptions={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:true,relation:"before",toMiddleware:serializerMiddlewareOption.name};const getEndpointPlugin=(config,instructions)=>({applyToStack:clientStack=>{clientStack.addRelativeTo(endpointMiddleware({config,instructions}),endpointMiddlewareOptions)}});const resolveEndpointConfig=input=>{const tls=input.tls??true;const{endpoint,useDualstackEndpoint,useFipsEndpoint}=input;const customEndpointProvider=endpoint!=null?async()=>toEndpointV1(await normalizeProvider$1(endpoint)()):undefined;const isCustomEndpoint=!!endpoint;const resolvedConfig=Object.assign(input,{endpoint:customEndpointProvider,tls,isCustomEndpoint,useDualstackEndpoint:normalizeProvider$1(useDualstackEndpoint??false),useFipsEndpoint:normalizeProvider$1(useFipsEndpoint??false)});let configuredEndpointPromise=undefined;resolvedConfig.serviceConfiguredEndpoint=async()=>{if(input.serviceId&&!configuredEndpointPromise){configuredEndpointPromise=getEndpointFromConfig(input.serviceId)}return configuredEndpointPromise};return resolvedConfig};var RETRY_MODES;(function(RETRY_MODES){RETRY_MODES["STANDARD"]="standard";RETRY_MODES["ADAPTIVE"]="adaptive"})(RETRY_MODES||(RETRY_MODES={}));const DEFAULT_MAX_ATTEMPTS=3;const DEFAULT_RETRY_MODE=RETRY_MODES.STANDARD;const THROTTLING_ERROR_CODES=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"];const TRANSIENT_ERROR_CODES=["TimeoutError","RequestTimeout","RequestTimeoutException"];const TRANSIENT_ERROR_STATUS_CODES=[500,502,503,504];const NODEJS_TIMEOUT_ERROR_CODES=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"];const isClockSkewCorrectedError=error=>error.$metadata?.clockSkewCorrected;const isBrowserNetworkError=error=>{const errorMessages=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);const isValid=error&&error instanceof TypeError;if(!isValid){return false}return errorMessages.has(error.message)};const isThrottlingError=error=>error.$metadata?.httpStatusCode===429||THROTTLING_ERROR_CODES.includes(error.name)||error.$retryable?.throttling==true;const isTransientError=function(error){let depth=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;return isClockSkewCorrectedError(error)||TRANSIENT_ERROR_CODES.includes(error.name)||NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code||"")||TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode||0)||isBrowserNetworkError(error)||error.cause!==undefined&&depth<=10&&isTransientError(error.cause,depth+1)};const isServerError=error=>{if(error.$metadata?.httpStatusCode!==undefined){const statusCode=error.$metadata.httpStatusCode;if(500<=statusCode&&statusCode<=599&&!isTransientError(error)){return true}return false}return false};class DefaultRateLimiter{constructor(options){this.currentCapacity=0;this.enabled=false;this.lastMaxRate=0;this.measuredTxRate=0;this.requestCount=0;this.lastTimestamp=0;this.timeWindow=0;this.beta=options?.beta??0.7;this.minCapacity=options?.minCapacity??1;this.minFillRate=options?.minFillRate??0.5;this.scaleConstant=options?.scaleConstant??0.4;this.smooth=options?.smooth??0.8;const currentTimeInSeconds=this.getCurrentTimeInSeconds();this.lastThrottleTime=currentTimeInSeconds;this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds());this.fillRate=this.minFillRate;this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1000}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(amount){if(!this.enabled){return}this.refillTokenBucket();if(amount>this.currentCapacity){const delay=(amount-this.currentCapacity)/this.fillRate*1000;await new Promise(resolve=>DefaultRateLimiter.setTimeoutFn(resolve,delay))}this.currentCapacity=this.currentCapacity-amount}refillTokenBucket(){const timestamp=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=timestamp;return}const fillAmount=(timestamp-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+fillAmount);this.lastTimestamp=timestamp}updateClientSendingRate(response){let calculatedRate;this.updateMeasuredRate();if(isThrottlingError(response)){const rateToUse=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=rateToUse;this.calculateTimeWindow();this.lastThrottleTime=this.getCurrentTimeInSeconds();calculatedRate=this.cubicThrottle(rateToUse);this.enableTokenBucket()}else{this.calculateTimeWindow();calculatedRate=this.cubicSuccess(this.getCurrentTimeInSeconds())}const newRate=Math.min(calculatedRate,2*this.measuredTxRate);this.updateTokenBucketRate(newRate)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(rateToUse){return this.getPrecise(rateToUse*this.beta)}cubicSuccess(timestamp){return this.getPrecise(this.scaleConstant*Math.pow(timestamp-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=true}updateTokenBucketRate(newRate){this.refillTokenBucket();this.fillRate=Math.max(newRate,this.minFillRate);this.maxCapacity=Math.max(newRate,this.minCapacity);this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){const t=this.getCurrentTimeInSeconds();const timeBucket=Math.floor(t*2)/2;this.requestCount++;if(timeBucket>this.lastTxRateBucket){const currentRate=this.requestCount/(timeBucket-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(currentRate*this.smooth+this.measuredTxRate*(1-this.smooth));this.requestCount=0;this.lastTxRateBucket=timeBucket}}getPrecise(num){return parseFloat(num.toFixed(8))}}DefaultRateLimiter.setTimeoutFn=setTimeout;const DEFAULT_RETRY_DELAY_BASE=100;const MAXIMUM_RETRY_DELAY=20*1000;const THROTTLING_RETRY_DELAY_BASE=500;const INITIAL_RETRY_TOKENS=500;const RETRY_COST=5;const TIMEOUT_RETRY_COST=10;const NO_RETRY_INCREMENT=1;const INVOCATION_ID_HEADER="amz-sdk-invocation-id";const REQUEST_HEADER="amz-sdk-request";const getDefaultRetryBackoffStrategy=()=>{let delayBase=DEFAULT_RETRY_DELAY_BASE;const computeNextBackoffDelay=attempts=>{return Math.floor(Math.min(MAXIMUM_RETRY_DELAY,Math.random()*2**attempts*delayBase))};const setDelayBase=delay=>{delayBase=delay};return{computeNextBackoffDelay,setDelayBase}};const createDefaultRetryToken=_ref41=>{let{retryDelay,retryCount,retryCost}=_ref41;const getRetryCount=()=>retryCount;const getRetryDelay=()=>Math.min(MAXIMUM_RETRY_DELAY,retryDelay);const getRetryCost=()=>retryCost;return{getRetryCount,getRetryDelay,getRetryCost}};class StandardRetryStrategy{constructor(maxAttempts){this.maxAttempts=maxAttempts;this.mode=RETRY_MODES.STANDARD;this.capacity=INITIAL_RETRY_TOKENS;this.retryBackoffStrategy=getDefaultRetryBackoffStrategy();this.maxAttemptsProvider=typeof maxAttempts==="function"?maxAttempts:async()=>maxAttempts}async acquireInitialRetryToken(retryTokenScope){return createDefaultRetryToken({retryDelay:DEFAULT_RETRY_DELAY_BASE,retryCount:0})}async refreshRetryTokenForRetry(token,errorInfo){const maxAttempts=await this.getMaxAttempts();if(this.shouldRetry(token,errorInfo,maxAttempts)){const errorType=errorInfo.errorType;this.retryBackoffStrategy.setDelayBase(errorType==="THROTTLING"?THROTTLING_RETRY_DELAY_BASE:DEFAULT_RETRY_DELAY_BASE);const delayFromErrorType=this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());const retryDelay=errorInfo.retryAfterHint?Math.max(errorInfo.retryAfterHint.getTime()-Date.now()||0,delayFromErrorType):delayFromErrorType;const capacityCost=this.getCapacityCost(errorType);this.capacity-=capacityCost;return createDefaultRetryToken({retryDelay,retryCount:token.getRetryCount()+1,retryCost:capacityCost})}throw new Error("No retry token available")}recordSuccess(token){this.capacity=Math.max(INITIAL_RETRY_TOKENS,this.capacity+(token.getRetryCost()??NO_RETRY_INCREMENT))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(error){console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);return DEFAULT_MAX_ATTEMPTS}}shouldRetry(tokenToRenew,errorInfo,maxAttempts){const attempts=tokenToRenew.getRetryCount()+1;return attempts<maxAttempts&&this.capacity>=this.getCapacityCost(errorInfo.errorType)&&this.isRetryableError(errorInfo.errorType)}getCapacityCost(errorType){return errorType==="TRANSIENT"?TIMEOUT_RETRY_COST:RETRY_COST}isRetryableError(errorType){return errorType==="THROTTLING"||errorType==="TRANSIENT"}}class AdaptiveRetryStrategy{constructor(maxAttemptsProvider,options){this.maxAttemptsProvider=maxAttemptsProvider;this.mode=RETRY_MODES.ADAPTIVE;const{rateLimiter}=options??{};this.rateLimiter=rateLimiter??new DefaultRateLimiter;this.standardRetryStrategy=new StandardRetryStrategy(maxAttemptsProvider)}async acquireInitialRetryToken(retryTokenScope){await this.rateLimiter.getSendToken();return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope)}async refreshRetryTokenForRetry(tokenToRenew,errorInfo){this.rateLimiter.updateClientSendingRate(errorInfo);return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew,errorInfo)}recordSuccess(token){this.rateLimiter.updateClientSendingRate({});this.standardRetryStrategy.recordSuccess(token)}}// Unique ID creation requires a high quality random # generator. In the browser we therefore
239
240
  // require the crypto API and do not support built-in fallback to lower quality random number
240
241
  // generators (like Math.random()).
241
242
  let getRandomValues;const rnds8=new Uint8Array(16);function rng(){// lazy load so that environments that need to polyfill have a chance to do so
@@ -245,6 +246,6 @@ getRandomValues=typeof crypto!=="undefined"&&crypto.getRandomValues&&crypto.getR
245
246
  * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
246
247
  */const byteToHex=[];for(let i=0;i<256;++i){byteToHex.push((i+256).toString(16).slice(1))}function unsafeStringify(arr){let offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;// Note: Be careful editing this code! It's been tuned for performance
247
248
  // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
248
- return byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]}const randomUUID=typeof crypto!=="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var native={randomUUID};function v4(options,buf,offset){if(native.randomUUID&&!buf&&!options){return native.randomUUID()}options=options||{};const rnds=options.random||(options.rng||rng)();// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
249
+ return byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]}const randomUUID=typeof crypto!=="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var native={randomUUID};function v4(options,buf,offset){if(native.randomUUID&&true&&!options){return native.randomUUID()}options=options||{};const rnds=options.random||(options.rng||rng)();// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
249
250
  rnds[6]=rnds[6]&15|64;rnds[8]=rnds[8]&63|128;// Copy bytes to buffer, if provided
250
- if(buf){offset=offset||0;for(let i=0;i<16;++i){buf[offset+i]=rnds[i]}return buf}return unsafeStringify(rnds)}const asSdkError=error=>{if(error instanceof Error)return error;if(error instanceof Object)return Object.assign(new Error,error);if(typeof error==="string")return new Error(error);return new Error(`AWS SDK error wrapper for ${error}`)};const resolveRetryConfig=input=>{const{retryStrategy}=input;const maxAttempts=normalizeProvider$1(input.maxAttempts??DEFAULT_MAX_ATTEMPTS);return{...input,maxAttempts,retryStrategy:async()=>{if(retryStrategy){return retryStrategy}const retryMode=await normalizeProvider$1(input.retryMode)();if(retryMode===RETRY_MODES.ADAPTIVE){return new AdaptiveRetryStrategy(maxAttempts)}return new StandardRetryStrategy(maxAttempts)}}};const isStreamingPayload=request=>request?.body instanceof ReadableStream;const retryMiddleware=options=>(next,context)=>async args=>{let retryStrategy=await options.retryStrategy();const maxAttempts=await options.maxAttempts();if(isRetryStrategyV2(retryStrategy)){retryStrategy=retryStrategy;let retryToken=await retryStrategy.acquireInitialRetryToken(context["partition_id"]);let lastError=new Error;let attempts=0;let totalRetryDelay=0;const{request}=args;const isRequest=HttpRequest.isInstance(request);if(isRequest){request.headers[INVOCATION_ID_HEADER]=v4()}while(true){try{if(isRequest){request.headers[REQUEST_HEADER]=`attempt=${attempts+1}; max=${maxAttempts}`}const{response,output}=await next(args);retryStrategy.recordSuccess(retryToken);output.$metadata.attempts=attempts+1;output.$metadata.totalRetryDelay=totalRetryDelay;return{response,output}}catch(e){const retryErrorInfo=getRetryErrorInfo(e);lastError=asSdkError(e);if(isRequest&&isStreamingPayload(request)){(context.logger instanceof NoOpLogger?console:context.logger)?.warn("An error was encountered in a non-retryable streaming request.");throw lastError}try{retryToken=await retryStrategy.refreshRetryTokenForRetry(retryToken,retryErrorInfo)}catch(refreshError){if(!lastError.$metadata){lastError.$metadata={}}lastError.$metadata.attempts=attempts+1;lastError.$metadata.totalRetryDelay=totalRetryDelay;throw lastError}attempts=retryToken.getRetryCount();const delay=retryToken.getRetryDelay();totalRetryDelay+=delay;await new Promise(resolve=>setTimeout(resolve,delay))}}}else{retryStrategy=retryStrategy;if(retryStrategy?.mode)context.userAgent=[...(context.userAgent||[]),["cfg/retry-mode",retryStrategy.mode]];return retryStrategy.retry(next,args)}};const isRetryStrategyV2=retryStrategy=>typeof retryStrategy.acquireInitialRetryToken!=="undefined"&&typeof retryStrategy.refreshRetryTokenForRetry!=="undefined"&&typeof retryStrategy.recordSuccess!=="undefined";const getRetryErrorInfo=error=>{const errorInfo={error,errorType:getRetryErrorType(error)};const retryAfterHint=getRetryAfterHint(error.$response);if(retryAfterHint){errorInfo.retryAfterHint=retryAfterHint}return errorInfo};const getRetryErrorType=error=>{if(isThrottlingError(error))return"THROTTLING";if(isTransientError(error))return"TRANSIENT";if(isServerError(error))return"SERVER_ERROR";return"CLIENT_ERROR"};const retryMiddlewareOptions={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:true};const getRetryPlugin=options=>({applyToStack:clientStack=>{clientStack.add(retryMiddleware(options),retryMiddlewareOptions)}});const getRetryAfterHint=response=>{if(!HttpResponse.isInstance(response))return;const retryAfterHeaderName=Object.keys(response.headers).find(key=>key.toLowerCase()==="retry-after");if(!retryAfterHeaderName)return;const retryAfter=response.headers[retryAfterHeaderName];const retryAfterSeconds=Number(retryAfter);if(!Number.isNaN(retryAfterSeconds))return new Date(retryAfterSeconds*1000);const retryAfterDate=new Date(retryAfter);return retryAfterDate};const defaultCognitoIdentityHttpAuthSchemeParametersProvider=async(config,context,input)=>{return{operation:getSmithyContext(context).operation,region:(await normalizeProvider$1(config.region)())||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function createAwsAuthSigv4HttpAuthOption(authParameters){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-identity",region:authParameters.region},propertiesExtractor:(config,context)=>({signingProperties:{config,context}})}}function createSmithyApiNoAuthHttpAuthOption(authParameters){return{schemeId:"smithy.api#noAuth"}}const defaultCognitoIdentityHttpAuthSchemeProvider=authParameters=>{const options=[];switch(authParameters.operation){case"GetCredentialsForIdentity":{options.push(createSmithyApiNoAuthHttpAuthOption());break}case"GetId":{options.push(createSmithyApiNoAuthHttpAuthOption());break}case"GetOpenIdToken":{options.push(createSmithyApiNoAuthHttpAuthOption());break}case"UnlinkIdentity":{options.push(createSmithyApiNoAuthHttpAuthOption());break}default:{options.push(createAwsAuthSigv4HttpAuthOption(authParameters))}}return options};const resolveHttpAuthSchemeConfig=config=>{const config_0=resolveAwsSdkSigV4Config(config);return{...config_0}};const resolveClientEndpointParameters=options=>{return{...options,useDualstackEndpoint:options.useDualstackEndpoint??false,useFipsEndpoint:options.useFipsEndpoint??false,defaultSigningName:"cognito-identity"}};const commonParams={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var name="@aws-sdk/client-cognito-identity";var description="AWS SDK for JavaScript Cognito Identity Client for Node.js, Browser and React Native";var version="3.682.0";var scripts={build:"concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'","build:cjs":"node ../../scripts/compilation/inline client-cognito-identity","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"rimraf ./dist-* && rimraf *.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo cognito-identity","test:e2e":"vitest run -c vitest.config.e2e.ts","test:e2e:watch":"vitest watch -c vitest.config.e2e.ts"};var main="./dist-cjs/index.js";var types="./dist-types/index.d.ts";var module="./dist-es/index.js";var sideEffects=false;var dependencies={"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/client-sso-oidc":"3.682.0","@aws-sdk/client-sts":"3.682.0","@aws-sdk/core":"3.679.0","@aws-sdk/credential-provider-node":"3.682.0","@aws-sdk/middleware-host-header":"3.679.0","@aws-sdk/middleware-logger":"3.679.0","@aws-sdk/middleware-recursion-detection":"3.679.0","@aws-sdk/middleware-user-agent":"3.682.0","@aws-sdk/region-config-resolver":"3.679.0","@aws-sdk/types":"3.679.0","@aws-sdk/util-endpoints":"3.679.0","@aws-sdk/util-user-agent-browser":"3.679.0","@aws-sdk/util-user-agent-node":"3.682.0","@smithy/config-resolver":"^3.0.9","@smithy/core":"^2.4.8","@smithy/fetch-http-handler":"^3.2.9","@smithy/hash-node":"^3.0.7","@smithy/invalid-dependency":"^3.0.7","@smithy/middleware-content-length":"^3.0.9","@smithy/middleware-endpoint":"^3.1.4","@smithy/middleware-retry":"^3.0.23","@smithy/middleware-serde":"^3.0.7","@smithy/middleware-stack":"^3.0.7","@smithy/node-config-provider":"^3.1.8","@smithy/node-http-handler":"^3.2.4","@smithy/protocol-http":"^4.1.4","@smithy/smithy-client":"^3.4.0","@smithy/types":"^3.5.0","@smithy/url-parser":"^3.0.7","@smithy/util-base64":"^3.0.0","@smithy/util-body-length-browser":"^3.0.0","@smithy/util-body-length-node":"^3.0.0","@smithy/util-defaults-mode-browser":"^3.0.23","@smithy/util-defaults-mode-node":"^3.0.23","@smithy/util-endpoints":"^2.1.3","@smithy/util-middleware":"^3.0.7","@smithy/util-retry":"^3.0.7","@smithy/util-utf8":"^3.0.0",tslib:"^2.6.2"};var devDependencies={"@aws-sdk/client-iam":"3.682.0","@tsconfig/node16":"16.1.3","@types/chai":"^4.2.11","@types/mocha":"^8.0.4","@types/node":"^16.18.96",concurrently:"7.0.0","downlevel-dts":"0.10.1",rimraf:"3.0.2",typescript:"~4.9.5"};var engines={node:">=16.0.0"};var typesVersions={"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}};var files=["dist-*/**"];var author={name:"AWS SDK for JavaScript Team",url:"https://aws.amazon.com/javascript/"};var license="Apache-2.0";var browser={"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"};var homepage="https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-cognito-identity";var repository={type:"git",url:"https://github.com/aws/aws-sdk-js-v3.git",directory:"clients/client-cognito-identity"};var packageInfo={name:name,description:description,version:version,scripts:scripts,main:main,types:types,module:module,sideEffects:sideEffects,dependencies:dependencies,devDependencies:devDependencies,engines:engines,typesVersions:typesVersions,files:files,author:author,license:license,browser:browser,"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},homepage:homepage,repository:repository};var SHA_256_HASH={name:"SHA-256"};var SHA_256_HMAC_ALGO={name:"HMAC",hash:SHA_256_HASH};var EMPTY_DATA_SHA_256=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]);const fallbackWindow={};function locateWindow(){if(typeof window!=="undefined"){return window}else if(typeof self!=="undefined"){return self}return fallbackWindow}var Sha256$1=/** @class */function(){function Sha256(secret){this.toHash=new Uint8Array(0);this.secret=secret;this.reset()}Sha256.prototype.update=function(data){if(isEmptyData(data)){return}var update=convertToBuffer(data);var typedArray=new Uint8Array(this.toHash.byteLength+update.byteLength);typedArray.set(this.toHash,0);typedArray.set(update,this.toHash.byteLength);this.toHash=typedArray};Sha256.prototype.digest=function(){var _this=this;if(this.key){return this.key.then(function(key){return locateWindow().crypto.subtle.sign(SHA_256_HMAC_ALGO,key,_this.toHash).then(function(data){return new Uint8Array(data)})})}if(isEmptyData(this.toHash)){return Promise.resolve(EMPTY_DATA_SHA_256)}return Promise.resolve().then(function(){return locateWindow().crypto.subtle.digest(SHA_256_HASH,_this.toHash)}).then(function(data){return Promise.resolve(new Uint8Array(data))})};Sha256.prototype.reset=function(){var _this=this;this.toHash=new Uint8Array(0);if(this.secret&&this.secret!==void 0){this.key=new Promise(function(resolve,reject){locateWindow().crypto.subtle.importKey("raw",convertToBuffer(_this.secret),SHA_256_HMAC_ALGO,false,["sign"]).then(resolve,reject)});this.key.catch(function(){})}};return Sha256}();var subtleCryptoMethods=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function supportsWebCrypto(window){if(supportsSecureRandom(window)&&typeof window.crypto.subtle==="object"){var subtle=window.crypto.subtle;return supportsSubtleCrypto(subtle)}return false}function supportsSecureRandom(window){if(typeof window==="object"&&typeof window.crypto==="object"){var getRandomValues=window.crypto.getRandomValues;return typeof getRandomValues==="function"}return false}function supportsSubtleCrypto(subtle){return subtle&&subtleCryptoMethods.every(function(methodName){return typeof subtle[methodName]==="function"})}var Sha256=/** @class */function(){function Sha256(secret){if(supportsWebCrypto(locateWindow())){this.hash=new Sha256$1(secret)}else{this.hash=new Sha256$2(secret)}}Sha256.prototype.update=function(data,encoding){this.hash.update(convertToBuffer(data))};Sha256.prototype.digest=function(){return this.hash.digest()};Sha256.prototype.reset=function(){this.hash.reset()};return Sha256}();var es5={exports:{}};(function(module,exports){!function(e,t){module.exports=t()}(commonjsGlobal,function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=90)}({17:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=r(18),i=function(){function e(){}return e.getFirstMatch=function(e,t){var r=t.match(e);return r&&r.length>0&&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":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";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),s=e.getVersionPrecision(r),a=Math.max(i,s),o=0,u=e.map([t,r],function(t){var r=a-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&&(o=a-Math.min(i,s)),a-=1;a>=o;){if(u[0][a]>u[1][a])return 1;if(u[0][a]===u[1][a]){if(a===o)return 0;a-=1}else if(u[0][a]<u[1][a])return-1}},e.map=function(e,t){var r,n=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(r=0;r<e.length;r+=1)n.push(t(e[r]));return n},e.find=function(e,t){var r,n;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,n=e.length;r<n;r+=1){var i=e[r];if(t(i,r))return i}},e.assign=function(e){for(var t,r,n=e,i=arguments.length,s=new Array(i>1?i-1:0),a=1;a<i;a++)s[a-1]=arguments[a];if(Object.assign)return Object.assign.apply(Object,[e].concat(s));var o=function(){var e=s[t];"object"==typeof e&&null!==e&&Object.keys(e).forEach(function(t){n[t]=e[t]})};for(t=0,r=s.length;t<r;t+=1)o();return e},e.getBrowserAlias=function(e){return n.BROWSER_ALIASES_MAP[e]},e.getBrowserTypeByAlias=function(e){return n.BROWSER_MAP[e]||""},e}();t.default=i,e.exports=t.default},18:function(e,t,r){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0;t.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"};t.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"};t.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"};t.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"};t.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"}},90:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(91))&&n.__esModule?n:{default:n},s=r(18);function a(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}var o=function(){function e(){}var t,r,n;return e.getParser=function(e,t){if(void 0===t&&(t=!1),"string"!=typeof e)throw new Error("UserAgent should be a string");return new i.default(e,t)},e.parse=function(e){return new i.default(e).getResult()},t=e,n=[{key:"BROWSER_MAP",get:function(){return s.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return s.ENGINE_MAP}},{key:"OS_MAP",get:function(){return s.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return s.PLATFORMS_MAP}}],(r=null)&&a(t.prototype,r),n&&a(t,n),e}();t.default=o,e.exports=t.default},91:function(e,t,r){t.__esModule=!0,t.default=void 0;var n=u(r(92)),i=u(r(93)),s=u(r(94)),a=u(r(95)),o=u(r(17));function u(e){return e&&e.__esModule?e:{default:e}}var d=function(){function e(e,t){if(void 0===t&&(t=!1),null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}var t=e.prototype;return t.getUA=function(){return this._ua},t.test=function(e){return e.test(this._ua)},t.parseBrowser=function(){var e=this;this.parsedResult.browser={};var t=o.default.find(n.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser},t.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},t.getBrowserName=function(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},t.getBrowserVersion=function(){return this.getBrowser().version},t.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},t.parseOS=function(){var e=this;this.parsedResult.os={};var t=o.default.find(i.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os},t.getOSName=function(e){var t=this.getOS().name;return e?String(t).toLowerCase()||"":t||""},t.getOSVersion=function(){return this.getOS().version},t.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},t.getPlatformType=function(e){void 0===e&&(e=!1);var t=this.getPlatform().type;return e?String(t).toLowerCase()||"":t||""},t.parsePlatform=function(){var e=this;this.parsedResult.platform={};var t=o.default.find(s.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform},t.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},t.getEngineName=function(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},t.parseEngine=function(){var e=this;this.parsedResult.engine={};var t=o.default.find(a.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine},t.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},t.getResult=function(){return o.default.assign({},this.parsedResult)},t.satisfies=function(e){var t=this,r={},n=0,i={},s=0;if(Object.keys(e).forEach(function(t){var a=e[t];"string"==typeof a?(i[t]=a,s+=1):"object"==typeof a&&(r[t]=a,n+=1)}),n>0){var a=Object.keys(r),u=o.default.find(a,function(e){return t.isOS(e)});if(u){var d=this.satisfies(r[u]);if(void 0!==d)return d}var c=o.default.find(a,function(e){return t.isPlatform(e)});if(c){var f=this.satisfies(r[c]);if(void 0!==f)return f}}if(s>0){var l=Object.keys(i),h=o.default.find(l,function(e){return t.isBrowser(e,!0)});if(void 0!==h)return this.compareVersion(i[h])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var r=this.getBrowserName().toLowerCase(),n=e.toLowerCase(),i=o.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(o.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};var s=/version\/(\d+(\.?_?\d+)+)/i,a=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(s,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(s,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=i.default.getFirstMatch(s,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(s,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(s,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(s,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(s,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=i.default.getFirstMatch(s,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(s,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(s,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=i.default.getFirstMatch(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=i.default.getFirstMatch(s,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=a,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},s=r(18);var a=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:s.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:s.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:s.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:s.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:s.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:s.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:s.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:s.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:s.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:s.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:s.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.PlayStation4,version:t}}}];t.default=a,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},s=r(18);var a=[{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:s.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:s.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:s.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:s.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:s.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}}];t.default=a,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},s=r(18);var a=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:s.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:s.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:s.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:s.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:s.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:s.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:s.ENGINE_MAP.WebKit},r=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];t.default=a,e.exports=t.default}})})})(es5);var es5Exports=es5.exports;var bowser=/*@__PURE__*/getDefaultExportFromCjs(es5Exports);const createDefaultUserAgentProvider=_ref41=>{let{serviceId,clientVersion}=_ref41;return async config=>{const parsedUA=typeof window!=="undefined"&&window?.navigator?.userAgent?bowser.parse(window.navigator.userAgent):undefined;const sections=[["aws-sdk-js",clientVersion],["ua","2.1"],[`os/${parsedUA?.os?.name||"other"}`,parsedUA?.os?.version],["lang/js"],["md/browser",`${parsedUA?.browser?.name??"unknown"}_${parsedUA?.browser?.version??"unknown"}`]];if(serviceId){sections.push([`api/${serviceId}`,clientVersion])}const appId=await config?.userAgentAppId?.();if(appId){sections.push([`app/${appId}`])}return sections}};const invalidProvider=message=>()=>Promise.reject(message);const TEXT_ENCODER=typeof TextEncoder=="function"?new TextEncoder:null;const calculateBodyLength=body=>{if(typeof body==="string"){if(TEXT_ENCODER){return TEXT_ENCODER.encode(body).byteLength}let len=body.length;for(let i=len-1;i>=0;i--){const code=body.charCodeAt(i);if(code>127&&code<=2047)len++;else if(code>2047&&code<=65535)len+=2;if(code>=56320&&code<=57343)i--}return len}else if(typeof body.byteLength==="number"){return body.byteLength}else if(typeof body.size==="number"){return body.size}throw new Error(`Body Length computation failed for ${body}`)};const fromUtf8=input=>new TextEncoder().encode(input);const toUtf8=input=>{if(typeof input==="string"){return input}if(typeof input!=="object"||typeof input.byteOffset!=="number"||typeof input.byteLength!=="number"){throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.")}return new TextDecoder("utf-8").decode(input)};const s="required",t="fn",u="argv",v="ref";const a=true,b="isSet",c="booleanEquals",d="error",e="endpoint",f="tree",g="PartitionResult",h={[s]:false,"type":"String"},i={[s]:true,"default":false,"type":"Boolean"},j={[v]:"Endpoint"},k={[t]:c,[u]:[{[v]:"UseFIPS"},true]},l={[t]:c,[u]:[{[v]:"UseDualStack"},true]},m={},n={[t]:"getAttr",[u]:[{[v]:g},"supportsFIPS"]},o={[t]:c,[u]:[true,{[t]:"getAttr",[u]:[{[v]:g},"supportsDualStack"]}]},p=[k],q=[l],r=[{[v]:"Region"}];const _data={version:"1.0",parameters:{Region:h,UseDualStack:i,UseFIPS:i,Endpoint:h},rules:[{conditions:[{[t]:b,[u]:[j]}],rules:[{conditions:p,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:d},{conditions:q,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:d},{endpoint:{url:j,properties:m,headers:m},type:e}],type:f},{conditions:[{[t]:b,[u]:r}],rules:[{conditions:[{[t]:"aws.partition",[u]:r,assign:g}],rules:[{conditions:[k,l],rules:[{conditions:[{[t]:c,[u]:[a,n]},o],rules:[{endpoint:{url:"https://cognito-identity-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:m,headers:m},type:e}],type:f},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:d}],type:f},{conditions:p,rules:[{conditions:[{[t]:c,[u]:[n,a]}],rules:[{endpoint:{url:"https://cognito-identity-fips.{Region}.{PartitionResult#dnsSuffix}",properties:m,headers:m},type:e}],type:f},{error:"FIPS is enabled but this partition does not support FIPS",type:d}],type:f},{conditions:q,rules:[{conditions:[o],rules:[{endpoint:{url:"https://cognito-identity.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:m,headers:m},type:e}],type:f},{error:"DualStack is enabled but this partition does not support DualStack",type:d}],type:f},{endpoint:{url:"https://cognito-identity.{Region}.{PartitionResult#dnsSuffix}",properties:m,headers:m},type:e}],type:f}],type:f},{error:"Invalid Configuration: Missing Region",type:d}]};const ruleSet=_data;const cache=new EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]});const defaultEndpointResolver=function(endpointParams){let context=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return cache.get(endpointParams,()=>resolveEndpoint(ruleSet,{endpointParams:endpointParams,logger:context.logger}))};customEndpointFunctions.aws=awsEndpointFunctions;const getRuntimeConfig$1=config=>{return{apiVersion:"2014-06-30",base64Decoder:config?.base64Decoder??fromBase64,base64Encoder:config?.base64Encoder??toBase64,disableHostPrefix:config?.disableHostPrefix??false,endpointProvider:config?.endpointProvider??defaultEndpointResolver,extensions:config?.extensions??[],httpAuthSchemeProvider:config?.httpAuthSchemeProvider??defaultCognitoIdentityHttpAuthSchemeProvider,httpAuthSchemes:config?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:ipc=>ipc.getIdentityProvider("aws.auth#sigv4"),signer:new AwsSdkSigV4Signer},{schemeId:"smithy.api#noAuth",identityProvider:ipc=>ipc.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new NoAuthSigner}],logger:config?.logger??new NoOpLogger,serviceId:config?.serviceId??"Cognito Identity",urlParser:config?.urlParser??parseUrl,utf8Decoder:config?.utf8Decoder??fromUtf8,utf8Encoder:config?.utf8Encoder??toUtf8}};const DEFAULTS_MODE_OPTIONS=["in-region","cross-region","mobile","standard","legacy"];const resolveDefaultsModeConfig=function(){let{defaultsMode}=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};return memoize(async()=>{const mode=typeof defaultsMode==="function"?await defaultsMode():defaultsMode;switch(mode?.toLowerCase()){case"auto":return Promise.resolve(isMobileBrowser()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(mode?.toLocaleLowerCase());case undefined:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`)}})};const isMobileBrowser=()=>{const parsedUA=typeof window!=="undefined"&&window?.navigator?.userAgent?bowser.parse(window.navigator.userAgent):undefined;const platform=parsedUA?.platform?.type;return platform==="tablet"||platform==="mobile"};const getRuntimeConfig=config=>{const defaultsMode=resolveDefaultsModeConfig(config);const defaultConfigProvider=()=>defaultsMode().then(loadConfigsForDefaultMode);const clientSharedValues=getRuntimeConfig$1(config);return{...clientSharedValues,...config,runtime:"browser",defaultsMode,bodyLengthChecker:config?.bodyLengthChecker??calculateBodyLength,credentialDefaultProvider:config?.credentialDefaultProvider??(_=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:config?.defaultUserAgentProvider??createDefaultUserAgentProvider({serviceId:clientSharedValues.serviceId,clientVersion:packageInfo.version}),maxAttempts:config?.maxAttempts??DEFAULT_MAX_ATTEMPTS,region:config?.region??invalidProvider("Region is missing"),requestHandler:FetchHttpHandler.create(config?.requestHandler??defaultConfigProvider),retryMode:config?.retryMode??(async()=>(await defaultConfigProvider()).retryMode||DEFAULT_RETRY_MODE),sha256:config?.sha256??Sha256,streamCollector:config?.streamCollector??streamCollector,useDualstackEndpoint:config?.useDualstackEndpoint??(()=>Promise.resolve(DEFAULT_USE_DUALSTACK_ENDPOINT)),useFipsEndpoint:config?.useFipsEndpoint??(()=>Promise.resolve(DEFAULT_USE_FIPS_ENDPOINT))}};const getAwsRegionExtensionConfiguration=runtimeConfig=>{let runtimeConfigRegion=async()=>{if(runtimeConfig.region===undefined){throw new Error("Region is missing from runtimeConfig")}const region=runtimeConfig.region;if(typeof region==="string"){return region}return region()};return{setRegion(region){runtimeConfigRegion=region},region(){return runtimeConfigRegion}}};const resolveAwsRegionExtensionConfiguration=awsRegionExtensionConfiguration=>{return{region:awsRegionExtensionConfiguration.region()}};const getHttpAuthExtensionConfiguration=runtimeConfig=>{const _httpAuthSchemes=runtimeConfig.httpAuthSchemes;let _httpAuthSchemeProvider=runtimeConfig.httpAuthSchemeProvider;let _credentials=runtimeConfig.credentials;return{setHttpAuthScheme(httpAuthScheme){const index=_httpAuthSchemes.findIndex(scheme=>scheme.schemeId===httpAuthScheme.schemeId);if(index===-1){_httpAuthSchemes.push(httpAuthScheme)}else{_httpAuthSchemes.splice(index,1,httpAuthScheme)}},httpAuthSchemes(){return _httpAuthSchemes},setHttpAuthSchemeProvider(httpAuthSchemeProvider){_httpAuthSchemeProvider=httpAuthSchemeProvider},httpAuthSchemeProvider(){return _httpAuthSchemeProvider},setCredentials(credentials){_credentials=credentials},credentials(){return _credentials}}};const resolveHttpAuthRuntimeConfig=config=>{return{httpAuthSchemes:config.httpAuthSchemes(),httpAuthSchemeProvider:config.httpAuthSchemeProvider(),credentials:config.credentials()}};const asPartial=t=>t;const resolveRuntimeExtensions=(runtimeConfig,extensions)=>{const extensionConfiguration={...asPartial(getAwsRegionExtensionConfiguration(runtimeConfig)),...asPartial(getDefaultExtensionConfiguration(runtimeConfig)),...asPartial(getHttpHandlerExtensionConfiguration(runtimeConfig)),...asPartial(getHttpAuthExtensionConfiguration(runtimeConfig))};extensions.forEach(extension=>extension.configure(extensionConfiguration));return{...runtimeConfig,...resolveAwsRegionExtensionConfiguration(extensionConfiguration),...resolveDefaultRuntimeConfig(extensionConfiguration),...resolveHttpHandlerRuntimeConfig(extensionConfiguration),...resolveHttpAuthRuntimeConfig(extensionConfiguration)}};class CognitoIdentityClient extends Client{constructor(){for(var _len2=arguments.length,_ref42=new Array(_len2),_key2=0;_key2<_len2;_key2++){_ref42[_key2]=arguments[_key2]}let[configuration]=_ref42;const _config_0=getRuntimeConfig(configuration||{});const _config_1=resolveClientEndpointParameters(_config_0);const _config_2=resolveUserAgentConfig(_config_1);const _config_3=resolveRetryConfig(_config_2);const _config_4=resolveRegionConfig(_config_3);const _config_5=resolveHostHeaderConfig(_config_4);const _config_6=resolveEndpointConfig(_config_5);const _config_7=resolveHttpAuthSchemeConfig(_config_6);const _config_8=resolveRuntimeExtensions(_config_7,configuration?.extensions||[]);super(_config_8);this.config=_config_8;this.middlewareStack.use(getUserAgentPlugin(this.config));this.middlewareStack.use(getRetryPlugin(this.config));this.middlewareStack.use(getContentLengthPlugin(this.config));this.middlewareStack.use(getHostHeaderPlugin(this.config));this.middlewareStack.use(getLoggerPlugin(this.config));this.middlewareStack.use(getRecursionDetectionPlugin(this.config));this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:defaultCognitoIdentityHttpAuthSchemeParametersProvider,identityProviderConfigProvider:async config=>new DefaultIdentityProviderConfig({"aws.auth#sigv4":config.credentials})}));this.middlewareStack.use(getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class CognitoIdentityServiceException extends ServiceException{constructor(options){super(options);Object.setPrototypeOf(this,CognitoIdentityServiceException.prototype)}}class InternalErrorException extends CognitoIdentityServiceException{constructor(opts){super({name:"InternalErrorException",$fault:"server",...opts});this.name="InternalErrorException";this.$fault="server";Object.setPrototypeOf(this,InternalErrorException.prototype)}}class InvalidParameterException extends CognitoIdentityServiceException{constructor(opts){super({name:"InvalidParameterException",$fault:"client",...opts});this.name="InvalidParameterException";this.$fault="client";Object.setPrototypeOf(this,InvalidParameterException.prototype)}}class LimitExceededException extends CognitoIdentityServiceException{constructor(opts){super({name:"LimitExceededException",$fault:"client",...opts});this.name="LimitExceededException";this.$fault="client";Object.setPrototypeOf(this,LimitExceededException.prototype)}}class NotAuthorizedException extends CognitoIdentityServiceException{constructor(opts){super({name:"NotAuthorizedException",$fault:"client",...opts});this.name="NotAuthorizedException";this.$fault="client";Object.setPrototypeOf(this,NotAuthorizedException.prototype)}}class ResourceConflictException extends CognitoIdentityServiceException{constructor(opts){super({name:"ResourceConflictException",$fault:"client",...opts});this.name="ResourceConflictException";this.$fault="client";Object.setPrototypeOf(this,ResourceConflictException.prototype)}}class TooManyRequestsException extends CognitoIdentityServiceException{constructor(opts){super({name:"TooManyRequestsException",$fault:"client",...opts});this.name="TooManyRequestsException";this.$fault="client";Object.setPrototypeOf(this,TooManyRequestsException.prototype)}}class ResourceNotFoundException extends CognitoIdentityServiceException{constructor(opts){super({name:"ResourceNotFoundException",$fault:"client",...opts});this.name="ResourceNotFoundException";this.$fault="client";Object.setPrototypeOf(this,ResourceNotFoundException.prototype)}}class ExternalServiceException extends CognitoIdentityServiceException{constructor(opts){super({name:"ExternalServiceException",$fault:"client",...opts});this.name="ExternalServiceException";this.$fault="client";Object.setPrototypeOf(this,ExternalServiceException.prototype)}}class InvalidIdentityPoolConfigurationException extends CognitoIdentityServiceException{constructor(opts){super({name:"InvalidIdentityPoolConfigurationException",$fault:"client",...opts});this.name="InvalidIdentityPoolConfigurationException";this.$fault="client";Object.setPrototypeOf(this,InvalidIdentityPoolConfigurationException.prototype)}}class DeveloperUserAlreadyRegisteredException extends CognitoIdentityServiceException{constructor(opts){super({name:"DeveloperUserAlreadyRegisteredException",$fault:"client",...opts});this.name="DeveloperUserAlreadyRegisteredException";this.$fault="client";Object.setPrototypeOf(this,DeveloperUserAlreadyRegisteredException.prototype)}}class ConcurrentModificationException extends CognitoIdentityServiceException{constructor(opts){super({name:"ConcurrentModificationException",$fault:"client",...opts});this.name="ConcurrentModificationException";this.$fault="client";Object.setPrototypeOf(this,ConcurrentModificationException.prototype)}}const GetCredentialsForIdentityInputFilterSensitiveLog=obj=>({...obj,...(obj.Logins&&{Logins:SENSITIVE_STRING})});const CredentialsFilterSensitiveLog=obj=>({...obj,...(obj.SecretKey&&{SecretKey:SENSITIVE_STRING})});const GetCredentialsForIdentityResponseFilterSensitiveLog=obj=>({...obj,...(obj.Credentials&&{Credentials:CredentialsFilterSensitiveLog(obj.Credentials)})});const GetIdInputFilterSensitiveLog=obj=>({...obj,...(obj.Logins&&{Logins:SENSITIVE_STRING})});const se_GetCredentialsForIdentityCommand=async(input,context)=>{const headers=sharedHeaders("GetCredentialsForIdentity");let body;body=JSON.stringify(_json(input));return buildHttpRpcRequest(context,headers,"/",undefined,body)};const se_GetIdCommand=async(input,context)=>{const headers=sharedHeaders("GetId");let body;body=JSON.stringify(_json(input));return buildHttpRpcRequest(context,headers,"/",undefined,body)};const de_GetCredentialsForIdentityCommand=async(output,context)=>{if(output.statusCode>=300){return de_CommandError(output,context)}const data=await parseJsonBody(output.body,context);let contents={};contents=de_GetCredentialsForIdentityResponse(data);const response={$metadata:deserializeMetadata(output),...contents};return response};const de_GetIdCommand=async(output,context)=>{if(output.statusCode>=300){return de_CommandError(output,context)}const data=await parseJsonBody(output.body,context);let contents={};contents=_json(data);const response={$metadata:deserializeMetadata(output),...contents};return response};const de_CommandError=async(output,context)=>{const parsedOutput={...output,body:await parseJsonErrorBody(output.body,context)};const errorCode=loadRestJsonErrorCode(output,parsedOutput.body);switch(errorCode){case"InternalErrorException":case"com.amazonaws.cognitoidentity#InternalErrorException":throw await de_InternalErrorExceptionRes(parsedOutput);case"InvalidParameterException":case"com.amazonaws.cognitoidentity#InvalidParameterException":throw await de_InvalidParameterExceptionRes(parsedOutput);case"LimitExceededException":case"com.amazonaws.cognitoidentity#LimitExceededException":throw await de_LimitExceededExceptionRes(parsedOutput);case"NotAuthorizedException":case"com.amazonaws.cognitoidentity#NotAuthorizedException":throw await de_NotAuthorizedExceptionRes(parsedOutput);case"ResourceConflictException":case"com.amazonaws.cognitoidentity#ResourceConflictException":throw await de_ResourceConflictExceptionRes(parsedOutput);case"TooManyRequestsException":case"com.amazonaws.cognitoidentity#TooManyRequestsException":throw await de_TooManyRequestsExceptionRes(parsedOutput);case"ResourceNotFoundException":case"com.amazonaws.cognitoidentity#ResourceNotFoundException":throw await de_ResourceNotFoundExceptionRes(parsedOutput);case"ExternalServiceException":case"com.amazonaws.cognitoidentity#ExternalServiceException":throw await de_ExternalServiceExceptionRes(parsedOutput);case"InvalidIdentityPoolConfigurationException":case"com.amazonaws.cognitoidentity#InvalidIdentityPoolConfigurationException":throw await de_InvalidIdentityPoolConfigurationExceptionRes(parsedOutput);case"DeveloperUserAlreadyRegisteredException":case"com.amazonaws.cognitoidentity#DeveloperUserAlreadyRegisteredException":throw await de_DeveloperUserAlreadyRegisteredExceptionRes(parsedOutput);case"ConcurrentModificationException":case"com.amazonaws.cognitoidentity#ConcurrentModificationException":throw await de_ConcurrentModificationExceptionRes(parsedOutput);default:const parsedBody=parsedOutput.body;return throwDefaultError({output,parsedBody,errorCode})}};const de_ConcurrentModificationExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new ConcurrentModificationException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_DeveloperUserAlreadyRegisteredExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new DeveloperUserAlreadyRegisteredException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_ExternalServiceExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new ExternalServiceException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_InternalErrorExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new InternalErrorException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_InvalidIdentityPoolConfigurationExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new InvalidIdentityPoolConfigurationException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_InvalidParameterExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new InvalidParameterException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_LimitExceededExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new LimitExceededException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_NotAuthorizedExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new NotAuthorizedException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_ResourceConflictExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new ResourceConflictException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_ResourceNotFoundExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new ResourceNotFoundException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_TooManyRequestsExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new TooManyRequestsException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_Credentials=(output,context)=>{return take(output,{AccessKeyId:expectString,Expiration:_=>expectNonNull(parseEpochTimestamp(expectNumber(_))),SecretKey:expectString,SessionToken:expectString})};const de_GetCredentialsForIdentityResponse=(output,context)=>{return take(output,{Credentials:_=>de_Credentials(_),IdentityId:expectString})};const deserializeMetadata=output=>({httpStatusCode:output.statusCode,requestId:output.headers["x-amzn-requestid"]??output.headers["x-amzn-request-id"]??output.headers["x-amz-request-id"],extendedRequestId:output.headers["x-amz-id-2"],cfId:output.headers["x-amz-cf-id"]});const throwDefaultError=withBaseException(CognitoIdentityServiceException);const buildHttpRpcRequest=async(context,headers,path,resolvedHostname,body)=>{const{hostname,protocol="https",port,path:basePath}=await context.endpoint();const contents={protocol,hostname,port,method:"POST",path:basePath.endsWith("/")?basePath.slice(0,-1)+path:basePath+path,headers};if(resolvedHostname!==undefined){contents.hostname=resolvedHostname}if(body!==undefined){contents.body=body}return new HttpRequest(contents)};function sharedHeaders(operation){return{"content-type":"application/x-amz-json-1.1","x-amz-target":`AWSCognitoIdentityService.${operation}`}}class GetCredentialsForIdentityCommand extends Command.classBuilder().ep(commonParams).m(function(Command,cs,config,o){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityService","GetCredentialsForIdentity",{}).n("CognitoIdentityClient","GetCredentialsForIdentityCommand").f(GetCredentialsForIdentityInputFilterSensitiveLog,GetCredentialsForIdentityResponseFilterSensitiveLog).ser(se_GetCredentialsForIdentityCommand).de(de_GetCredentialsForIdentityCommand).build(){}class GetIdCommand extends Command.classBuilder().ep(commonParams).m(function(Command,cs,config,o){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityService","GetId",{}).n("CognitoIdentityClient","GetIdCommand").f(GetIdInputFilterSensitiveLog,void 0).ser(se_GetIdCommand).de(de_GetIdCommand).build(){}var loadCognitoIdentity=/*#__PURE__*/Object.freeze({__proto__:null,CognitoIdentityClient:CognitoIdentityClient,GetCredentialsForIdentityCommand:GetCredentialsForIdentityCommand,GetIdCommand:GetIdCommand})});
251
+ return unsafeStringify(rnds)}const asSdkError=error=>{if(error instanceof Error)return error;if(error instanceof Object)return Object.assign(new Error,error);if(typeof error==="string")return new Error(error);return new Error(`AWS SDK error wrapper for ${error}`)};const resolveRetryConfig=input=>{const{retryStrategy,retryMode:_retryMode,maxAttempts:_maxAttempts}=input;const maxAttempts=normalizeProvider$1(_maxAttempts??DEFAULT_MAX_ATTEMPTS);return Object.assign(input,{maxAttempts,retryStrategy:async()=>{if(retryStrategy){return retryStrategy}const retryMode=await normalizeProvider$1(_retryMode)();if(retryMode===RETRY_MODES.ADAPTIVE){return new AdaptiveRetryStrategy(maxAttempts)}return new StandardRetryStrategy(maxAttempts)}})};const isStreamingPayload=request=>request?.body instanceof ReadableStream;const retryMiddleware=options=>(next,context)=>async args=>{let retryStrategy=await options.retryStrategy();const maxAttempts=await options.maxAttempts();if(isRetryStrategyV2(retryStrategy)){retryStrategy=retryStrategy;let retryToken=await retryStrategy.acquireInitialRetryToken(context["partition_id"]);let lastError=new Error;let attempts=0;let totalRetryDelay=0;const{request}=args;const isRequest=HttpRequest.isInstance(request);if(isRequest){request.headers[INVOCATION_ID_HEADER]=v4()}while(true){try{if(isRequest){request.headers[REQUEST_HEADER]=`attempt=${attempts+1}; max=${maxAttempts}`}const{response,output}=await next(args);retryStrategy.recordSuccess(retryToken);output.$metadata.attempts=attempts+1;output.$metadata.totalRetryDelay=totalRetryDelay;return{response,output}}catch(e){const retryErrorInfo=getRetryErrorInfo(e);lastError=asSdkError(e);if(isRequest&&isStreamingPayload(request)){(context.logger instanceof NoOpLogger?console:context.logger)?.warn("An error was encountered in a non-retryable streaming request.");throw lastError}try{retryToken=await retryStrategy.refreshRetryTokenForRetry(retryToken,retryErrorInfo)}catch(refreshError){if(!lastError.$metadata){lastError.$metadata={}}lastError.$metadata.attempts=attempts+1;lastError.$metadata.totalRetryDelay=totalRetryDelay;throw lastError}attempts=retryToken.getRetryCount();const delay=retryToken.getRetryDelay();totalRetryDelay+=delay;await new Promise(resolve=>setTimeout(resolve,delay))}}}else{retryStrategy=retryStrategy;if(retryStrategy?.mode)context.userAgent=[...(context.userAgent||[]),["cfg/retry-mode",retryStrategy.mode]];return retryStrategy.retry(next,args)}};const isRetryStrategyV2=retryStrategy=>typeof retryStrategy.acquireInitialRetryToken!=="undefined"&&typeof retryStrategy.refreshRetryTokenForRetry!=="undefined"&&typeof retryStrategy.recordSuccess!=="undefined";const getRetryErrorInfo=error=>{const errorInfo={error,errorType:getRetryErrorType(error)};const retryAfterHint=getRetryAfterHint(error.$response);if(retryAfterHint){errorInfo.retryAfterHint=retryAfterHint}return errorInfo};const getRetryErrorType=error=>{if(isThrottlingError(error))return"THROTTLING";if(isTransientError(error))return"TRANSIENT";if(isServerError(error))return"SERVER_ERROR";return"CLIENT_ERROR"};const retryMiddlewareOptions={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:true};const getRetryPlugin=options=>({applyToStack:clientStack=>{clientStack.add(retryMiddleware(options),retryMiddlewareOptions)}});const getRetryAfterHint=response=>{if(!HttpResponse.isInstance(response))return;const retryAfterHeaderName=Object.keys(response.headers).find(key=>key.toLowerCase()==="retry-after");if(!retryAfterHeaderName)return;const retryAfter=response.headers[retryAfterHeaderName];const retryAfterSeconds=Number(retryAfter);if(!Number.isNaN(retryAfterSeconds))return new Date(retryAfterSeconds*1000);const retryAfterDate=new Date(retryAfter);return retryAfterDate};const defaultCognitoIdentityHttpAuthSchemeParametersProvider=async(config,context,input)=>{return{operation:getSmithyContext(context).operation,region:(await normalizeProvider$1(config.region)())||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function createAwsAuthSigv4HttpAuthOption(authParameters){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-identity",region:authParameters.region},propertiesExtractor:(config,context)=>({signingProperties:{config,context}})}}function createSmithyApiNoAuthHttpAuthOption(authParameters){return{schemeId:"smithy.api#noAuth"}}const defaultCognitoIdentityHttpAuthSchemeProvider=authParameters=>{const options=[];switch(authParameters.operation){case"GetCredentialsForIdentity":{options.push(createSmithyApiNoAuthHttpAuthOption());break}case"GetId":{options.push(createSmithyApiNoAuthHttpAuthOption());break}case"GetOpenIdToken":{options.push(createSmithyApiNoAuthHttpAuthOption());break}case"UnlinkIdentity":{options.push(createSmithyApiNoAuthHttpAuthOption());break}default:{options.push(createAwsAuthSigv4HttpAuthOption(authParameters))}}return options};const resolveHttpAuthSchemeConfig=config=>{const config_0=resolveAwsSdkSigV4Config(config);return Object.assign(config_0,{authSchemePreference:normalizeProvider$1(config.authSchemePreference??[])})};const resolveClientEndpointParameters=options=>{return Object.assign(options,{useDualstackEndpoint:options.useDualstackEndpoint??false,useFipsEndpoint:options.useFipsEndpoint??false,defaultSigningName:"cognito-identity"})};const commonParams={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var version="3.806.0";var packageInfo={version:version};var SHA_256_HASH={name:"SHA-256"};var SHA_256_HMAC_ALGO={name:"HMAC",hash:SHA_256_HASH};var EMPTY_DATA_SHA_256=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]);const fallbackWindow={};function locateWindow(){if(typeof window!=="undefined"){return window}else if(typeof self!=="undefined"){return self}return fallbackWindow}var Sha256$1=/** @class */function(){function Sha256(secret){this.toHash=new Uint8Array(0);this.secret=secret;this.reset()}Sha256.prototype.update=function(data){if(isEmptyData(data)){return}var update=convertToBuffer(data);var typedArray=new Uint8Array(this.toHash.byteLength+update.byteLength);typedArray.set(this.toHash,0);typedArray.set(update,this.toHash.byteLength);this.toHash=typedArray};Sha256.prototype.digest=function(){var _this=this;if(this.key){return this.key.then(function(key){return locateWindow().crypto.subtle.sign(SHA_256_HMAC_ALGO,key,_this.toHash).then(function(data){return new Uint8Array(data)})})}if(isEmptyData(this.toHash)){return Promise.resolve(EMPTY_DATA_SHA_256)}return Promise.resolve().then(function(){return locateWindow().crypto.subtle.digest(SHA_256_HASH,_this.toHash)}).then(function(data){return Promise.resolve(new Uint8Array(data))})};Sha256.prototype.reset=function(){var _this=this;this.toHash=new Uint8Array(0);if(this.secret&&this.secret!==void 0){this.key=new Promise(function(resolve,reject){locateWindow().crypto.subtle.importKey("raw",convertToBuffer(_this.secret),SHA_256_HMAC_ALGO,false,["sign"]).then(resolve,reject)});this.key.catch(function(){})}};return Sha256}();var subtleCryptoMethods=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function supportsWebCrypto(window){if(supportsSecureRandom(window)&&typeof window.crypto.subtle==="object"){var subtle=window.crypto.subtle;return supportsSubtleCrypto(subtle)}return false}function supportsSecureRandom(window){if(typeof window==="object"&&typeof window.crypto==="object"){var getRandomValues=window.crypto.getRandomValues;return typeof getRandomValues==="function"}return false}function supportsSubtleCrypto(subtle){return subtle&&subtleCryptoMethods.every(function(methodName){return typeof subtle[methodName]==="function"})}var Sha256=/** @class */function(){function Sha256(secret){if(supportsWebCrypto(locateWindow())){this.hash=new Sha256$1(secret)}else{this.hash=new Sha256$2(secret)}}Sha256.prototype.update=function(data,encoding){this.hash.update(convertToBuffer(data))};Sha256.prototype.digest=function(){return this.hash.digest()};Sha256.prototype.reset=function(){this.hash.reset()};return Sha256}();var es5$1={exports:{}};var es5=es5$1.exports;var hasRequiredEs5;function requireEs5(){if(hasRequiredEs5)return es5$1.exports;hasRequiredEs5=1;(function(module,exports){!function(e,t){module.exports=t()}(es5,function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:false,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=true,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:true,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:true})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:true,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=90)}({17:function(e,t,r){t.__esModule=true,t.default=void 0;var n=r(18),i=function(){function e(){}return e.getFirstMatch=function(e,t){var r=t.match(e);return r&&r.length>0&&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":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";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=false);var i=e.getVersionPrecision(t),s=e.getVersionPrecision(r),a=Math.max(i,s),o=0,u=e.map([t,r],function(t){var r=a-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&&(o=a-Math.min(i,s)),a-=1;a>=o;){if(u[0][a]>u[1][a])return 1;if(u[0][a]===u[1][a]){if(a===o)return 0;a-=1}else if(u[0][a]<u[1][a])return-1}},e.map=function(e,t){var r,n=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(r=0;r<e.length;r+=1)n.push(t(e[r]));return n},e.find=function(e,t){var r,n;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,n=e.length;r<n;r+=1){var i=e[r];if(t(i,r))return i}},e.assign=function(e){for(var t,r,n=e,i=arguments.length,s=new Array(i>1?i-1:0),a=1;a<i;a++)s[a-1]=arguments[a];if(Object.assign)return Object.assign.apply(Object,[e].concat(s));var o=function(){var e=s[t];"object"==typeof e&&null!==e&&Object.keys(e).forEach(function(t){n[t]=e[t]})};for(t=0,r=s.length;t<r;t+=1)o();return e},e.getBrowserAlias=function(e){return n.BROWSER_ALIASES_MAP[e]},e.getBrowserTypeByAlias=function(e){return n.BROWSER_MAP[e]||""},e}();t.default=i,e.exports=t.default},18:function(e,t,r){t.__esModule=true,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0;t.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"};t.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"};t.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"};t.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"};t.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"}},90:function(e,t,r){t.__esModule=true,t.default=void 0;var n,i=(n=r(91))&&n.__esModule?n:{default:n},s=r(18);function a(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||false,n.configurable=true,"value"in n&&(n.writable=true),Object.defineProperty(e,n.key,n)}}var o=function(){function e(){}var t,r,n;return e.getParser=function(e,t){if(void 0===t&&(t=false),"string"!=typeof e)throw new Error("UserAgent should be a string");return new i.default(e,t)},e.parse=function(e){return new i.default(e).getResult()},t=e,n=[{key:"BROWSER_MAP",get:function(){return s.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return s.ENGINE_MAP}},{key:"OS_MAP",get:function(){return s.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return s.PLATFORMS_MAP}}],(r=null)&&a(t.prototype,r),n&&a(t,n),e}();t.default=o,e.exports=t.default},91:function(e,t,r){t.__esModule=true,t.default=void 0;var n=u(r(92)),i=u(r(93)),s=u(r(94)),a=u(r(95)),o=u(r(17));function u(e){return e&&e.__esModule?e:{default:e}}var d=function(){function e(e,t){if(void 0===t&&(t=false),null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},true!==t&&this.parse()}var t=e.prototype;return t.getUA=function(){return this._ua},t.test=function(e){return e.test(this._ua)},t.parseBrowser=function(){var e=this;this.parsedResult.browser={};var t=o.default.find(n.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser},t.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},t.getBrowserName=function(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},t.getBrowserVersion=function(){return this.getBrowser().version},t.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},t.parseOS=function(){var e=this;this.parsedResult.os={};var t=o.default.find(i.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os},t.getOSName=function(e){var t=this.getOS().name;return e?String(t).toLowerCase()||"":t||""},t.getOSVersion=function(){return this.getOS().version},t.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},t.getPlatformType=function(e){void 0===e&&(e=false);var t=this.getPlatform().type;return e?String(t).toLowerCase()||"":t||""},t.parsePlatform=function(){var e=this;this.parsedResult.platform={};var t=o.default.find(s.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform},t.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},t.getEngineName=function(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},t.parseEngine=function(){var e=this;this.parsedResult.engine={};var t=o.default.find(a.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine},t.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},t.getResult=function(){return o.default.assign({},this.parsedResult)},t.satisfies=function(e){var t=this,r={},n=0,i={},s=0;if(Object.keys(e).forEach(function(t){var a=e[t];"string"==typeof a?(i[t]=a,s+=1):"object"==typeof a&&(r[t]=a,n+=1)}),n>0){var a=Object.keys(r),u=o.default.find(a,function(e){return t.isOS(e)});if(u){var d=this.satisfies(r[u]);if(void 0!==d)return d}var c=o.default.find(a,function(e){return t.isPlatform(e)});if(c){var f=this.satisfies(r[c]);if(void 0!==f)return f}}if(s>0){var l=Object.keys(i),h=o.default.find(l,function(e){return t.isBrowser(e,true)});if(void 0!==h)return this.compareVersion(i[h])}},t.isBrowser=function(e,t){void 0===t&&(t=false);var r=this.getBrowserName().toLowerCase(),n=e.toLowerCase(),i=o.default.getBrowserTypeByAlias(n);return t&&i&&(n=i.toLowerCase()),n===r},t.compareVersion=function(e){var t=[0],r=e,n=false,i=this.getBrowserVersion();if("string"==typeof i)return">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(n=true,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(n=true,r=e.substr(1)),t.indexOf(o.default.compareVersions(i,r,n))>-1},t.isOS=function(e){return this.getOSName(true)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(true)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(true)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=false),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=true,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n};var s=/version\/(\d+(\.?_?\d+)+)/i,a=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(s,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(s,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=i.default.getFirstMatch(s,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(s,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(s,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(s,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(s,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=i.default.getFirstMatch(s,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(s,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(s,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=i.default.getFirstMatch(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,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(s,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=i.default.getFirstMatch(s,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=i.default.getFirstMatch(s,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=a,e.exports=t.default},93:function(e,t,r){t.__esModule=true,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18);var a=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:s.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:s.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:s.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:s.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:s.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:s.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:s.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:s.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:s.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:s.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:s.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:s.OS_MAP.PlayStation4,version:t}}}];t.default=a,e.exports=t.default},94:function(e,t,r){t.__esModule=true,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18);var a=[{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:s.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:s.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:s.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:s.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(true)},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(true)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:s.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(true)&&t>=3},describe:function(){return{type:s.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(true)},describe:function(){return{type:s.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(true)},describe:function(){return{type:s.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(true)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(true)},describe:function(){return{type:s.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(true)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(true)},describe:function(){return{type:s.PLATFORMS_MAP.tv}}}];t.default=a,e.exports=t.default},95:function(e,t,r){t.__esModule=true,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},s=r(18);var a=[{test:function(e){return"microsoft edge"===e.getBrowserName(true)},describe:function(e){if(/\sedg\//i.test(e))return{name:s.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:s.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:s.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:s.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:s.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:s.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:s.ENGINE_MAP.WebKit},r=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];t.default=a,e.exports=t.default}})})})(es5$1);return es5$1.exports}var es5Exports=requireEs5();var bowser=/*@__PURE__*/getDefaultExportFromCjs(es5Exports);const createDefaultUserAgentProvider=_ref42=>{let{serviceId,clientVersion}=_ref42;return async config=>{const parsedUA=typeof window!=="undefined"&&window?.navigator?.userAgent?bowser.parse(window.navigator.userAgent):undefined;const sections=[["aws-sdk-js",clientVersion],["ua","2.1"],[`os/${parsedUA?.os?.name||"other"}`,parsedUA?.os?.version],["lang/js"],["md/browser",`${parsedUA?.browser?.name??"unknown"}_${parsedUA?.browser?.version??"unknown"}`]];if(serviceId){sections.push([`api/${serviceId}`,clientVersion])}const appId=await config?.userAgentAppId?.();if(appId){sections.push([`app/${appId}`])}return sections}};const invalidProvider=message=>()=>Promise.reject(message);const TEXT_ENCODER=typeof TextEncoder=="function"?new TextEncoder:null;const calculateBodyLength=body=>{if(typeof body==="string"){if(TEXT_ENCODER){return TEXT_ENCODER.encode(body).byteLength}let len=body.length;for(let i=len-1;i>=0;i--){const code=body.charCodeAt(i);if(code>127&&code<=2047)len++;else if(code>2047&&code<=65535)len+=2;if(code>=56320&&code<=57343)i--}return len}else if(typeof body.byteLength==="number"){return body.byteLength}else if(typeof body.size==="number"){return body.size}throw new Error(`Body Length computation failed for ${body}`)};const fromUtf8=input=>new TextEncoder().encode(input);const toUtf8=input=>{if(typeof input==="string"){return input}if(typeof input!=="object"||typeof input.byteOffset!=="number"||typeof input.byteLength!=="number"){throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.")}return new TextDecoder("utf-8").decode(input)};const w="required",x="fn",y="argv",z="ref";const a=true,b="isSet",c="booleanEquals",d="error",e="endpoint",f="tree",g="PartitionResult",h="getAttr",i="stringEquals",j={[w]:false,"type":"String"},k={[w]:true,"default":false,"type":"Boolean"},l={[z]:"Endpoint"},m={[x]:c,[y]:[{[z]:"UseFIPS"},true]},n={[x]:c,[y]:[{[z]:"UseDualStack"},true]},o={},p={[z]:"Region"},q={[x]:h,[y]:[{[z]:g},"supportsFIPS"]},r={[z]:g},s={[x]:c,[y]:[true,{[x]:h,[y]:[r,"supportsDualStack"]}]},t=[m],u=[n],v=[p];const _data={parameters:{Region:j,UseDualStack:k,UseFIPS:k,Endpoint:j},rules:[{conditions:[{[x]:b,[y]:[l]}],rules:[{conditions:t,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:d},{conditions:u,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:d},{endpoint:{url:l,properties:o,headers:o},type:e}],type:f},{conditions:[{[x]:b,[y]:v}],rules:[{conditions:[{[x]:"aws.partition",[y]:v,assign:g}],rules:[{conditions:[m,n],rules:[{conditions:[{[x]:c,[y]:[a,q]},s],rules:[{conditions:[{[x]:i,[y]:[p,"us-east-1"]}],endpoint:{url:"https://cognito-identity-fips.us-east-1.amazonaws.com",properties:o,headers:o},type:e},{conditions:[{[x]:i,[y]:[p,"us-east-2"]}],endpoint:{url:"https://cognito-identity-fips.us-east-2.amazonaws.com",properties:o,headers:o},type:e},{conditions:[{[x]:i,[y]:[p,"us-west-1"]}],endpoint:{url:"https://cognito-identity-fips.us-west-1.amazonaws.com",properties:o,headers:o},type:e},{conditions:[{[x]:i,[y]:[p,"us-west-2"]}],endpoint:{url:"https://cognito-identity-fips.us-west-2.amazonaws.com",properties:o,headers:o},type:e},{endpoint:{url:"https://cognito-identity-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:o,headers:o},type:e}],type:f},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:d}],type:f},{conditions:t,rules:[{conditions:[{[x]:c,[y]:[q,a]}],rules:[{endpoint:{url:"https://cognito-identity-fips.{Region}.{PartitionResult#dnsSuffix}",properties:o,headers:o},type:e}],type:f},{error:"FIPS is enabled but this partition does not support FIPS",type:d}],type:f},{conditions:u,rules:[{conditions:[s],rules:[{conditions:[{[x]:i,[y]:["aws",{[x]:h,[y]:[r,"name"]}]}],endpoint:{url:"https://cognito-identity.{Region}.amazonaws.com",properties:o,headers:o},type:e},{endpoint:{url:"https://cognito-identity.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:o,headers:o},type:e}],type:f},{error:"DualStack is enabled but this partition does not support DualStack",type:d}],type:f},{endpoint:{url:"https://cognito-identity.{Region}.{PartitionResult#dnsSuffix}",properties:o,headers:o},type:e}],type:f}],type:f},{error:"Invalid Configuration: Missing Region",type:d}]};const ruleSet=_data;const cache=new EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]});const defaultEndpointResolver=function(endpointParams){let context=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return cache.get(endpointParams,()=>resolveEndpoint(ruleSet,{endpointParams:endpointParams,logger:context.logger}))};customEndpointFunctions.aws=awsEndpointFunctions;const getRuntimeConfig$1=config=>{return{apiVersion:"2014-06-30",base64Decoder:config?.base64Decoder??fromBase64,base64Encoder:config?.base64Encoder??toBase64,disableHostPrefix:config?.disableHostPrefix??false,endpointProvider:config?.endpointProvider??defaultEndpointResolver,extensions:config?.extensions??[],httpAuthSchemeProvider:config?.httpAuthSchemeProvider??defaultCognitoIdentityHttpAuthSchemeProvider,httpAuthSchemes:config?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:ipc=>ipc.getIdentityProvider("aws.auth#sigv4"),signer:new AwsSdkSigV4Signer},{schemeId:"smithy.api#noAuth",identityProvider:ipc=>ipc.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new NoAuthSigner}],logger:config?.logger??new NoOpLogger,serviceId:config?.serviceId??"Cognito Identity",urlParser:config?.urlParser??parseUrl,utf8Decoder:config?.utf8Decoder??fromUtf8,utf8Encoder:config?.utf8Encoder??toUtf8}};const DEFAULTS_MODE_OPTIONS=["in-region","cross-region","mobile","standard","legacy"];const resolveDefaultsModeConfig=function(){let{defaultsMode}=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};return memoize(async()=>{const mode=typeof defaultsMode==="function"?await defaultsMode():defaultsMode;switch(mode?.toLowerCase()){case"auto":return Promise.resolve(isMobileBrowser()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(mode?.toLocaleLowerCase());case undefined:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`)}})};const isMobileBrowser=()=>{const parsedUA=typeof window!=="undefined"&&window?.navigator?.userAgent?bowser.parse(window.navigator.userAgent):undefined;const platform=parsedUA?.platform?.type;return platform==="tablet"||platform==="mobile"};const getRuntimeConfig=config=>{const defaultsMode=resolveDefaultsModeConfig(config);const defaultConfigProvider=()=>defaultsMode().then(loadConfigsForDefaultMode);const clientSharedValues=getRuntimeConfig$1(config);return{...clientSharedValues,...config,runtime:"browser",defaultsMode,bodyLengthChecker:config?.bodyLengthChecker??calculateBodyLength,credentialDefaultProvider:config?.credentialDefaultProvider??(_=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:config?.defaultUserAgentProvider??createDefaultUserAgentProvider({serviceId:clientSharedValues.serviceId,clientVersion:packageInfo.version}),maxAttempts:config?.maxAttempts??DEFAULT_MAX_ATTEMPTS,region:config?.region??invalidProvider("Region is missing"),requestHandler:FetchHttpHandler.create(config?.requestHandler??defaultConfigProvider),retryMode:config?.retryMode??(async()=>(await defaultConfigProvider()).retryMode||DEFAULT_RETRY_MODE),sha256:config?.sha256??Sha256,streamCollector:config?.streamCollector??streamCollector,useDualstackEndpoint:config?.useDualstackEndpoint??(()=>Promise.resolve(DEFAULT_USE_DUALSTACK_ENDPOINT)),useFipsEndpoint:config?.useFipsEndpoint??(()=>Promise.resolve(DEFAULT_USE_FIPS_ENDPOINT))}};const getAwsRegionExtensionConfiguration=runtimeConfig=>{return{setRegion(region){runtimeConfig.region=region},region(){return runtimeConfig.region}}};const resolveAwsRegionExtensionConfiguration=awsRegionExtensionConfiguration=>{return{region:awsRegionExtensionConfiguration.region()}};const getHttpAuthExtensionConfiguration=runtimeConfig=>{const _httpAuthSchemes=runtimeConfig.httpAuthSchemes;let _httpAuthSchemeProvider=runtimeConfig.httpAuthSchemeProvider;let _credentials=runtimeConfig.credentials;return{setHttpAuthScheme(httpAuthScheme){const index=_httpAuthSchemes.findIndex(scheme=>scheme.schemeId===httpAuthScheme.schemeId);if(index===-1){_httpAuthSchemes.push(httpAuthScheme)}else{_httpAuthSchemes.splice(index,1,httpAuthScheme)}},httpAuthSchemes(){return _httpAuthSchemes},setHttpAuthSchemeProvider(httpAuthSchemeProvider){_httpAuthSchemeProvider=httpAuthSchemeProvider},httpAuthSchemeProvider(){return _httpAuthSchemeProvider},setCredentials(credentials){_credentials=credentials},credentials(){return _credentials}}};const resolveHttpAuthRuntimeConfig=config=>{return{httpAuthSchemes:config.httpAuthSchemes(),httpAuthSchemeProvider:config.httpAuthSchemeProvider(),credentials:config.credentials()}};const resolveRuntimeExtensions=(runtimeConfig,extensions)=>{const extensionConfiguration=Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig),getDefaultExtensionConfiguration(runtimeConfig),getHttpHandlerExtensionConfiguration(runtimeConfig),getHttpAuthExtensionConfiguration(runtimeConfig));extensions.forEach(extension=>extension.configure(extensionConfiguration));return Object.assign(runtimeConfig,resolveAwsRegionExtensionConfiguration(extensionConfiguration),resolveDefaultRuntimeConfig(extensionConfiguration),resolveHttpHandlerRuntimeConfig(extensionConfiguration),resolveHttpAuthRuntimeConfig(extensionConfiguration))};class CognitoIdentityClient extends Client{config;constructor(){for(var _len2=arguments.length,_ref43=new Array(_len2),_key2=0;_key2<_len2;_key2++){_ref43[_key2]=arguments[_key2]}let[configuration]=_ref43;const _config_0=getRuntimeConfig(configuration||{});super(_config_0);this.initConfig=_config_0;const _config_1=resolveClientEndpointParameters(_config_0);const _config_2=resolveUserAgentConfig(_config_1);const _config_3=resolveRetryConfig(_config_2);const _config_4=resolveRegionConfig(_config_3);const _config_5=resolveHostHeaderConfig(_config_4);const _config_6=resolveEndpointConfig(_config_5);const _config_7=resolveHttpAuthSchemeConfig(_config_6);const _config_8=resolveRuntimeExtensions(_config_7,configuration?.extensions||[]);this.config=_config_8;this.middlewareStack.use(getUserAgentPlugin(this.config));this.middlewareStack.use(getRetryPlugin(this.config));this.middlewareStack.use(getContentLengthPlugin(this.config));this.middlewareStack.use(getHostHeaderPlugin(this.config));this.middlewareStack.use(getLoggerPlugin(this.config));this.middlewareStack.use(getRecursionDetectionPlugin(this.config));this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:defaultCognitoIdentityHttpAuthSchemeParametersProvider,identityProviderConfigProvider:async config=>new DefaultIdentityProviderConfig({"aws.auth#sigv4":config.credentials})}));this.middlewareStack.use(getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class CognitoIdentityServiceException extends ServiceException{constructor(options){super(options);Object.setPrototypeOf(this,CognitoIdentityServiceException.prototype)}}class InternalErrorException extends CognitoIdentityServiceException{name="InternalErrorException";$fault="server";constructor(opts){super({name:"InternalErrorException",$fault:"server",...opts});Object.setPrototypeOf(this,InternalErrorException.prototype)}}class InvalidParameterException extends CognitoIdentityServiceException{name="InvalidParameterException";$fault="client";constructor(opts){super({name:"InvalidParameterException",$fault:"client",...opts});Object.setPrototypeOf(this,InvalidParameterException.prototype)}}class LimitExceededException extends CognitoIdentityServiceException{name="LimitExceededException";$fault="client";constructor(opts){super({name:"LimitExceededException",$fault:"client",...opts});Object.setPrototypeOf(this,LimitExceededException.prototype)}}class NotAuthorizedException extends CognitoIdentityServiceException{name="NotAuthorizedException";$fault="client";constructor(opts){super({name:"NotAuthorizedException",$fault:"client",...opts});Object.setPrototypeOf(this,NotAuthorizedException.prototype)}}class ResourceConflictException extends CognitoIdentityServiceException{name="ResourceConflictException";$fault="client";constructor(opts){super({name:"ResourceConflictException",$fault:"client",...opts});Object.setPrototypeOf(this,ResourceConflictException.prototype)}}class TooManyRequestsException extends CognitoIdentityServiceException{name="TooManyRequestsException";$fault="client";constructor(opts){super({name:"TooManyRequestsException",$fault:"client",...opts});Object.setPrototypeOf(this,TooManyRequestsException.prototype)}}class ResourceNotFoundException extends CognitoIdentityServiceException{name="ResourceNotFoundException";$fault="client";constructor(opts){super({name:"ResourceNotFoundException",$fault:"client",...opts});Object.setPrototypeOf(this,ResourceNotFoundException.prototype)}}class ExternalServiceException extends CognitoIdentityServiceException{name="ExternalServiceException";$fault="client";constructor(opts){super({name:"ExternalServiceException",$fault:"client",...opts});Object.setPrototypeOf(this,ExternalServiceException.prototype)}}class InvalidIdentityPoolConfigurationException extends CognitoIdentityServiceException{name="InvalidIdentityPoolConfigurationException";$fault="client";constructor(opts){super({name:"InvalidIdentityPoolConfigurationException",$fault:"client",...opts});Object.setPrototypeOf(this,InvalidIdentityPoolConfigurationException.prototype)}}class DeveloperUserAlreadyRegisteredException extends CognitoIdentityServiceException{name="DeveloperUserAlreadyRegisteredException";$fault="client";constructor(opts){super({name:"DeveloperUserAlreadyRegisteredException",$fault:"client",...opts});Object.setPrototypeOf(this,DeveloperUserAlreadyRegisteredException.prototype)}}class ConcurrentModificationException extends CognitoIdentityServiceException{name="ConcurrentModificationException";$fault="client";constructor(opts){super({name:"ConcurrentModificationException",$fault:"client",...opts});Object.setPrototypeOf(this,ConcurrentModificationException.prototype)}}const GetCredentialsForIdentityInputFilterSensitiveLog=obj=>({...obj,...(obj.Logins&&{Logins:SENSITIVE_STRING})});const CredentialsFilterSensitiveLog=obj=>({...obj,...(obj.SecretKey&&{SecretKey:SENSITIVE_STRING})});const GetCredentialsForIdentityResponseFilterSensitiveLog=obj=>({...obj,...(obj.Credentials&&{Credentials:CredentialsFilterSensitiveLog(obj.Credentials)})});const GetIdInputFilterSensitiveLog=obj=>({...obj,...(obj.Logins&&{Logins:SENSITIVE_STRING})});const se_GetCredentialsForIdentityCommand=async(input,context)=>{const headers=sharedHeaders("GetCredentialsForIdentity");let body;body=JSON.stringify(_json(input));return buildHttpRpcRequest(context,headers,"/",undefined,body)};const se_GetIdCommand=async(input,context)=>{const headers=sharedHeaders("GetId");let body;body=JSON.stringify(_json(input));return buildHttpRpcRequest(context,headers,"/",undefined,body)};const de_GetCredentialsForIdentityCommand=async(output,context)=>{if(output.statusCode>=300){return de_CommandError(output,context)}const data=await parseJsonBody(output.body,context);let contents={};contents=de_GetCredentialsForIdentityResponse(data);const response={$metadata:deserializeMetadata(output),...contents};return response};const de_GetIdCommand=async(output,context)=>{if(output.statusCode>=300){return de_CommandError(output,context)}const data=await parseJsonBody(output.body,context);let contents={};contents=_json(data);const response={$metadata:deserializeMetadata(output),...contents};return response};const de_CommandError=async(output,context)=>{const parsedOutput={...output,body:await parseJsonErrorBody(output.body,context)};const errorCode=loadRestJsonErrorCode(output,parsedOutput.body);switch(errorCode){case"InternalErrorException":case"com.amazonaws.cognitoidentity#InternalErrorException":throw await de_InternalErrorExceptionRes(parsedOutput);case"InvalidParameterException":case"com.amazonaws.cognitoidentity#InvalidParameterException":throw await de_InvalidParameterExceptionRes(parsedOutput);case"LimitExceededException":case"com.amazonaws.cognitoidentity#LimitExceededException":throw await de_LimitExceededExceptionRes(parsedOutput);case"NotAuthorizedException":case"com.amazonaws.cognitoidentity#NotAuthorizedException":throw await de_NotAuthorizedExceptionRes(parsedOutput);case"ResourceConflictException":case"com.amazonaws.cognitoidentity#ResourceConflictException":throw await de_ResourceConflictExceptionRes(parsedOutput);case"TooManyRequestsException":case"com.amazonaws.cognitoidentity#TooManyRequestsException":throw await de_TooManyRequestsExceptionRes(parsedOutput);case"ResourceNotFoundException":case"com.amazonaws.cognitoidentity#ResourceNotFoundException":throw await de_ResourceNotFoundExceptionRes(parsedOutput);case"ExternalServiceException":case"com.amazonaws.cognitoidentity#ExternalServiceException":throw await de_ExternalServiceExceptionRes(parsedOutput);case"InvalidIdentityPoolConfigurationException":case"com.amazonaws.cognitoidentity#InvalidIdentityPoolConfigurationException":throw await de_InvalidIdentityPoolConfigurationExceptionRes(parsedOutput);case"DeveloperUserAlreadyRegisteredException":case"com.amazonaws.cognitoidentity#DeveloperUserAlreadyRegisteredException":throw await de_DeveloperUserAlreadyRegisteredExceptionRes(parsedOutput);case"ConcurrentModificationException":case"com.amazonaws.cognitoidentity#ConcurrentModificationException":throw await de_ConcurrentModificationExceptionRes(parsedOutput);default:const parsedBody=parsedOutput.body;return throwDefaultError({output,parsedBody,errorCode})}};const de_ConcurrentModificationExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new ConcurrentModificationException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_DeveloperUserAlreadyRegisteredExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new DeveloperUserAlreadyRegisteredException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_ExternalServiceExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new ExternalServiceException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_InternalErrorExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new InternalErrorException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_InvalidIdentityPoolConfigurationExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new InvalidIdentityPoolConfigurationException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_InvalidParameterExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new InvalidParameterException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_LimitExceededExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new LimitExceededException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_NotAuthorizedExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new NotAuthorizedException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_ResourceConflictExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new ResourceConflictException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_ResourceNotFoundExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new ResourceNotFoundException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_TooManyRequestsExceptionRes=async(parsedOutput,context)=>{const body=parsedOutput.body;const deserialized=_json(body);const exception=new TooManyRequestsException({$metadata:deserializeMetadata(parsedOutput),...deserialized});return decorateServiceException(exception,body)};const de_Credentials=(output,context)=>{return take(output,{AccessKeyId:expectString,Expiration:_=>expectNonNull(parseEpochTimestamp(expectNumber(_))),SecretKey:expectString,SessionToken:expectString})};const de_GetCredentialsForIdentityResponse=(output,context)=>{return take(output,{Credentials:_=>de_Credentials(_),IdentityId:expectString})};const deserializeMetadata=output=>({httpStatusCode:output.statusCode,requestId:output.headers["x-amzn-requestid"]??output.headers["x-amzn-request-id"]??output.headers["x-amz-request-id"],extendedRequestId:output.headers["x-amz-id-2"],cfId:output.headers["x-amz-cf-id"]});const throwDefaultError=withBaseException(CognitoIdentityServiceException);const buildHttpRpcRequest=async(context,headers,path,resolvedHostname,body)=>{const{hostname,protocol="https",port,path:basePath}=await context.endpoint();const contents={protocol,hostname,port,method:"POST",path:basePath.endsWith("/")?basePath.slice(0,-1)+path:basePath+path,headers};if(body!==undefined){contents.body=body}return new HttpRequest(contents)};function sharedHeaders(operation){return{"content-type":"application/x-amz-json-1.1","x-amz-target":`AWSCognitoIdentityService.${operation}`}}class GetCredentialsForIdentityCommand extends Command.classBuilder().ep(commonParams).m(function(Command,cs,config,o){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityService","GetCredentialsForIdentity",{}).n("CognitoIdentityClient","GetCredentialsForIdentityCommand").f(GetCredentialsForIdentityInputFilterSensitiveLog,GetCredentialsForIdentityResponseFilterSensitiveLog).ser(se_GetCredentialsForIdentityCommand).de(de_GetCredentialsForIdentityCommand).build(){}class GetIdCommand extends Command.classBuilder().ep(commonParams).m(function(Command,cs,config,o){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityService","GetId",{}).n("CognitoIdentityClient","GetIdCommand").f(GetIdInputFilterSensitiveLog,void 0).ser(se_GetIdCommand).de(de_GetIdCommand).build(){}var loadCognitoIdentity=/*#__PURE__*/Object.freeze({__proto__:null,CognitoIdentityClient:CognitoIdentityClient,GetCredentialsForIdentityCommand:GetCredentialsForIdentityCommand,GetIdCommand:GetIdCommand})});
@@ -2,7 +2,7 @@
2
2
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.withAPIKey = void 0;
5
+ exports.withAPIKey = withAPIKey;
6
6
  /**
7
7
  * Creates an auth helper instance using APIKey. The `getClientConfig` function creates a signer to set the APIKey in
8
8
  * all the commands of a client.
@@ -31,4 +31,3 @@ function withAPIKey(apiKey, region) {
31
31
  getClientConfig: () => clientConfig,
32
32
  };
33
33
  }
34
- exports.withAPIKey = withAPIKey;
@@ -2,7 +2,7 @@
2
2
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.withIdentityPoolId = void 0;
5
+ exports.withIdentityPoolId = withIdentityPoolId;
6
6
  const credential_providers_1 = require("@aws-sdk/credential-providers");
7
7
  const signer_1 = require("../utils/signer");
8
8
  /**
@@ -32,7 +32,7 @@ async function withIdentityPoolId(identityPoolId, options) {
32
32
  getMapAuthenticationOptions: () => ({
33
33
  transformRequest: (url, resourceType) => {
34
34
  // Only sign Amazon Location Service URLs
35
- if (url.match(/^https:\/\/maps\.(geo|geo-fips)\.[a-z0-9-]+\.(amazonaws\.com)/)) {
35
+ if (url.match(/^https:\/\/maps\.(geo|geo-fips)\.[a-z0-9-]+\.(amazonaws\.com|api\.aws)/)) {
36
36
  const urlObj = new URL(url);
37
37
  // Split the pathname into parts, using the filter(Boolean) to ignore any empty parts,
38
38
  // since the first item will be empty because the pathname looks like:
@@ -68,4 +68,3 @@ async function withIdentityPoolId(identityPoolId, options) {
68
68
  getCredentials: () => credentials,
69
69
  };
70
70
  }
71
- exports.withIdentityPoolId = withIdentityPoolId;
@@ -267,6 +267,7 @@ const getSignedHeaders = (headers) => Object.keys(headers)
267
267
  .map((key) => key.toLowerCase())
268
268
  .sort()
269
269
  .join(";");
270
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
270
271
  const getHashedPayload = (body) => {
271
272
  // Modification - For our use-case, the body is always null,
272
273
  // so we just return the EMPTY_HASH
@@ -29,7 +29,7 @@ export async function withIdentityPoolId(identityPoolId, options) {
29
29
  getMapAuthenticationOptions: () => ({
30
30
  transformRequest: (url, resourceType) => {
31
31
  // Only sign Amazon Location Service URLs
32
- if (url.match(/^https:\/\/maps\.(geo|geo-fips)\.[a-z0-9-]+\.(amazonaws\.com)/)) {
32
+ if (url.match(/^https:\/\/maps\.(geo|geo-fips)\.[a-z0-9-]+\.(amazonaws\.com|api\.aws)/)) {
33
33
  const urlObj = new URL(url);
34
34
  // Split the pathname into parts, using the filter(Boolean) to ignore any empty parts,
35
35
  // since the first item will be empty because the pathname looks like:
@@ -263,6 +263,7 @@ const getSignedHeaders = (headers) => Object.keys(headers)
263
263
  .map((key) => key.toLowerCase())
264
264
  .sort()
265
265
  .join(";");
266
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
266
267
  const getHashedPayload = (body) => {
267
268
  // Modification - For our use-case, the body is always null,
268
269
  // so we just return the EMPTY_HASH
@@ -1,3 +1,7 @@
1
1
  export declare class Signer {
2
- static signUrl(urlToSign: string, region: string, serviceName: string, accessInfo: any): string;
2
+ static signUrl(urlToSign: string, region: string, serviceName: string, accessInfo: {
3
+ access_key: string;
4
+ secret_key: string;
5
+ session_token: string;
6
+ }): string;
3
7
  }
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@aws/amazon-location-utilities-auth-helper",
3
3
  "description": "Amazon Location Utilities - Authentication Helper for JavaScript",
4
4
  "license": "Apache-2.0",
5
- "version": "1.2.0",
5
+ "version": "1.2.2",
6
6
  "keywords": [],
7
7
  "author": {
8
8
  "name": "Amazon Web Services",
@@ -65,32 +65,32 @@
65
65
  },
66
66
  "dependencies": {
67
67
  "@aws-crypto/sha256-js": "^5.2.0",
68
- "@aws-sdk/credential-providers": "^3.682.0",
69
- "@aws-sdk/types": "^3.609.0",
70
- "@smithy/util-hex-encoding": "^2.2.0"
68
+ "@aws-sdk/credential-providers": "^3.806.0",
69
+ "@aws-sdk/types": "^3.804.0",
70
+ "@smithy/util-hex-encoding": "^4.0.0"
71
71
  },
72
72
  "devDependencies": {
73
- "@babel/core": "^7.26.0",
74
- "@babel/preset-env": "^7.26.0",
75
- "@babel/preset-typescript": "^7.26.0",
73
+ "@babel/core": "^7.27.1",
74
+ "@babel/preset-env": "^7.27.2",
75
+ "@babel/preset-typescript": "^7.27.1",
76
76
  "@rollup/plugin-babel": "^6.0.4",
77
- "@rollup/plugin-commonjs": "^25.0.8",
77
+ "@rollup/plugin-commonjs": "^28.0.3",
78
78
  "@rollup/plugin-json": "^6.1.0",
79
- "@rollup/plugin-node-resolve": "^15.3.0",
79
+ "@rollup/plugin-node-resolve": "^16.0.1",
80
80
  "@types/jest": "^29.5.14",
81
- "@typescript-eslint/eslint-plugin": "^5.62.0",
82
- "@typescript-eslint/parser": "^5.62.0",
83
- "eslint": "^8.57.1",
84
- "husky": "^8.0.3",
81
+ "@typescript-eslint/eslint-plugin": "^8.32.0",
82
+ "@typescript-eslint/parser": "^8.32.0",
83
+ "eslint": "^9.26.0",
84
+ "husky": "^9.1.7",
85
85
  "jest": "^29.7.0",
86
- "lint-staged": "^15.2.10",
86
+ "lint-staged": "^15.5.2",
87
87
  "npm-run-all": "^4.1.5",
88
- "prettier": "^2.8.8",
89
- "prettier-plugin-jsdoc": "^0.4.2",
90
- "rollup": "^3.29.5",
91
- "ts-jest": "^29.2.5",
88
+ "prettier": "^3.5.3",
89
+ "prettier-plugin-jsdoc": "^1.3.2",
90
+ "rollup": "^4.40.2",
91
+ "ts-jest": "^29.3.2",
92
92
  "ts-node": "^10.9.2",
93
- "typedoc": "^0.24.8",
94
- "typescript": "^5.1.6"
93
+ "typedoc": "^0.28.4",
94
+ "typescript": "^5.8.3"
95
95
  }
96
96
  }