@aws/amazon-location-client 1.1.1 → 1.2.0

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.
package/README.md CHANGED
@@ -31,7 +31,7 @@ This example uses the Amazon Location Client to make a request that authenticate
31
31
 
32
32
  ```javascript
33
33
  // Create an authentication helper instance using an API key and region
34
- const authHelper = await amazonLocationClient.withAPIKey("<API Key>", "<Region>");
34
+ const authHelper = amazonLocationClient.withAPIKey("<API Key>", "<Region>");
35
35
 
36
36
  const client = new amazonLocationClient.GeoRoutesClient(authHelper.getClientConfig());
37
37
  const input = { ... };
@@ -63,7 +63,7 @@ The standalone Maps SDK commands are grouped into a `maps` namespace. For exampl
63
63
 
64
64
  ```javascript
65
65
  // Create an authentication helper instance using an API key and region
66
- const authHelper = await amazonLocationClient.withAPIKey("<API Key>", "<Region>");
66
+ const authHelper = amazonLocationClient.withAPIKey("<API Key>", "<Region>");
67
67
 
68
68
  const client = new amazonLocationClient.GeoMapsClient(authHelper.getClientConfig());
69
69
  const input = { ... };
@@ -77,7 +77,7 @@ The standalone Places SDK commands are grouped into a `places` namespace. For ex
77
77
 
78
78
  ```javascript
79
79
  // Create an authentication helper instance using an API key and region
80
- const authHelper = await amazonLocationClient.withAPIKey("<API Key>", "<Region>");
80
+ const authHelper = amazonLocationClient.withAPIKey("<API Key>", "<Region>");
81
81
 
82
82
  const client = new amazonLocationClient.GeoPlacesClient(authHelper.getClientConfig());
83
83
  const input = { ... };
@@ -91,7 +91,7 @@ The standalone Routes SDK commands are grouped into a `routes` namespace. For ex
91
91
 
92
92
  ```javascript
93
93
  // Create an authentication helper instance using an API key and region
94
- const authHelper = await amazonLocationClient.withAPIKey("<API Key>", "<Region>");
94
+ const authHelper = amazonLocationClient.withAPIKey("<API Key>", "<Region>");
95
95
 
96
96
  const client = new amazonLocationClient.GeoRoutesClient(authHelper.getClientConfig());
97
97
  const input = { ... };
@@ -105,7 +105,7 @@ The Location SDK commands are under the top-level namespace. For example:
105
105
 
106
106
  ```javascript
107
107
  // Create an authentication helper instance using an API key and region
108
- const authHelper = await amazonLocationClient.withAPIKey("<API Key>", "<Region>");
108
+ const authHelper = amazonLocationClient.withAPIKey("<API Key>", "<Region>");
109
109
 
110
110
  const client = new amazonLocationClient.LocationClient(authHelper.getClientConfig());
111
111
  const input = { ... };
@@ -12898,8 +12898,7 @@ ${toHex(hashedRequest)}`;
12898
12898
  const ALGORITHM_QUERY_PARAM$1="X-Amz-Algorithm";const AMZ_DATE_QUERY_PARAM$1="X-Amz-Date";const CREDENTIAL_QUERY_PARAM$1="X-Amz-Credential";const SIGNATURE_QUERY_PARAM$1="X-Amz-Signature";const SIGNED_HEADERS_QUERY_PARAM$1="X-Amz-SignedHeaders";const TOKEN_QUERY_PARAM$1="X-Amz-Security-Token";// Headers
12899
12899
  const HOST_HEADER="host";// Identifiers
12900
12900
  const KEY_TYPE_IDENTIFIER$1="aws4_request";const SHA256_ALGORITHM_IDENTIFIER="AWS4-HMAC-SHA256";const SIGNATURE_IDENTIFIER="AWS4";// Preset values
12901
- const EMPTY_HASH="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";class Signer{static signUrl(urlToSign,region,accessInfo){const method="GET";let body;const presignable={body,method,url:new URL(urlToSign)};const options=getOptions(urlToSign,region,accessInfo);const signedUrl=presignUrl(presignable,options);return signedUrl.toString()}}const getOptions=(url,region,accessInfo)=>{const{access_key,secret_key,session_token}=accessInfo!==null&&accessInfo!==void 0?accessInfo:{};const credentials={accessKeyId:access_key,secretAccessKey:secret_key,sessionToken:session_token};// Service hard-coded to "geo" for our purposes
12902
- const service="geo";return {credentials,signingDate:new Date,signingRegion:region,signingService:service}};/**
12901
+ const EMPTY_HASH="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";class Signer{static signUrl(urlToSign,region,serviceName,accessInfo){const method="GET";let body;const presignable={body,method,url:new URL(urlToSign)};const options=getOptions(urlToSign,region,serviceName,accessInfo);const signedUrl=presignUrl(presignable,options);return signedUrl.toString()}}const getOptions=(url,region,serviceName,accessInfo)=>{const{access_key,secret_key,session_token}=accessInfo!==null&&accessInfo!==void 0?accessInfo:{};const credentials={accessKeyId:access_key,secretAccessKey:secret_key,sessionToken:session_token};return {credentials,signingDate:new Date,signingRegion:region,signingService:serviceName}};/**
12903
12902
  * Given a `Presignable` object, returns a Signature Version 4 presigned `URL` object.
12904
12903
  *
12905
12904
  * @param presignable `Presignable` object containing at least a url to be presigned with authentication query params.
@@ -13044,15 +13043,23 @@ ${toHex(hashedRequest)}`;
13044
13043
  * @param identityPoolId Cognito Identity Pool Id
13045
13044
  */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
13046
13045
  if(credentials.expiration){timeToRefresh=credentials.expiration.getTime()-new Date().getTime();}// timeToRefresh minus 1 minute to give some time for the actual refresh to happen.
13047
- setTimeout(refreshCredentials,timeToRefresh-60000);}await refreshCredentials();const clientConfig={credentials:credentialsProvider,region:region};return {getMapAuthenticationOptions:()=>({transformRequest:url=>{// Only sign Amazon Location Service URLs
13048
- if(url.match(/^https:\/\/maps\.(geo|geo-fips)\.[a-z0-9-]+\.(amazonaws\.com)/)){return {url:Signer.signUrl(url,region,{access_key:credentials.accessKeyId,secret_key:credentials.secretAccessKey,session_token:credentials.sessionToken})}}return {url}}}),getLocationClientConfig:()=>clientConfig,getClientConfig:()=>clientConfig,getCredentials:()=>credentials}}// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
13046
+ setTimeout(refreshCredentials,timeToRefresh-60000);}await refreshCredentials();const clientConfig={credentials:credentialsProvider,region:region};return {getMapAuthenticationOptions:()=>({transformRequest:(url,resourceType)=>{// Only sign Amazon Location Service URLs
13047
+ 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,
13048
+ // since the first item will be empty because the pathname looks like:
13049
+ // /v2/styles/Standard/descriptor
13050
+ const pathParts=urlObj.pathname.split("/").filter(Boolean);// The signing service name for the standalone Maps SDK is "geo-maps"
13051
+ let serviceName="geo-maps";if((pathParts===null||pathParts===void 0?void 0:pathParts[0])=="v2"){// For this case, we only need to sign the map tiles, so we
13052
+ // can return the original url if it is for descriptor, sprites, or glyphs
13053
+ if(!resourceType||resourceType!=="Tile"){return {url}}}else {// The signing service name for the consolidated Location Client is "geo"
13054
+ // In this case, we need to sign all URLs (sprites, glyphs, map tiles)
13055
+ serviceName="geo";}return {url:Signer.signUrl(url,region,serviceName,{access_key:credentials.accessKeyId,secret_key:credentials.secretAccessKey,session_token:credentials.sessionToken})}}return {url}}}),getLocationClientConfig:()=>clientConfig,getClientConfig:()=>clientConfig,getCredentials:()=>credentials}}// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
13049
13056
  // SPDX-License-Identifier: Apache-2.0
13050
13057
  /**
13051
13058
  * Creates an auth helper instance using APIKey. The `getClientConfig` function creates a signer to set the APIKey in
13052
13059
  * all the commands of a client.
13053
13060
  *
13054
13061
  * @param apiKey APIKey
13055
- */async function withAPIKey(apiKey,region){const clientConfig={signer:{sign:async requestToSign=>{var _a;// APIKey in the command can override the APIKey set by auth helper.
13062
+ */function withAPIKey(apiKey,region){const clientConfig={signer:{sign:async requestToSign=>{var _a;// APIKey in the command can override the APIKey set by auth helper.
13056
13063
  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
13057
13064
  credentials:async()=>({})};// Include the region, if it was supplied
13058
13065
  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}
@@ -18588,7 +18595,7 @@ ${toHex(hashedRequest)}`}getCanonicalPath(_ref37){let{path}=_ref37;if(this.uriEs
18588
18595
 
18589
18596
  var name$1 = "@aws-sdk/client-cognito-identity";
18590
18597
  var description$1 = "AWS SDK for JavaScript Cognito Identity Client for Node.js, Browser and React Native";
18591
- var version$1 = "3.682.0";
18598
+ var version$1 = "3.685.0";
18592
18599
  var scripts$1 = {
18593
18600
  build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
18594
18601
  "build:cjs": "node ../../scripts/compilation/inline client-cognito-identity",
@@ -18599,7 +18606,7 @@ ${toHex(hashedRequest)}`}getCanonicalPath(_ref37){let{path}=_ref37;if(this.uriEs
18599
18606
  clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
18600
18607
  "extract:docs": "api-extractor run --local",
18601
18608
  "generate:client": "node ../../scripts/generate-clients/single-service --solo cognito-identity",
18602
- "test:e2e": "vitest run -c vitest.config.e2e.ts",
18609
+ "test:e2e": "vitest run -c vitest.config.e2e.ts --mode development",
18603
18610
  "test:e2e:watch": "vitest watch -c vitest.config.e2e.ts"
18604
18611
  };
18605
18612
  var main$1 = "./dist-cjs/index.js";
@@ -18653,7 +18660,6 @@ ${toHex(hashedRequest)}`}getCanonicalPath(_ref37){let{path}=_ref37;if(this.uriEs
18653
18660
  "@aws-sdk/client-iam": "3.682.0",
18654
18661
  "@tsconfig/node16": "16.1.3",
18655
18662
  "@types/chai": "^4.2.11",
18656
- "@types/mocha": "^8.0.4",
18657
18663
  "@types/node": "^16.18.96",
18658
18664
  concurrently: "7.0.0",
18659
18665
  "downlevel-dts": "0.10.1",
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@aws/amazon-location-client",
3
3
  "description": "Amazon Location Client Bundle",
4
4
  "license": "Apache-2.0",
5
- "version": "1.1.1",
5
+ "version": "1.2.0",
6
6
  "keywords": [],
7
7
  "author": {
8
8
  "name": "Amazon Web Services",
@@ -48,11 +48,11 @@
48
48
  "lint-staged": {},
49
49
  "dependencies": {
50
50
  "@aws-sdk/client-location": "^3.682.0",
51
- "@aws-sdk/credential-providers": "^3.682.0",
51
+ "@aws-sdk/credential-providers": "^3.685.0",
52
52
  "@aws-sdk/client-geo-maps": "^3.683.0",
53
53
  "@aws-sdk/client-geo-places": "^3.683.0",
54
54
  "@aws-sdk/client-geo-routes": "^3.683.0",
55
- "@aws/amazon-location-utilities-auth-helper": "^1.1.0"
55
+ "@aws/amazon-location-utilities-auth-helper": "^1.2.0"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@rollup/plugin-commonjs": "^28.0.1",