From 8b1d2366db54aaf916125ff1ea991e8590bf5535 Mon Sep 17 00:00:00 2001 From: peze <954152927@qq.com> Date: Fri, 13 Dec 2024 17:31:34 +0800 Subject: [PATCH] [typescript]upgrade by darabonba v2 --- .gitignore | 3 + Teafile | 16 +- main.tea | 960 +++++++++-------- node_modules/.package_versions.json | 1 + ts/package.json | 24 +- ts/scripts/ts_version.js | 33 + ts/src/client.ts | 1481 +++++++++++++++------------ ts/src/utils.ts | 1027 +++++++++++++++++++ ts/test/client.spec.ts | 201 ++-- utils.dara | 224 ++++ 10 files changed, 2827 insertions(+), 1143 deletions(-) create mode 100644 node_modules/.package_versions.json create mode 100644 ts/scripts/ts_version.js create mode 100644 ts/src/utils.ts create mode 100644 utils.dara diff --git a/.gitignore b/.gitignore index 04f2db7..a808de6 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,9 @@ libraries .libraries.json ts/node_modules ts/dist +ts/.nyc_output +ts/coverage +ts/package-lock.json go.sum .DS_Store diff --git a/Teafile b/Teafile index cda98fa..7c05f03 100644 --- a/Teafile +++ b/Teafile @@ -1,7 +1,7 @@ { "scope": "alibabacloud", - "name": "OpenApi", - "version": "0.3.15", + "name": "OpenApiV2", + "version": "0.1.0", "main": "./main.tea", "maintainers": [ { @@ -9,15 +9,15 @@ "email": "sdk-team@alibabacloud.com" } ], + "exports": { + "OpenApiUtil": "./utils.dara" + }, "libraries": { - "Util": "darabonba:Util:*", - "OpenApiUtil": "alibabacloud:OpenApiUtil:*", - "Credential": "alibabacloud:Credential:*", "SPI": "alibabacloud:GatewaySPI:*", - "XML": "darabonba:XML:*" + "Credential": "alibabacloud:Credential:*" }, "releases": { - "ts": "@alicloud/openapi-client:^0.4.12", + "ts": "@alicloud/openapi-core:^1.0.0", "go": "github.com/alibabacloud-go/darabonba-openapi/v2/client:v2.0.10", "csharp": "AlibabaCloud.OpenApiClient:0.1.12", "java": "com.aliyun:tea-openapi:0.3.6", @@ -104,4 +104,4 @@ ], "compatible": true } -} +} \ No newline at end of file diff --git a/main.tea b/main.tea index b6243c4..621f0f8 100644 --- a/main.tea +++ b/main.tea @@ -2,11 +2,9 @@ * This is for OpenApi SDK */ -import Util; +import './utils' OpenApiUtil; import Credential; -import OpenApiUtil; import SPI; -import XML; type @endpoint = string type @regionId = string @@ -33,66 +31,53 @@ type @signatureVersion = string type @signatureAlgorithm = string type @headers = map[string]string type @spi = SPI -type @globalParameters = GlobalParameters +type @globalParameters = OpenApiUtil.GlobalParameters type @key = string type @cert = string type @ca = string type @disableHttp2 = boolean +type @retryOptions = $RetryOptions -model GlobalParameters { - headers?: map[string]string, - queries?: map[string]string, + +model SSEResponse { + headers: map[string]string, + statusCode: number(description='HTTP Status Code'), + event: $SSEEvent } -/** - * Model for initing client - */ -model Config { - accessKeyId?: string(description='accesskey id',default=''), - accessKeySecret?: string(description='accesskey secret',default=''), - securityToken?: string(description='security token',example='a.txt',default=''), - bearerToken?: string(description='bearer token',example='the-bearer-token',default=''), - protocol?: string(description='http protocol',example='http',default='http'), - method?: string(description='http method',example='GET',default=''), - regionId?: string(description='region id',example='cn-hangzhou',default=''), - readTimeout?: integer(description='read timeout',example='10',default=''), - connectTimeout?: integer(description='connect timeout',example='10',default=''), - httpProxy?: string(description='http proxy',example='http://localhost',default=''), - httpsProxy?: string(description='https proxy',example='https://localhost',default=''), - credential?: Credential(description='credential',example='',default=''), - endpoint?: string(description='endpoint',example='cs.aliyuncs.com',default=''), - noProxy?: string(description='proxy white list',example='http://localhost',default=''), - maxIdleConns?: integer(description='max idle conns',example='3',default=''), - network?: string(description='network for endpoint',example='public',default=''), - userAgent?: string(description='user agent',example='Alibabacloud/1',default=''), - suffix?: string(description='suffix for endpoint',example='aliyun',default=''), - socks5Proxy?: string(description='socks5 proxy',default=''), - socks5NetWork?: string(description='socks5 network',example='TCP',default=''), - endpointType?: string(description='endpoint type',example='internal',default=''), - openPlatformEndpoint?: string(description='OpenPlatform endpoint',example='openplatform.aliyuncs.com',default=''), - type?: string(description='credential type',example='access_key',default='',deprecated=true), - signatureVersion?: string(description='Signature Version',example='v1',default=''), - signatureAlgorithm?: string(description='Signature Algorithm',example='ACS3-HMAC-SHA256',default=''), - globalParameters?: GlobalParameters(description='Global Parameters'), - key?: string(description='privite key for client certificate', example='MIIEvQ',default=''), - cert?: string(description='client certificate', example='-----BEGIN CERTIFICATE-----\nxxx-----END CERTIFICATE-----',default=''), - ca?: string(description='server certificate', example='-----BEGIN CERTIFICATE-----\nxxx-----END CERTIFICATE-----',default=''), - disableHttp2?: boolean(description='disable HTTP/2', example='false'), + +exception AlibabaCloud extends $Error { + statusCode?: number(description='HTTP Status Code'), + code?: string(description="Error Code"), + message?: string(description="Error Message"), + description?: string(description="Error Description"), + requestId?: string(description="Request ID"), +} + +exception Client extends AlibabaCloud { + accessDeniedDetail?: map[string]any(description="Access Denied Detail"), +} + +exception Server extends AlibabaCloud { +} + +exception Throttling extends AlibabaCloud { + retryAfter?: long(description="Retry After(ms)"), } /** * Init client with Config * @param config config contains the necessary information to create a client */ -init(config: Config) { - if (Util.isUnset(config)) { - throw { +init(config: OpenApiUtil.Config) { + if ($isNull(config)) { + throw new Client { code = 'ParameterMissing', message = '\'config\' can not be unset' }; } - if(!Util.empty(config.accessKeyId) && !Util.empty(config.accessKeySecret)){ - if (!Util.empty(config.securityToken)) { + if(!$isNull(config.accessKeyId) && !$isNull(config.accessKeySecret)){ + if (!$isNull(config.securityToken)) { config.type = 'sts'; } else { config.type = 'access_key'; @@ -104,13 +89,13 @@ init(config: Config) { }; credentialConfig.securityToken = config.securityToken; @credential = new Credential(credentialConfig); - } else if (!Util.empty(config.bearerToken)) { + } else if (!$isNull(config.bearerToken)) { var cc = new Credential.Config{ type = 'bearer', bearerToken = config.bearerToken }; @credential = new Credential(cc); - } else if(!Util.isUnset(config.credential)) { + } else if(!$isNull(config.credential)) { @credential = config.credential; } @endpoint = config.endpoint; @@ -136,15 +121,7 @@ init(config: Config) { @cert = config.cert; @ca = config.ca; @disableHttp2 = config.disableHttp2; -} - -model OpenApiRequest { - headers?: map[string]string, - query?: map[string]string, - body?: any, - stream?: readable, - hostMap?: map[string]string, - endpointOverride?: string, + @retryOptions = config.retryOptions; } /** @@ -159,29 +136,29 @@ model OpenApiRequest { * @param runtime which controls some details of call api, such as retry times * @return the response */ -api doRPCRequest(action: string, version: string, protocol: string, method: string, authType: string, bodyType: string, request: OpenApiRequest, runtime: Util.RuntimeOptions): object { - __request.protocol = Util.defaultString(@protocol, protocol); +api doRPCRequest(action: string, version: string, protocol: string, method: string, authType: string, bodyType: string, request: OpenApiUtil.OpenApiRequest, runtime: $RuntimeOptions): object { + __request.protocol = $string($default(@protocol, protocol)); __request.method = method; __request.pathname = '/'; var globalQueries : map[string]string = {}; var globalHeaders : map[string]string = {}; - if (!Util.isUnset(@globalParameters)) { + if (!$isNull(@globalParameters)) { var globalParams = @globalParameters; - if (!Util.isUnset(globalParams.queries)) { + if (!$isNull(globalParams.queries)) { globalQueries = globalParams.queries; } - if (!Util.isUnset(globalParams.headers)) { + if (!$isNull(globalParams.headers)) { globalHeaders = globalParams.headers; } } var extendsHeaders : map[string]string = {}; var extendsQueries : map[string]string = {}; - if (!Util.isUnset(runtime.extendsParameters)) { + if (!$isNull(runtime.extendsParameters)) { var extendsParameters = runtime.extendsParameters; - if (!Util.isUnset(extendsParameters.headers)) { + if (!$isNull(extendsParameters.headers)) { extendsHeaders = extendsParameters.headers; } - if (!Util.isUnset(extendsParameters.queries)) { + if (!$isNull(extendsParameters.queries)) { extendsQueries = extendsParameters.queries; } } @@ -190,20 +167,20 @@ api doRPCRequest(action: string, version: string, protocol: string, method: stri Format = 'json', Version = version, Timestamp = OpenApiUtil.getTimestamp(), - SignatureNonce = Util.getNonce(), + SignatureNonce = OpenApiUtil.getNonce(), ...globalQueries, ...extendsQueries, ...request.query }; var headers = getRpcHeaders(); - if(Util.isUnset(headers)){ + if($isNull(headers)){ // endpoint is setted in product client __request.headers = { host = @endpoint, x-acs-version = version, x-acs-action = action, - user-agent = getUserAgent(), + user-agent = OpenApiUtil.getUserAgent(@userAgent), ...globalHeaders, ...extendsHeaders }; @@ -212,30 +189,31 @@ api doRPCRequest(action: string, version: string, protocol: string, method: stri host = @endpoint, x-acs-version = version, x-acs-action = action, - user-agent = getUserAgent(), + user-agent = OpenApiUtil.getUserAgent(@userAgent), ...globalHeaders, ...extendsHeaders, ...headers }; } - if (!Util.isUnset(request.body)) { - var m = Util.assertAsMap(request.body); - var tmp = Util.anyifyMapValue(OpenApiUtil.query(m)); - __request.body = Util.toFormString(tmp); + if (!$isNull(request.body)) { + var m = $object(request.body); + var tmp = $object(OpenApiUtil.query(m)); + __request.body = $Form.toFormString(tmp); __request.headers.content-type = 'application/x-www-form-urlencoded'; } - if (!Util.equalString(authType, 'Anonymous')) { - if (Util.isUnset(@credential)) { - throw { + + if (authType != 'Anonymous') { + if ($isNull(@credential)) { + throw new Client{ code = `InvalidCredentials`, message = `Please set up the credentials correctly. If you are setting them through environment variables, please ensure that ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set correctly. See https://help.aliyun.com/zh/sdk/developer-reference/configure-the-alibaba-cloud-accesskey-environment-variable-on-linux-macos-and-windows-systems for more details.` } } var credentialModel = @credential.getCredential(); var credentialType = credentialModel.type; - if (Util.equalString(credentialType, 'bearer')) { + if (credentialType == 'bearer') { var bearerToken = credentialModel.bearerToken; __request.query.BearerToken = bearerToken; __request.query.SignatureType = 'BEARERTOKEN'; @@ -243,15 +221,15 @@ api doRPCRequest(action: string, version: string, protocol: string, method: stri var accessKeyId = credentialModel.accessKeyId; var accessKeySecret = credentialModel.accessKeySecret; var securityToken = credentialModel.securityToken; - if (!Util.empty(securityToken)) { + if (!$isNull(securityToken)) { __request.query.SecurityToken = securityToken; } __request.query.SignatureMethod = 'HMAC-SHA1'; __request.query.SignatureVersion = '1.0'; __request.query.AccessKeyId = accessKeyId; var t : map[string]any = null; - if (!Util.isUnset(request.body)) { - t = Util.assertAsMap(request.body); + if (!$isNull(request.body)) { + t = $object(request.body); } var signedParam = { ...__request.query, @@ -261,50 +239,70 @@ api doRPCRequest(action: string, version: string, protocol: string, method: stri } } } returns { - if (Util.is4xx(__response.statusCode) || Util.is5xx(__response.statusCode)) { - var _res = Util.readAsJSON(__response.body); - var err = Util.assertAsMap(_res); - var requestId = defaultAny(err.RequestId, err.requestId); - err.statusCode = __response.statusCode; - throw { - code = `${defaultAny(err.Code, err.code)}`, - message = `code: ${__response.statusCode}, ${defaultAny(err.Message, err.message)} request id: ${requestId}`, - data = err, - description = `${defaultAny(err.Description, err.description)}`, - accessDeniedDetail = defaultAny(err.AccessDeniedDetail, err.accessDeniedDetail), - }; + if ((__response.statusCode >= 400) && (__response.statusCode < 600)) { + var _res = $Stream.readAsJSON(__response.body); + var err = $object(_res); + var requestId = $default(err.RequestId, err.requestId); + var code = $default(err.Code, err.code); + if ((`${code}` == 'Throttling') || (`${code}` == 'Throttling.User') || (`${code}` == 'Throttling.Api')) { + throw new Throttling{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + retryAfter = OpenApiUtil.getThrottlingTimeLeft(__response.headers), + requestId = `${requestId}`, + }; + } else if ((__response.statusCode >= 400) && (__response.statusCode < 500)) { + throw new Client{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + accessDeniedDetail = getAccessDeniedDetail(err), + requestId = `${requestId}`, + }; + } else { + throw new Server{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + requestId = `${requestId}`, + }; + } } - if (Util.equalString(bodyType, 'binary')) { + if (bodyType == 'binary') { var resp = { body = __response.body, headers = __response.headers, statusCode = __response.statusCode }; return resp; - } else if (Util.equalString(bodyType, 'byte')) { - var byt = Util.readAsBytes(__response.body); + } else if (bodyType == 'byte') { + var byt = $Stream.readAsBytes(__response.body); return { body = byt, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(bodyType, 'string')) { - var str = Util.readAsString(__response.body); + } else if (bodyType == 'string') { + var str = $Stream.readAsString(__response.body); return { body = str, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(bodyType, 'json')){ - var obj = Util.readAsJSON(__response.body); - var res = Util.assertAsMap(obj); + } else if (bodyType == 'json'){ + var obj = $Stream.readAsJSON(__response.body); + var res = $object(obj); return { body = res, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(bodyType, 'array')){ - var arr = Util.readAsJSON(__response.body); + } else if (bodyType == 'array'){ + var arr = $Stream.readAsJSON(__response.body); return { body = arr, headers = __response.headers, @@ -317,26 +315,18 @@ api doRPCRequest(action: string, version: string, protocol: string, method: stri }; } } runtime { - timeouted = 'retry', - key = Util.defaultString(runtime.key, @key), - cert = Util.defaultString(runtime.cert, @cert), - ca = Util.defaultString(runtime.ca, @ca), - readTimeout = Util.defaultNumber(runtime.readTimeout, @readTimeout), - connectTimeout = Util.defaultNumber(runtime.connectTimeout, @connectTimeout), - httpProxy = Util.defaultString(runtime.httpProxy, @httpProxy), - httpsProxy = Util.defaultString(runtime.httpsProxy, @httpsProxy), - noProxy = Util.defaultString(runtime.noProxy, @noProxy), - socks5Proxy = Util.defaultString(runtime.socks5Proxy, @socks5Proxy), - socks5NetWork = Util.defaultString(runtime.socks5NetWork, @socks5NetWork), - maxIdleConns = Util.defaultNumber(runtime.maxIdleConns, @maxIdleConns), - retry = { - retryable = runtime.autoretry, - maxAttempts = Util.defaultNumber(runtime.maxAttempts, 3) - }, - backoff = { - policy = Util.defaultString(runtime.backoffPolicy, 'no'), - period = Util.defaultNumber(runtime.backoffPeriod, 1) - }, + key = $string($default(runtime.key, @key)), + cert = $string($default(runtime.cert, @cert)), + ca = $string($default(runtime.ca, @ca)), + readTimeout = $number($default(runtime.readTimeout, @readTimeout)), + connectTimeout = $number($default(runtime.connectTimeout, @connectTimeout)), + httpProxy = $string($default(runtime.httpProxy, @httpProxy)), + httpsProxy = $string($default(runtime.httpsProxy, @httpsProxy)), + noProxy = $string($default(runtime.noProxy, @noProxy)), + socks5Proxy = $string($default(runtime.socks5Proxy, @socks5Proxy)), + socks5NetWork = $string($default(runtime.socks5NetWork, @socks5NetWork)), + maxIdleConns = $number($default(runtime.maxIdleConns, @maxIdleConns)), + retryOptions = @retryOptions, ignoreSSL = runtime.ignoreSSL } @@ -353,49 +343,51 @@ api doRPCRequest(action: string, version: string, protocol: string, method: stri * @param runtime which controls some details of call api, such as retry times * @return the response */ -api doROARequest(action: string, version: string, protocol: string, method: string, authType: string, pathname: string, bodyType: string, request: OpenApiRequest, runtime: Util.RuntimeOptions): object { - __request.protocol = Util.defaultString(@protocol, protocol); +api doROARequest(action: string, version: string, protocol: string, method: string, authType: string, pathname: string, bodyType: string, request: OpenApiUtil.OpenApiRequest, runtime: $RuntimeOptions): object { + __request.protocol = $string($default(@protocol, protocol)); __request.method = method; __request.pathname = pathname; var globalQueries : map[string]string = {}; var globalHeaders : map[string]string = {}; - if (!Util.isUnset(@globalParameters)) { + if (!$isNull(@globalParameters)) { var globalParams = @globalParameters; - if (!Util.isUnset(globalParams.queries)) { + if (!$isNull(globalParams.queries)) { globalQueries = globalParams.queries; } - if (!Util.isUnset(globalParams.headers)) { + if (!$isNull(globalParams.headers)) { globalHeaders = globalParams.headers; } } + var extendsHeaders : map[string]string = {}; var extendsQueries : map[string]string = {}; - if (!Util.isUnset(runtime.extendsParameters)) { + if (!$isNull(runtime.extendsParameters)) { var extendsParameters = runtime.extendsParameters; - if (!Util.isUnset(extendsParameters.headers)) { + if (!$isNull(extendsParameters.headers)) { extendsHeaders = extendsParameters.headers; } - if (!Util.isUnset(extendsParameters.queries)) { + if (!$isNull(extendsParameters.queries)) { extendsQueries = extendsParameters.queries; } } + __request.headers = { - date = Util.getDateUTCString(), + date = OpenApiUtil.getDateUTCString(), host = @endpoint, accept = 'application/json', - x-acs-signature-nonce = Util.getNonce(), + x-acs-signature-nonce = OpenApiUtil.getNonce(), x-acs-signature-method = 'HMAC-SHA1', x-acs-signature-version = '1.0', x-acs-version = version, x-acs-action = action, - user-agent = Util.getUserAgent(@userAgent), + user-agent = OpenApiUtil.getUserAgent(@userAgent), ...globalHeaders, ...extendsHeaders, ...request.headers }; - if (!Util.isUnset(request.body)) { - __request.body = Util.toJSONString(request.body); + if (!$isNull(request.body)) { + __request.body = $JSON.stringify(request.body); __request.headers.content-type = 'application/json; charset=utf-8'; } @@ -403,23 +395,23 @@ api doROARequest(action: string, version: string, protocol: string, method: stri ...globalQueries, ...extendsQueries, }; - if (!Util.isUnset(request.query)) { + if (!$isNull(request.query)) { __request.query = { ...__request.query, ...request.query }; } - if (!Util.equalString(authType, 'Anonymous')) { - if (Util.isUnset(@credential)) { - throw { + if (authType != 'Anonymous') { + if ($isNull(@credential)) { + throw new Client{ code = `InvalidCredentials`, message = `Please set up the credentials correctly. If you are setting them through environment variables, please ensure that ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set correctly. See https://help.aliyun.com/zh/sdk/developer-reference/configure-the-alibaba-cloud-accesskey-environment-variable-on-linux-macos-and-windows-systems for more details.` } } var credentialModel = @credential.getCredential(); var credentialType = credentialModel.type; - if (Util.equalString(credentialType, 'bearer')) { + if (credentialType == 'bearer') { var bearerToken = credentialModel.bearerToken; __request.headers.x-acs-bearer-token = bearerToken; __request.headers.x-acs-signature-type = 'BEARERTOKEN'; @@ -427,7 +419,7 @@ api doROARequest(action: string, version: string, protocol: string, method: stri var accessKeyId = credentialModel.accessKeyId; var accessKeySecret = credentialModel.accessKeySecret; var securityToken = credentialModel.securityToken; - if (!Util.empty(securityToken)) { + if (!$isNull(securityToken)) { __request.headers.x-acs-accesskey-id = accessKeyId; __request.headers.x-acs-security-token = securityToken; } @@ -437,57 +429,77 @@ api doROARequest(action: string, version: string, protocol: string, method: stri } } } returns { - if (Util.equalNumber(__response.statusCode, 204)) { + if (__response.statusCode == 204) { return { headers = __response.headers }; } - if (Util.is4xx(__response.statusCode) || Util.is5xx(__response.statusCode)) { - var _res = Util.readAsJSON(__response.body); - var err = Util.assertAsMap(_res); - var requestId = defaultAny(err.RequestId, err.requestId); - requestId = defaultAny(requestId, err.requestid); - err.statusCode = __response.statusCode; - throw { - code = `${defaultAny(err.Code, err.code)}`, - message = `code: ${__response.statusCode}, ${defaultAny(err.Message, err.message)} request id: ${requestId}`, - data = err, - description = `${defaultAny(err.Description, err.description)}`, - accessDeniedDetail = defaultAny(err.AccessDeniedDetail, err.accessDeniedDetail), - }; + if ((__response.statusCode >= 400) && (__response.statusCode < 600)) { + var _res = $Stream.readAsJSON(__response.body); + var err = $object(_res); + var requestId = $string($default(err.RequestId, err.requestId)); + requestId = $string($default(requestId, err.requestid)); + var code = $string($default(err.Code, err.code)); + if ((`${code}` == 'Throttling') || (`${code}` == 'Throttling.User') || (`${code}` == 'Throttling.Api')) { + throw new Throttling{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + retryAfter = OpenApiUtil.getThrottlingTimeLeft(__response.headers), + requestId = `${requestId}`, + }; + } else if ((__response.statusCode >= 400) && (__response.statusCode < 500)) { + throw new Client{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + accessDeniedDetail = getAccessDeniedDetail(err), + requestId = `${requestId}`, + }; + } else { + throw new Server{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + requestId = `${requestId}`, + }; + } } - if (Util.equalString(bodyType, 'binary')) { + if (bodyType == 'binary') { var resp = { body = __response.body, headers = __response.headers, statusCode = __response.statusCode }; return resp; - } else if (Util.equalString(bodyType, 'byte')) { - var byt = Util.readAsBytes(__response.body); + } else if (bodyType == 'byte') { + var byt = $Stream.readAsBytes(__response.body); return { body = byt, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(bodyType, 'string')) { - var str = Util.readAsString(__response.body); + } else if (bodyType == 'string') { + var str = $Stream.readAsString(__response.body); return { body = str, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(bodyType, 'json')){ - var obj = Util.readAsJSON(__response.body); - var res = Util.assertAsMap(obj); + } else if (bodyType == 'json'){ + var obj = $Stream.readAsJSON(__response.body); + var res = $object(obj); return { body = res, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(bodyType, 'array')){ - var arr = Util.readAsJSON(__response.body); + } else if (bodyType == 'array'){ + var arr = $Stream.readAsJSON(__response.body); return { body = arr, headers = __response.headers, @@ -500,26 +512,18 @@ api doROARequest(action: string, version: string, protocol: string, method: stri }; } } runtime { - timeouted = 'retry', - key = Util.defaultString(runtime.key, @key), - cert = Util.defaultString(runtime.cert, @cert), - ca = Util.defaultString(runtime.ca, @ca), - readTimeout = Util.defaultNumber(runtime.readTimeout, @readTimeout), - connectTimeout = Util.defaultNumber(runtime.connectTimeout, @connectTimeout), - httpProxy = Util.defaultString(runtime.httpProxy, @httpProxy), - httpsProxy = Util.defaultString(runtime.httpsProxy, @httpsProxy), - noProxy = Util.defaultString(runtime.noProxy, @noProxy), - socks5Proxy = Util.defaultString(runtime.socks5Proxy, @socks5Proxy), - socks5NetWork = Util.defaultString(runtime.socks5NetWork, @socks5NetWork), - maxIdleConns = Util.defaultNumber(runtime.maxIdleConns, @maxIdleConns), - retry = { - retryable = runtime.autoretry, - maxAttempts = Util.defaultNumber(runtime.maxAttempts, 3) - }, - backoff = { - policy = Util.defaultString(runtime.backoffPolicy, 'no'), - period = Util.defaultNumber(runtime.backoffPeriod, 1) - }, + key = $string($default(runtime.key, @key)), + cert = $string($default(runtime.cert, @cert)), + ca = $string($default(runtime.ca, @ca)), + readTimeout = $number($default(runtime.readTimeout, @readTimeout)), + connectTimeout = $number($default(runtime.connectTimeout, @connectTimeout)), + httpProxy = $string($default(runtime.httpProxy, @httpProxy)), + httpsProxy = $string($default(runtime.httpsProxy, @httpsProxy)), + noProxy = $string($default(runtime.noProxy, @noProxy)), + socks5Proxy = $string($default(runtime.socks5Proxy, @socks5Proxy)), + socks5NetWork = $string($default(runtime.socks5NetWork, @socks5NetWork)), + maxIdleConns = $number($default(runtime.maxIdleConns, @maxIdleConns)), + retryOptions = @retryOptions, ignoreSSL = runtime.ignoreSSL } @@ -536,49 +540,49 @@ api doROARequest(action: string, version: string, protocol: string, method: stri * @param runtime which controls some details of call api, such as retry times * @return the response */ -api doROARequestWithForm(action: string, version: string, protocol: string, method: string, authType: string, pathname: string, bodyType: string, request: OpenApiRequest, runtime: Util.RuntimeOptions): object { - __request.protocol = Util.defaultString(@protocol, protocol); +api doROARequestWithForm(action: string, version: string, protocol: string, method: string, authType: string, pathname: string, bodyType: string, request: OpenApiUtil.OpenApiRequest, runtime: $RuntimeOptions): object { + __request.protocol = $string($default(@protocol, protocol)); __request.method = method; __request.pathname = pathname; var globalQueries : map[string]string = {}; var globalHeaders : map[string]string = {}; - if (!Util.isUnset(@globalParameters)) { + if (!$isNull(@globalParameters)) { var globalParams = @globalParameters; - if (!Util.isUnset(globalParams.queries)) { + if (!$isNull(globalParams.queries)) { globalQueries = globalParams.queries; } - if (!Util.isUnset(globalParams.headers)) { + if (!$isNull(globalParams.headers)) { globalHeaders = globalParams.headers; } } var extendsHeaders : map[string]string = {}; var extendsQueries : map[string]string = {}; - if (!Util.isUnset(runtime.extendsParameters)) { + if (!$isNull(runtime.extendsParameters)) { var extendsParameters = runtime.extendsParameters; - if (!Util.isUnset(extendsParameters.headers)) { + if (!$isNull(extendsParameters.headers)) { extendsHeaders = extendsParameters.headers; } - if (!Util.isUnset(extendsParameters.queries)) { + if (!$isNull(extendsParameters.queries)) { extendsQueries = extendsParameters.queries; } } __request.headers = { - date = Util.getDateUTCString(), + date = OpenApiUtil.getDateUTCString(), host = @endpoint, accept = 'application/json', - x-acs-signature-nonce = Util.getNonce(), + x-acs-signature-nonce = OpenApiUtil.getNonce(), x-acs-signature-method = 'HMAC-SHA1', x-acs-signature-version = '1.0', x-acs-version = version, x-acs-action = action, - user-agent = Util.getUserAgent(@userAgent), + user-agent = OpenApiUtil.getUserAgent(@userAgent), ...globalHeaders, ...extendsHeaders, ...request.headers }; - if (!Util.isUnset(request.body)) { - var m = Util.assertAsMap(request.body); + if (!$isNull(request.body)) { + var m = $object(request.body); __request.body = OpenApiUtil.toForm(m); __request.headers.content-type = 'application/x-www-form-urlencoded'; } @@ -588,23 +592,23 @@ api doROARequestWithForm(action: string, version: string, protocol: string, meth ...globalQueries, ...extendsQueries, }; - if (!Util.isUnset(request.query)) { + if (!$isNull(request.query)) { __request.query = { ...__request.query, ...request.query }; } - if (!Util.equalString(authType, 'Anonymous')) { - if (Util.isUnset(@credential)) { - throw { + if (authType != 'Anonymous') { + if ($isNull(@credential)) { + throw new Client{ code = `InvalidCredentials`, message = `Please set up the credentials correctly. If you are setting them through environment variables, please ensure that ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set correctly. See https://help.aliyun.com/zh/sdk/developer-reference/configure-the-alibaba-cloud-accesskey-environment-variable-on-linux-macos-and-windows-systems for more details.` } } var credentialModel = @credential.getCredential(); var credentialType = credentialModel.type; - if (Util.equalString(credentialType, 'bearer')) { + if (credentialType == 'bearer') { var bearerToken = credentialModel.bearerToken; __request.headers.x-acs-bearer-token = bearerToken; __request.headers.x-acs-signature-type = 'BEARERTOKEN'; @@ -612,65 +616,85 @@ api doROARequestWithForm(action: string, version: string, protocol: string, meth var accessKeyId = credentialModel.accessKeyId; var accessKeySecret = credentialModel.accessKeySecret; var securityToken = credentialModel.securityToken; - if (!Util.empty(securityToken)) { + if (!$isNull(securityToken)) { __request.headers.x-acs-accesskey-id = accessKeyId; __request.headers.x-acs-security-token = securityToken; } - var stringToSign = OpenApiUtil.getStringToSign(__request); __request.headers.authorization = `acs ${accessKeyId}:${OpenApiUtil.getROASignature(stringToSign, accessKeySecret)}`; } } } returns { - if (Util.equalNumber(__response.statusCode, 204)) { + if (__response.statusCode == 204) { return { headers = __response.headers }; } - if (Util.is4xx(__response.statusCode) || Util.is5xx(__response.statusCode)) { - var _res = Util.readAsJSON(__response.body); - var err = Util.assertAsMap(_res); - err.statusCode = __response.statusCode; - throw { - code = `${defaultAny(err.Code, err.code)}`, - message = `code: ${__response.statusCode}, ${defaultAny(err.Message, err.message)} request id: ${defaultAny(err.RequestId, err.requestId)}`, - data = err, - description = `${defaultAny(err.Description, err.description)}`, - accessDeniedDetail = defaultAny(err.AccessDeniedDetail, err.accessDeniedDetail), - }; + if ((__response.statusCode >= 400) && (__response.statusCode < 600)) { + var _res = $Stream.readAsJSON(__response.body); + var err = $object(_res); + var requestId = $string($default(err.RequestId, err.requestId)); + var code = $string($default(err.Code, err.code)); + if ((`${code}` == 'Throttling') || (`${code}` == 'Throttling.User') || (`${code}` == 'Throttling.Api')) { + throw new Throttling{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + retryAfter = OpenApiUtil.getThrottlingTimeLeft(__response.headers), + requestId = `${requestId}`, + }; + } else if ((__response.statusCode >= 400) && (__response.statusCode < 500)) { + throw new Client{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + accessDeniedDetail = getAccessDeniedDetail(err), + requestId = `${requestId}`, + }; + } else { + throw new Server{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + requestId = `${requestId}`, + }; + } } - if (Util.equalString(bodyType, 'binary')) { + if (bodyType == 'binary') { var resp = { body = __response.body, headers = __response.headers, statusCode = __response.statusCode }; return resp; - } else if (Util.equalString(bodyType, 'byte')) { - var byt = Util.readAsBytes(__response.body); + } else if (bodyType == 'byte') { + var byt = $Stream.readAsBytes(__response.body); return { body = byt, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(bodyType, 'string')) { - var str = Util.readAsString(__response.body); + } else if (bodyType == 'string') { + var str = $Stream.readAsString(__response.body); return { body = str, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(bodyType, 'json')){ - var obj = Util.readAsJSON(__response.body); - var res = Util.assertAsMap(obj); + } else if (bodyType == 'json'){ + var obj = $Stream.readAsJSON(__response.body); + var res = $object(obj); return { body = res, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(bodyType, 'array')){ - var arr = Util.readAsJSON(__response.body); + } else if (bodyType == 'array'){ + var arr = $Stream.readAsJSON(__response.body); return { body = arr, headers = __response.headers, @@ -683,53 +707,33 @@ api doROARequestWithForm(action: string, version: string, protocol: string, meth }; } } runtime { - timeouted = 'retry', - key = Util.defaultString(runtime.key, @key), - cert = Util.defaultString(runtime.cert, @cert), - ca = Util.defaultString(runtime.ca, @ca), - readTimeout = Util.defaultNumber(runtime.readTimeout, @readTimeout), - connectTimeout = Util.defaultNumber(runtime.connectTimeout, @connectTimeout), - httpProxy = Util.defaultString(runtime.httpProxy, @httpProxy), - httpsProxy = Util.defaultString(runtime.httpsProxy, @httpsProxy), - noProxy = Util.defaultString(runtime.noProxy, @noProxy), - socks5Proxy = Util.defaultString(runtime.socks5Proxy, @socks5Proxy), - socks5NetWork = Util.defaultString(runtime.socks5NetWork, @socks5NetWork), - maxIdleConns = Util.defaultNumber(runtime.maxIdleConns, @maxIdleConns), - retry = { - retryable = runtime.autoretry, - maxAttempts = Util.defaultNumber(runtime.maxAttempts, 3) - }, - backoff = { - policy = Util.defaultString(runtime.backoffPolicy, 'no'), - period = Util.defaultNumber(runtime.backoffPeriod, 1) - }, + key = $string($default(runtime.key, @key)), + cert = $string($default(runtime.cert, @cert)), + ca = $string($default(runtime.ca, @ca)), + readTimeout = $number($default(runtime.readTimeout, @readTimeout)), + connectTimeout = $number($default(runtime.connectTimeout, @connectTimeout)), + httpProxy = $string($default(runtime.httpProxy, @httpProxy)), + httpsProxy = $string($default(runtime.httpsProxy, @httpsProxy)), + noProxy = $string($default(runtime.noProxy, @noProxy)), + socks5Proxy = $string($default(runtime.socks5Proxy, @socks5Proxy)), + socks5NetWork = $string($default(runtime.socks5NetWork, @socks5NetWork)), + maxIdleConns = $number($default(runtime.maxIdleConns, @maxIdleConns)), + retryOptions = @retryOptions, ignoreSSL = runtime.ignoreSSL } -model Params = { - action: string, - version: string, - protocol: string, - pathname: string, - method: string, - authType: string, - bodyType: string, - reqBodyType: string, - style?: string -} - -async function callApi(params: Params, request: OpenApiRequest, runtime: Util.RuntimeOptions): object { - if (Util.isUnset(params)) { - throw { +async function callApi(params: OpenApiUtil.Params, request: OpenApiUtil.OpenApiRequest, runtime: $RuntimeOptions): object { + if ($isNull(params)) { + throw new Client { code = 'ParameterMissing', message = '\'params\' can not be unset' }; } - if (Util.isUnset(@signatureAlgorithm) || !Util.equalString(@signatureAlgorithm, 'v2')) { + if ($isNull(@signatureAlgorithm) || @signatureAlgorithm != 'v2') { return doRequest(params, request, runtime); - } else if (Util.equalString(params.style, 'ROA') && Util.equalString(params.reqBodyType, 'json')) { + } else if ((params.style == 'ROA') && (params.reqBodyType == 'json')) { return doROARequest(params.action, params.version, params.protocol, params.method, params.authType, params.pathname, params.bodyType, request, runtime); - } else if (Util.equalString(params.style, 'ROA')) { + } else if (params.style == 'ROA') { return doROARequestWithForm(params.action, params.version, params.protocol, params.method, params.authType, params.pathname, params.bodyType, request, runtime); } else { return doRPCRequest(params.action, params.version, params.protocol, params.method, params.authType, params.bodyType, request, runtime); @@ -747,35 +751,34 @@ async function callApi(params: Params, request: OpenApiRequest, runtime: Util.Ru * @param runtime which controls some details of call api, such as retry times * @return the response */ -api doRequest(params: Params, request: OpenApiRequest, runtime: Util.RuntimeOptions): object { - __request.protocol = Util.defaultString(@protocol, params.protocol); +api doRequest(params: OpenApiUtil.Params, request: OpenApiUtil.OpenApiRequest, runtime: $RuntimeOptions): object { + __request.protocol = $string($default(@protocol, params.protocol)); __request.method = params.method; __request.pathname = params.pathname; var globalQueries : map[string]string = {}; var globalHeaders : map[string]string = {}; - if (!Util.isUnset(@globalParameters)) { + if (!$isNull(@globalParameters)) { var globalParams = @globalParameters; - if (!Util.isUnset(globalParams.queries)) { + if (!$isNull(globalParams.queries)) { globalQueries = globalParams.queries; } - if (!Util.isUnset(globalParams.headers)) { + if (!$isNull(globalParams.headers)) { globalHeaders = globalParams.headers; } } var extendsHeaders : map[string]string = {}; var extendsQueries : map[string]string = {}; - if (!Util.isUnset(runtime.extendsParameters)) { + if (!$isNull(runtime.extendsParameters)) { var extendsParameters = runtime.extendsParameters; - if (!Util.isUnset(extendsParameters.headers)) { + if (!$isNull(extendsParameters.headers)) { extendsHeaders = extendsParameters.headers; } - if (!Util.isUnset(extendsParameters.queries)) { + if (!$isNull(extendsParameters.queries)) { extendsQueries = extendsParameters.queries; } } __request.query = { ...globalQueries, - ...extendsQueries, ...request.query, }; @@ -784,17 +787,17 @@ api doRequest(params: Params, request: OpenApiRequest, runtime: Util.RuntimeOpti host = @endpoint, x-acs-version = params.version, x-acs-action = params.action, - user-agent = getUserAgent(), + user-agent = OpenApiUtil.getUserAgent(@userAgent), x-acs-date= OpenApiUtil.getTimestamp(), - x-acs-signature-nonce = Util.getNonce(), + x-acs-signature-nonce = OpenApiUtil.getNonce(), accept = 'application/json', ...globalHeaders, ...extendsHeaders, ...request.headers, }; - if (Util.equalString(params.style, 'RPC')) { + if (params.style == 'RPC') { var headers = getRpcHeaders(); - if (!Util.isUnset(headers)) { + if (!$isNull(headers)) { __request.headers = { ...__request.headers, ...headers @@ -802,125 +805,145 @@ api doRequest(params: Params, request: OpenApiRequest, runtime: Util.RuntimeOpti } } - var signatureAlgorithm = Util.defaultString(@signatureAlgorithm, 'ACS3-HMAC-SHA256'); - var hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(Util.toBytes(''), signatureAlgorithm)); + var signatureAlgorithm = $string($default(@signatureAlgorithm, 'ACS3-HMAC-SHA256')); + var hashedRequestPayload = OpenApiUtil.hash($Bytes.from('', 'utf-8'), signatureAlgorithm); - if (!Util.isUnset(request.stream)) { - var tmp = Util.readAsBytes(request.stream); - hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(tmp, signatureAlgorithm)); + if (!$isNull(request.stream)) { + var tmp = $Stream.readAsBytes(request.stream); + hashedRequestPayload = OpenApiUtil.hash(tmp, signatureAlgorithm); __request.body = tmp; __request.headers.content-type = 'application/octet-stream'; } else { - if (!Util.isUnset(request.body)) { - if (Util.equalString(params.reqBodyType, 'byte')) { - var byteObj = Util.assertAsBytes(request.body); - hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(byteObj, signatureAlgorithm)); + if (!$isNull(request.body)) { + if (params.reqBodyType == 'byte') { + var byteObj = $bytes(request.body); + hashedRequestPayload = OpenApiUtil.hash(byteObj, signatureAlgorithm); __request.body = byteObj; - } else if (Util.equalString(params.reqBodyType, 'json')) { - var jsonObj = Util.toJSONString(request.body); - hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(Util.toBytes(jsonObj), signatureAlgorithm)); + } else if (params.reqBodyType == 'json') { + var jsonObj = $JSON.stringify(request.body); + hashedRequestPayload = OpenApiUtil.hash(jsonObj.toBytes('utf8'), signatureAlgorithm); __request.body = jsonObj; __request.headers.content-type = 'application/json; charset=utf-8'; } else { - var m = Util.assertAsMap(request.body); + var m = $object(request.body); var formObj = OpenApiUtil.toForm(m); - hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(Util.toBytes(formObj), signatureAlgorithm)); + hashedRequestPayload = OpenApiUtil.hash(formObj.toBytes('utf8'), signatureAlgorithm); __request.body = formObj; __request.headers.content-type = 'application/x-www-form-urlencoded'; } } } - __request.headers.x-acs-content-sha256 = hashedRequestPayload; + __request.headers.x-acs-content-sha256 = hashedRequestPayload.toHex(); - if (!Util.equalString(params.authType, 'Anonymous')) { - if (Util.isUnset(@credential)) { - throw { + if (params.authType != 'Anonymous') { + if ($isNull(@credential)) { + throw new Client{ code = `InvalidCredentials`, message = `Please set up the credentials correctly. If you are setting them through environment variables, please ensure that ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set correctly. See https://help.aliyun.com/zh/sdk/developer-reference/configure-the-alibaba-cloud-accesskey-environment-variable-on-linux-macos-and-windows-systems for more details.` } } var credentialModel = @credential.getCredential(); var authType = credentialModel.type; - if (Util.equalString(authType, 'bearer')) { + if (authType == 'bearer') { var bearerToken = credentialModel.bearerToken; __request.headers.x-acs-bearer-token = bearerToken; - if (Util.equalString(params.style, 'RPC')) { + if (params.style == 'RPC') { __request.query.SignatureType = 'BEARERTOKEN'; } else { __request.headers.x-acs-signature-type = 'BEARERTOKEN'; } - } else { var accessKeyId = credentialModel.accessKeyId; var accessKeySecret = credentialModel.accessKeySecret; var securityToken = credentialModel.securityToken; - if (!Util.empty(securityToken)) { + if (!$isNull(securityToken)) { __request.headers.x-acs-accesskey-id = accessKeyId; __request.headers.x-acs-security-token = securityToken; } - __request.headers.Authorization = OpenApiUtil.getAuthorization(__request, signatureAlgorithm, hashedRequestPayload, accessKeyId, accessKeySecret); + __request.headers.Authorization = OpenApiUtil.getAuthorization(__request, signatureAlgorithm, hashedRequestPayload.toHex(), accessKeyId, accessKeySecret); } } } returns { - if (Util.is4xx(__response.statusCode) || Util.is5xx(__response.statusCode)) { + if ((__response.statusCode >= 400) && (__response.statusCode < 600)) { var err : map[string]any = {}; - if (!Util.isUnset(__response.headers.content-type) && Util.equalString(__response.headers.content-type, 'text/xml;charset=utf-8')) { - var _str = Util.readAsString(__response.body); - var respMap = XML.parseXml(_str, null); - err = Util.assertAsMap(respMap.Error); + if (!$isNull(__response.headers.content-type) && __response.headers.content-type == 'text/xml;charset=utf-8') { + var _str = $Stream.readAsString(__response.body); + var respMap = $XML.parseXml(_str, null); + err = $object(respMap.Error); } else { - var _res = Util.readAsJSON(__response.body); - err = Util.assertAsMap(_res); + var _res = $Stream.readAsJSON(__response.body); + err = $object(_res); + } + var requestId = $string($default(err.RequestId, err.requestId)); + var code = $string($default(err.Code, err.code)); + if ((`${code}` == 'Throttling') || (`${code}` == 'Throttling.User') || (`${code}` == 'Throttling.Api')) { + throw new Throttling{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + retryAfter = OpenApiUtil.getThrottlingTimeLeft(__response.headers), + requestId = `${requestId}`, + }; + } else if ((__response.statusCode >= 400) && (__response.statusCode < 500)) { + throw new Client{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + accessDeniedDetail = getAccessDeniedDetail(err), + requestId = `${requestId}`, + }; + } else { + throw new Server{ + statusCode = __response.statusCode, + code = `${code}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${requestId}`, + description = `${$default(err.Description, err.description)}`, + requestId = `${requestId}`, + }; } - err.statusCode = __response.statusCode; - throw { - code = `${defaultAny(err.Code, err.code)}`, - message = `code: ${__response.statusCode}, ${defaultAny(err.Message, err.message)} request id: ${defaultAny(err.RequestId, err.requestId)}`, - data = err, - description = `${defaultAny(err.Description, err.description)}`, - accessDeniedDetail = defaultAny(err.AccessDeniedDetail, err.accessDeniedDetail), - }; } - if (Util.equalString(params.bodyType, 'binary')) { + if (params.bodyType == 'binary') { var resp = { body = __response.body, headers = __response.headers, statusCode = __response.statusCode }; return resp; - } else if (Util.equalString(params.bodyType, 'byte')) { - var byt = Util.readAsBytes(__response.body); + } else if (params.bodyType == 'byte') { + var byt = $Stream.readAsBytes(__response.body); return { body = byt, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(params.bodyType, 'string')) { - var str = Util.readAsString(__response.body); + } else if (params.bodyType == 'string') { + var str = $Stream.readAsString(__response.body); return { body = str, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(params.bodyType, 'json')){ - var obj = Util.readAsJSON(__response.body); - var res = Util.assertAsMap(obj); + } else if (params.bodyType == 'json'){ + var obj = $Stream.readAsJSON(__response.body); + var res = $object(obj); return { body = res, headers = __response.headers, statusCode = __response.statusCode }; - } else if (Util.equalString(params.bodyType, 'array')){ - var arr = Util.readAsJSON(__response.body); + } else if (params.bodyType == 'array'){ + var arr = $Stream.readAsJSON(__response.body); return { body = arr, headers = __response.headers, statusCode = __response.statusCode }; } else { - var anything = Util.readAsString(__response.body); + var anything = $Stream.readAsString(__response.body); return { body = anything, headers = __response.headers, @@ -928,26 +951,18 @@ api doRequest(params: Params, request: OpenApiRequest, runtime: Util.RuntimeOpti }; } } runtime { - timeouted = 'retry', - key = Util.defaultString(runtime.key, @key), - cert = Util.defaultString(runtime.cert, @cert), - ca = Util.defaultString(runtime.ca, @ca), - readTimeout = Util.defaultNumber(runtime.readTimeout, @readTimeout), - connectTimeout = Util.defaultNumber(runtime.connectTimeout, @connectTimeout), - httpProxy = Util.defaultString(runtime.httpProxy, @httpProxy), - httpsProxy = Util.defaultString(runtime.httpsProxy, @httpsProxy), - noProxy = Util.defaultString(runtime.noProxy, @noProxy), - socks5Proxy = Util.defaultString(runtime.socks5Proxy, @socks5Proxy), - socks5NetWork = Util.defaultString(runtime.socks5NetWork, @socks5NetWork), - maxIdleConns = Util.defaultNumber(runtime.maxIdleConns, @maxIdleConns), - retry = { - retryable = runtime.autoretry, - maxAttempts = Util.defaultNumber(runtime.maxAttempts, 3) - }, - backoff = { - policy = Util.defaultString(runtime.backoffPolicy, 'no'), - period = Util.defaultNumber(runtime.backoffPeriod, 1) - }, + key = $string($default(runtime.key, @key)), + cert = $string($default(runtime.cert, @cert)), + ca = $string($default(runtime.ca, @ca)), + readTimeout = $number($default(runtime.readTimeout, @readTimeout)), + connectTimeout = $number($default(runtime.connectTimeout, @connectTimeout)), + httpProxy = $string($default(runtime.httpProxy, @httpProxy)), + httpsProxy = $string($default(runtime.httpsProxy, @httpsProxy)), + noProxy = $string($default(runtime.noProxy, @noProxy)), + socks5Proxy = $string($default(runtime.socks5Proxy, @socks5Proxy)), + socks5NetWork = $string($default(runtime.socks5NetWork, @socks5NetWork)), + maxIdleConns = $number($default(runtime.maxIdleConns, @maxIdleConns)), + retryOptions = @retryOptions, ignoreSSL = runtime.ignoreSSL } @@ -964,28 +979,28 @@ api doRequest(params: Params, request: OpenApiRequest, runtime: Util.RuntimeOpti * @param runtime which controls some details of call api, such as retry times * @return the response */ -api execute(params: Params, request: OpenApiRequest, runtime: Util.RuntimeOptions): object { +api execute(params: OpenApiUtil.Params, request: OpenApiUtil.OpenApiRequest, runtime: $RuntimeOptions): object { // spi = new Gateway();//Gateway implements SPI,这一步在产品 SDK 中实例化 var headers = getRpcHeaders(); var globalQueries : map[string]string = {}; var globalHeaders : map[string]string = {}; - if (!Util.isUnset(@globalParameters)) { + if (!$isNull(@globalParameters)) { var globalParams = @globalParameters; - if (!Util.isUnset(globalParams.queries)) { + if (!$isNull(globalParams.queries)) { globalQueries = globalParams.queries; } - if (!Util.isUnset(globalParams.headers)) { + if (!$isNull(globalParams.headers)) { globalHeaders = globalParams.headers; } } var extendsHeaders : map[string]string = {}; var extendsQueries : map[string]string = {}; - if (!Util.isUnset(runtime.extendsParameters)) { + if (!$isNull(runtime.extendsParameters)) { var extendsParameters = runtime.extendsParameters; - if (!Util.isUnset(extendsParameters.headers)) { + if (!$isNull(extendsParameters.headers)) { extendsHeaders = extendsParameters.headers; } - if (!Util.isUnset(extendsParameters.queries)) { + if (!$isNull(extendsParameters.queries)) { extendsQueries = extendsParameters.queries; } } @@ -1008,8 +1023,8 @@ api execute(params: Params, request: OpenApiRequest, runtime: Util.RuntimeOption productId = @productId, action = params.action, version = params.version, - protocol = Util.defaultString(@protocol, params.protocol), - method = Util.defaultString(@method, params.method), + protocol = $string($default(@protocol, params.protocol)), + method = $string($default(@method, params.method)), authType = params.authType, bodyType = params.bodyType, reqBodyType = params.reqBodyType, @@ -1017,11 +1032,11 @@ api execute(params: Params, request: OpenApiRequest, runtime: Util.RuntimeOption credential = @credential, signatureVersion = @signatureVersion, signatureAlgorithm = @signatureAlgorithm, - userAgent = getUserAgent() + userAgent = OpenApiUtil.getUserAgent(@userAgent) }; var configurationContext = new SPI.InterceptorContext.configuration{ regionId = @regionId, - endpoint = Util.defaultString(request.endpointOverride, @endpoint), + endpoint = $string($default(request.endpointOverride, @endpoint)), endpointRule = @endpointRule, endpointMap = @endpointMap, endpointType = @endpointType, @@ -1065,37 +1080,169 @@ api execute(params: Params, request: OpenApiRequest, runtime: Util.RuntimeOption }; } runtime { - timeouted = 'retry', - key = Util.defaultString(runtime.key, @key), - cert = Util.defaultString(runtime.cert, @cert), - ca = Util.defaultString(runtime.ca, @ca), - readTimeout = Util.defaultNumber(runtime.readTimeout, @readTimeout), - connectTimeout = Util.defaultNumber(runtime.connectTimeout, @connectTimeout), - httpProxy = Util.defaultString(runtime.httpProxy, @httpProxy), - httpsProxy = Util.defaultString(runtime.httpsProxy, @httpsProxy), - noProxy = Util.defaultString(runtime.noProxy, @noProxy), - socks5Proxy = Util.defaultString(runtime.socks5Proxy, @socks5Proxy), - socks5NetWork = Util.defaultString(runtime.socks5NetWork, @socks5NetWork), - maxIdleConns = Util.defaultNumber(runtime.maxIdleConns, @maxIdleConns), - retry = { - retryable = runtime.autoretry, - maxAttempts = Util.defaultNumber(runtime.maxAttempts, 3) - }, - backoff = { - policy = Util.defaultString(runtime.backoffPolicy, 'no'), - period = Util.defaultNumber(runtime.backoffPeriod, 1) - }, + key = $string($default(runtime.key, @key)), + cert = $string($default(runtime.cert, @cert)), + ca = $string($default(runtime.ca, @ca)), + readTimeout = $number($default(runtime.readTimeout, @readTimeout)), + connectTimeout = $number($default(runtime.connectTimeout, @connectTimeout)), + httpProxy = $string($default(runtime.httpProxy, @httpProxy)), + httpsProxy = $string($default(runtime.httpsProxy, @httpsProxy)), + noProxy = $string($default(runtime.noProxy, @noProxy)), + socks5Proxy = $string($default(runtime.socks5Proxy, @socks5Proxy)), + socks5NetWork = $string($default(runtime.socks5NetWork, @socks5NetWork)), + maxIdleConns = $number($default(runtime.maxIdleConns, @maxIdleConns)), + retryOptions = @retryOptions, ignoreSSL = runtime.ignoreSSL, - disableHttp2 = defaultAny(@disableHttp2, false) + disableHttp2 = $boolean($default(@disableHttp2, false)) } -/** - * Get user agent - * @return user agent - */ -function getUserAgent(): string { - var userAgent = Util.getUserAgent(@userAgent); - return userAgent; +api callSSEApi(params: OpenApiUtil.Params, request: OpenApiUtil.OpenApiRequest, runtime: $RuntimeOptions): asyncIterator[SSEResponse] { + __request.protocol = $string($default(@protocol, params.protocol)); + __request.method = params.method; + __request.pathname = params.pathname; + var globalQueries : map[string]string = {}; + var globalHeaders : map[string]string = {}; + if (!$isNull(@globalParameters)) { + var globalParams = @globalParameters; + if (!$isNull(globalParams.queries)) { + globalQueries = globalParams.queries; + } + if (!$isNull(globalParams.headers)) { + globalHeaders = globalParams.headers; + } + } + var extendsHeaders : map[string]string = {}; + var extendsQueries : map[string]string = {}; + if (!$isNull(runtime.extendsParameters)) { + var extendsParameters = runtime.extendsParameters; + if (!$isNull(extendsParameters.headers)) { + extendsHeaders = extendsParameters.headers; + } + if (!$isNull(extendsParameters.queries)) { + extendsQueries = extendsParameters.queries; + } + } + __request.query = { + ...globalQueries, + ...extendsQueries, + ...request.query, + }; + + // endpoint is setted in product client + __request.headers = { + host = @endpoint, + x-acs-version = params.version, + x-acs-action = params.action, + user-agent = OpenApiUtil.getUserAgent(@userAgent), + x-acs-date= OpenApiUtil.getTimestamp(), + x-acs-signature-nonce = OpenApiUtil.getNonce(), + accept = 'application/json', + ...extendsHeaders, + ...globalHeaders, + ...request.headers, + }; + if (params.style == 'RPC') { + var headers = getRpcHeaders(); + if (!$isNull(headers)) { + __request.headers = { + ...__request.headers, + ...headers + }; + } + } + + var signatureAlgorithm = $string($default(@signatureAlgorithm, 'ACS3-HMAC-SHA256')); + var hashedRequestPayload = OpenApiUtil.hash($Bytes.from('', 'utf-8'), signatureAlgorithm); + + if (!$isNull(request.stream)) { + var tmp = $Stream.readAsBytes(request.stream); + hashedRequestPayload = OpenApiUtil.hash(tmp, signatureAlgorithm); + __request.body = tmp; + __request.headers.content-type = 'application/octet-stream'; + } else { + if (!$isNull(request.body)) { + if (params.reqBodyType == 'byte') { + var byteObj = $bytes(request.body); + hashedRequestPayload = OpenApiUtil.hash(byteObj, signatureAlgorithm); + __request.body = byteObj; + } else if (params.reqBodyType == 'json') { + var jsonObj = $JSON.stringify(request.body); + hashedRequestPayload = OpenApiUtil.hash(jsonObj.toBytes('utf8'), signatureAlgorithm); + __request.body = jsonObj; + __request.headers.content-type = 'application/json; charset=utf-8'; + } else { + var m = $object(request.body); + var formObj = OpenApiUtil.toForm(m); + hashedRequestPayload = OpenApiUtil.hash(formObj.toBytes('utf8'), signatureAlgorithm); + __request.body = formObj; + __request.headers.content-type = 'application/x-www-form-urlencoded'; + } + } + } + + __request.headers.x-acs-content-sha256 = hashedRequestPayload.toHex(); + + if (params.authType != 'Anonymous') { + var credentialModel = @credential.getCredential(); + var authType = credentialModel.type; + if (authType == 'bearer') { + var bearerToken = credentialModel.bearerToken; + __request.headers.x-acs-bearer-token = bearerToken; + } else { + var accessKeyId = credentialModel.accessKeyId; + var accessKeySecret = credentialModel.accessKeySecret; + var securityToken = credentialModel.securityToken; + + if (!$isNull(securityToken)) { + __request.headers.x-acs-accesskey-id = accessKeyId; + __request.headers.x-acs-security-token = securityToken; + } + __request.headers.Authorization = OpenApiUtil.getAuthorization(__request, signatureAlgorithm, hashedRequestPayload.toHex(), accessKeyId, accessKeySecret); + } + } +} returns { + if ((__response.statusCode >= 400) && (__response.statusCode < 600)) { + var err : map[string]any = {}; + if (!$isNull(__response.headers.content-type) && __response.headers.content-type == 'text/xml;charset=utf-8') { + var _str = $Stream.readAsString(__response.body); + var respMap = $XML.parseXml(_str, null); + err = $object(respMap.Error); + } else { + var _res = $Stream.readAsJSON(__response.body); + err = $object(_res); + } + err.statusCode = __response.statusCode; + throw { + code = `${$default(err.Code, err.code)}`, + message = `code: ${__response.statusCode}, ${$default(err.Message, err.message)} request id: ${$default(err.RequestId, err.requestId)}`, + data = err, + description = `${$default(err.Description, err.description)}`, + accessDeniedDetail = $default(err.AccessDeniedDetail, err.accessDeniedDetail), + }; + } + var events = $Stream.readAsSSE(__response.body); + for(var event : events) { + yield new SSEResponse{ + statusCode = __response.statusCode, + headers = __response.headers, + event = event, + }; + } + return null; +} runtime { + key = $string($default(runtime.key, @key)), + cert = $string($default(runtime.cert, @cert)), + ca = $string($default(runtime.ca, @ca)), + readTimeout = $number($default(runtime.readTimeout, @readTimeout)), + connectTimeout = $number($default(runtime.connectTimeout, @connectTimeout)), + httpProxy = $string($default(runtime.httpProxy, @httpProxy)), + httpsProxy = $string($default(runtime.httpsProxy, @httpsProxy)), + noProxy = $string($default(runtime.noProxy, @noProxy)), + socks5Proxy = $string($default(runtime.socks5Proxy, @socks5Proxy)), + socks5NetWork = $string($default(runtime.socks5NetWork, @socks5NetWork)), + maxIdleConns = $number($default(runtime.maxIdleConns, @maxIdleConns)), + retryOptions = @retryOptions, + ignoreSSL = runtime.ignoreSSL } /** @@ -1103,7 +1250,7 @@ function getUserAgent(): string { * @return accesskey id */ async function getAccessKeyId(): string { - if (Util.isUnset(@credential)) { + if ($isNull(@credential)) { return ''; } var accessKeyId = @credential.getAccessKeyId(); @@ -1115,7 +1262,7 @@ async function getAccessKeyId(): string { * @return accesskey secret */ async function getAccessKeySecret(): string { - if (Util.isUnset(@credential)) { + if ($isNull(@credential)) { return ''; } var secret = @credential.getAccessKeySecret(); @@ -1127,7 +1274,7 @@ async function getAccessKeySecret(): string { * @return security token */ async function getSecurityToken(): string { - if (Util.isUnset(@credential)) { + if ($isNull(@credential)) { return ''; } var token = @credential.getSecurityToken(); @@ -1139,7 +1286,7 @@ async function getSecurityToken(): string { * @return bearer token */ async function getBearerToken(): string { - if (Util.isUnset(@credential)) { + if ($isNull(@credential)) { return ''; } var token = @credential.getBearerToken(); @@ -1151,33 +1298,20 @@ async function getBearerToken(): string { * @return credential type e.g. access_key */ async function getType(): string { - if (Util.isUnset(@credential)) { + if ($isNull(@credential)) { return ''; } var authType = @credential.getType(); return authType; } -/** - * If inputValue is not null, return it or return defaultValue - * @param inputValue users input value - * @param defaultValue default value - * @return the final result - */ -static function defaultAny(inputValue: any, defaultValue: any): any { - if (Util.isUnset(inputValue)) { - return defaultValue; - } - return inputValue; -} - /** * If the endpointRule and config.endpoint are empty, throw error * @param config config contains the necessary information to create a client */ -function checkConfig(config: Config)throws : void { - if (Util.empty(@endpointRule) && Util.empty(config.endpoint)) { - throw { +function checkConfig(config: OpenApiUtil.Config)throws : void { + if ($isNull(@endpointRule) && $isNull(config.endpoint)) { + throw new Client { code = 'ParameterMissing', message = '\'config.endpoint\' can not be empty' }; @@ -1208,3 +1342,15 @@ function getRpcHeaders() throws : map[string] string { @headers = null; return headers; } + +function getAccessDeniedDetail(err: map[string] any): map[string] any { + var accessDeniedDetail : map[string] any = null; + if (!$isNull(err.AccessDeniedDetail)) { + var detail1 = $object(err.AccessDeniedDetail); + accessDeniedDetail = detail1; + } else if (!$isNull(err.accessDeniedDetail)) { + var detail2 = $object(err.accessDeniedDetail); + accessDeniedDetail = detail2; + } + return accessDeniedDetail; +} diff --git a/node_modules/.package_versions.json b/node_modules/.package_versions.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/node_modules/.package_versions.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/ts/package.json b/ts/package.json index 38808a6..1b1b208 100644 --- a/ts/package.json +++ b/ts/package.json @@ -1,11 +1,13 @@ { - "name": "@alicloud/openapi-client", - "version": "0.4.12", + "name": "@alicloud/openapi-core", + "version": "1.0.0", "description": "", "main": "dist/client.js", "scripts": { "test": "mocha -r ts-node/register -r source-map-support/register test/**/*.spec.ts --timeout=10000", "test-cov": "nyc -e .ts -r=html -r=text -r=lcov npm run test", + "select-version": "node scripts/ts_version.js", + "postinstall": "npm run select-version", "build": "tsc", "prepublishOnly": "tsc" }, @@ -14,24 +16,20 @@ "devDependencies": { "@types/mocha": "^5.2.7", "mocha": "^6.2.0", - "@types/node": "^12.12.26", - "nyc": "^15.0.0", + "@types/node": "^18.0.0", + "nyc": "^14.1.1", "source-map-support": "^0.5.16", - "ts-node": "^8.6.2", - "typescript": "^3.7.5", - "@alicloud/gateway-pop": "0.0.6" + "ts-node": "^10.0.0", + "typescript": "^5.6.0" }, "dependencies": { - "@alicloud/tea-typescript": "^1.7.1", - "@alicloud/tea-util": "^1.4.9", - "@alicloud/credentials": "^2.3.1", - "@alicloud/openapi-util": "^0.3.2", + "@alicloud/gateway-pop": "0.0.6", "@alicloud/gateway-spi": "^0.0.8", - "@alicloud/tea-xml": "0.0.3" + "@darabonba/typescript": "^1.0.2" }, "files": [ "dist", "src" ], "repository": "git@github.com:aliyun/darabonba-openapi.git" -} \ No newline at end of file +} diff --git a/ts/scripts/ts_version.js b/ts/scripts/ts_version.js new file mode 100644 index 0000000..5edc3ca --- /dev/null +++ b/ts/scripts/ts_version.js @@ -0,0 +1,33 @@ +const { execSync } = require('child_process'); + +const nodeVersion = process.versions.node; +console.log(`Running with Node.js version: ${nodeVersion}`); + +// 定义不同 Node 版本对应的 TypeScript 和 @types/node 版本 +const depsMap = { + '10': { + typescript: 'typescript@^3.9.7', + nodeTypes: '@types/node@^12.0.0' + }, + '12': { + typescript: 'typescript@^4.1.3', + nodeTypes: '@types/node@^12.0.0' + } +}; + +// 获取当前 Node major 版本 +const majorVersion = nodeVersion.split('.')[0]; + +// 选择合适的版本 +const { typescript, nodeTypes } = depsMap[majorVersion] || {}; +if(!typescript) { + process.exit(0); +} +console.log(`Installing ${typescript} and ${nodeTypes}...`); + +try { + execSync(`npm install --no-save ${typescript} ${nodeTypes}`, { stdio: 'inherit' }); +} catch (error) { + console.error('Error installing specific TypeScript and @types/node version:', error); + process.exit(1); +} \ No newline at end of file diff --git a/ts/src/client.ts b/ts/src/client.ts index b3b2b7f..0207f8b 100644 --- a/ts/src/client.ts +++ b/ts/src/client.ts @@ -1,220 +1,101 @@ // This file is auto-generated, don't edit it /** + * @remarks * This is for OpenApi SDK */ -import Util, * as $Util from '@alicloud/tea-util'; +import OpenApiUtil, * as $OpenApiUtil from './utils'; import Credential, * as $Credential from '@alicloud/credentials'; -import OpenApiUtil from '@alicloud/openapi-util'; import SPI, * as $SPI from '@alicloud/gateway-spi'; -import XML from '@alicloud/tea-xml'; -import { Readable } from 'stream'; -import * as $tea from '@alicloud/tea-typescript'; +import * as $dara from '@darabonba/typescript'; -export class GlobalParameters extends $tea.Model { - headers?: { [key: string]: string }; - queries?: { [key: string]: string }; +export * as $OpenApiUtil from './utils'; +export { default as OpenApiUtil } from './utils'; + +export class SSEResponse extends $dara.Model { + headers: { [key: string]: string }; + /** + * @remarks + * HTTP Status Code + */ + statusCode: number; + event: $dara.SSEEvent; static names(): { [key: string]: string } { return { headers: 'headers', - queries: 'queries', + statusCode: 'statusCode', + event: 'event', }; } static types(): { [key: string]: any } { return { headers: { 'type': 'map', 'keyType': 'string', 'valueType': 'string' }, - queries: { 'type': 'map', 'keyType': 'string', 'valueType': 'string' }, + statusCode: 'number', + event: $dara.SSEEvent, }; } + validate() { + if(this.headers) { + $dara.Model.validateMap(this.headers); + } + $dara.Model.validateRequired("headers", this.headers); + $dara.Model.validateRequired("statusCode", this.statusCode); + $dara.Model.validateRequired("event", this.event); + super.validate(); + } + constructor(map?: { [key: string]: any }) { super(map); } } -/** - * Model for initing client - */ -export class Config extends $tea.Model { - accessKeyId?: string; - accessKeySecret?: string; - securityToken?: string; - bearerToken?: string; - protocol?: string; - method?: string; - regionId?: string; - readTimeout?: number; - connectTimeout?: number; - httpProxy?: string; - httpsProxy?: string; - credential?: Credential; - endpoint?: string; - noProxy?: string; - maxIdleConns?: number; - network?: string; - userAgent?: string; - suffix?: string; - socks5Proxy?: string; - socks5NetWork?: string; - endpointType?: string; - openPlatformEndpoint?: string; - type?: string; - signatureVersion?: string; - signatureAlgorithm?: string; - globalParameters?: GlobalParameters; - key?: string; - cert?: string; - ca?: string; - disableHttp2?: boolean; - static names(): { [key: string]: string } { - return { - accessKeyId: 'accessKeyId', - accessKeySecret: 'accessKeySecret', - securityToken: 'securityToken', - bearerToken: 'bearerToken', - protocol: 'protocol', - method: 'method', - regionId: 'regionId', - readTimeout: 'readTimeout', - connectTimeout: 'connectTimeout', - httpProxy: 'httpProxy', - httpsProxy: 'httpsProxy', - credential: 'credential', - endpoint: 'endpoint', - noProxy: 'noProxy', - maxIdleConns: 'maxIdleConns', - network: 'network', - userAgent: 'userAgent', - suffix: 'suffix', - socks5Proxy: 'socks5Proxy', - socks5NetWork: 'socks5NetWork', - endpointType: 'endpointType', - openPlatformEndpoint: 'openPlatformEndpoint', - type: 'type', - signatureVersion: 'signatureVersion', - signatureAlgorithm: 'signatureAlgorithm', - globalParameters: 'globalParameters', - key: 'key', - cert: 'cert', - ca: 'ca', - disableHttp2: 'disableHttp2', - }; - } - - static types(): { [key: string]: any } { - return { - accessKeyId: 'string', - accessKeySecret: 'string', - securityToken: 'string', - bearerToken: 'string', - protocol: 'string', - method: 'string', - regionId: 'string', - readTimeout: 'number', - connectTimeout: 'number', - httpProxy: 'string', - httpsProxy: 'string', - credential: Credential, - endpoint: 'string', - noProxy: 'string', - maxIdleConns: 'number', - network: 'string', - userAgent: 'string', - suffix: 'string', - socks5Proxy: 'string', - socks5NetWork: 'string', - endpointType: 'string', - openPlatformEndpoint: 'string', - type: 'string', - signatureVersion: 'string', - signatureAlgorithm: 'string', - globalParameters: GlobalParameters, - key: 'string', - cert: 'string', - ca: 'string', - disableHttp2: 'boolean', - }; - } +export class AlibabaCloudError extends $dara.BaseError { + statusCode?: number; + code: string; + message: string; + description?: string; + requestId?: string; constructor(map?: { [key: string]: any }) { super(map); + this.name = "AlibabaCloudError"; + Object.setPrototypeOf(this, AlibabaCloudError.prototype); + this.statusCode = map.statusCode; + this.code = map.code; + this.description = map.description; + this.requestId = map.requestId; } } -export class OpenApiRequest extends $tea.Model { - headers?: { [key: string]: string }; - query?: { [key: string]: string }; - body?: any; - stream?: Readable; - hostMap?: { [key: string]: string }; - endpointOverride?: string; - static names(): { [key: string]: string } { - return { - headers: 'headers', - query: 'query', - body: 'body', - stream: 'stream', - hostMap: 'hostMap', - endpointOverride: 'endpointOverride', - }; - } - - static types(): { [key: string]: any } { - return { - headers: { 'type': 'map', 'keyType': 'string', 'valueType': 'string' }, - query: { 'type': 'map', 'keyType': 'string', 'valueType': 'string' }, - body: 'any', - stream: 'Readable', - hostMap: { 'type': 'map', 'keyType': 'string', 'valueType': 'string' }, - endpointOverride: 'string', - }; - } +export class ClientError extends AlibabaCloudError { + accessDeniedDetail?: { [key: string]: any }; constructor(map?: { [key: string]: any }) { super(map); + this.name = "ClientError"; + Object.setPrototypeOf(this, ClientError.prototype); + this.accessDeniedDetail = map.accessDeniedDetail; } } -export class Params extends $tea.Model { - action: string; - version: string; - protocol: string; - pathname: string; - method: string; - authType: string; - bodyType: string; - reqBodyType: string; - style?: string; - static names(): { [key: string]: string } { - return { - action: 'action', - version: 'version', - protocol: 'protocol', - pathname: 'pathname', - method: 'method', - authType: 'authType', - bodyType: 'bodyType', - reqBodyType: 'reqBodyType', - style: 'style', - }; - } +export class ServerError extends AlibabaCloudError { - static types(): { [key: string]: any } { - return { - action: 'string', - version: 'string', - protocol: 'string', - pathname: 'string', - method: 'string', - authType: 'string', - bodyType: 'string', - reqBodyType: 'string', - style: 'string', - }; + constructor(map?: { [key: string]: any }) { + super(map); + this.name = "ServerError"; + Object.setPrototypeOf(this, ServerError.prototype); } +} + +export class ThrottlingError extends AlibabaCloudError { + retryAfter?: number; constructor(map?: { [key: string]: any }) { super(map); + this.name = "ThrottlingError"; + Object.setPrototypeOf(this, ThrottlingError.prototype); + this.retryAfter = map.retryAfter; } } @@ -245,26 +126,29 @@ export default class Client { _signatureAlgorithm: string; _headers: {[key: string ]: string}; _spi: SPI; - _globalParameters: GlobalParameters; + _globalParameters: $OpenApiUtil.GlobalParameters; _key: string; _cert: string; _ca: string; _disableHttp2: boolean; + _retryOptions: $dara.RetryOptions; /** + * @remarks * Init client with Config - * @param config config contains the necessary information to create a client + * + * @param config - config contains the necessary information to create a client */ - constructor(config: Config) { - if (Util.isUnset(config)) { - throw $tea.newError({ + constructor(config: $OpenApiUtil.Config) { + if ($dara.isNull(config)) { + throw new ClientError({ code: "ParameterMissing", message: "'config' can not be unset", }); } - if (!Util.empty(config.accessKeyId) && !Util.empty(config.accessKeySecret)) { - if (!Util.empty(config.securityToken)) { + if (!$dara.isNull(config.accessKeyId) && !$dara.isNull(config.accessKeySecret)) { + if (!$dara.isNull(config.securityToken)) { config.type = "sts"; } else { config.type = "access_key"; @@ -277,13 +161,13 @@ export default class Client { }); credentialConfig.securityToken = config.securityToken; this._credential = new Credential(credentialConfig); - } else if (!Util.empty(config.bearerToken)) { + } else if (!$dara.isNull(config.bearerToken)) { let cc = new $Credential.Config({ type: "bearer", bearerToken: config.bearerToken, }); this._credential = new Credential(cc); - } else if (!Util.isUnset(config.credential)) { + } else if (!$dara.isNull(config.credential)) { this._credential = config.credential; } @@ -310,71 +194,68 @@ export default class Client { this._cert = config.cert; this._ca = config.ca; this._disableHttp2 = config.disableHttp2; + this._retryOptions = config.retryOptions; } /** + * @remarks * Encapsulate the request and invoke the network - * @param action api name - * @param version product version - * @param protocol http or https - * @param method e.g. GET - * @param authType authorization type e.g. AK - * @param bodyType response body type e.g. String - * @param request object of OpenApiRequest - * @param runtime which controls some details of call api, such as retry times - * @return the response + * + * @param action - api name + * @param version - product version + * @param protocol - http or https + * @param method - e.g. GET + * @param authType - authorization type e.g. AK + * @param bodyType - response body type e.g. String + * @param request - object of OpenApiRequest + * @param runtime - which controls some details of call api, such as retry times + * @returns the response */ - async doRPCRequest(action: string, version: string, protocol: string, method: string, authType: string, bodyType: string, request: OpenApiRequest, runtime: $Util.RuntimeOptions): Promise<{[key: string]: any}> { + async doRPCRequest(action: string, version: string, protocol: string, method: string, authType: string, bodyType: string, request: $OpenApiUtil.OpenApiRequest, runtime: $dara.RuntimeOptions): Promise<{[key: string]: any}> { let _runtime: { [key: string]: any } = { - timeouted: "retry", - key: Util.defaultString(runtime.key, this._key), - cert: Util.defaultString(runtime.cert, this._cert), - ca: Util.defaultString(runtime.ca, this._ca), - readTimeout: Util.defaultNumber(runtime.readTimeout, this._readTimeout), - connectTimeout: Util.defaultNumber(runtime.connectTimeout, this._connectTimeout), - httpProxy: Util.defaultString(runtime.httpProxy, this._httpProxy), - httpsProxy: Util.defaultString(runtime.httpsProxy, this._httpsProxy), - noProxy: Util.defaultString(runtime.noProxy, this._noProxy), - socks5Proxy: Util.defaultString(runtime.socks5Proxy, this._socks5Proxy), - socks5NetWork: Util.defaultString(runtime.socks5NetWork, this._socks5NetWork), - maxIdleConns: Util.defaultNumber(runtime.maxIdleConns, this._maxIdleConns), - retry: { - retryable: runtime.autoretry, - maxAttempts: Util.defaultNumber(runtime.maxAttempts, 3), - }, - backoff: { - policy: Util.defaultString(runtime.backoffPolicy, "no"), - period: Util.defaultNumber(runtime.backoffPeriod, 1), - }, + key: runtime.key || this._key, + cert: runtime.cert || this._cert, + ca: runtime.ca || this._ca, + readTimeout: runtime.readTimeout || this._readTimeout, + connectTimeout: runtime.connectTimeout || this._connectTimeout, + httpProxy: runtime.httpProxy || this._httpProxy, + httpsProxy: runtime.httpsProxy || this._httpsProxy, + noProxy: runtime.noProxy || this._noProxy, + socks5Proxy: runtime.socks5Proxy || this._socks5Proxy, + socks5NetWork: runtime.socks5NetWork || this._socks5NetWork, + maxIdleConns: runtime.maxIdleConns || this._maxIdleConns, + retryOptions: this._retryOptions, ignoreSSL: runtime.ignoreSSL, } - let _lastRequest = null; - let _now = Date.now(); - let _retryTimes = 0; - while ($tea.allowRetry(_runtime['retry'], _retryTimes, _now)) { - if (_retryTimes > 0) { - let _backoffTime = $tea.getBackoffTime(_runtime['backoff'], _retryTimes); + let _retriesAttempted = 0; + let _lastRequest = null, _lastResponse = null; + let _context = new $dara.RetryPolicyContext({ + retriesAttempted: _retriesAttempted, + }); + while ($dara.shouldRetry(_runtime['retryOptions'], _context)) { + if (_retriesAttempted > 0) { + let _backoffTime = $dara.getBackoffDelay(_runtime['retryOptions'], _context); if (_backoffTime > 0) { - await $tea.sleep(_backoffTime); + await $dara.sleep(_backoffTime); } } - _retryTimes = _retryTimes + 1; + _retriesAttempted = _retriesAttempted + 1; try { - let request_ = new $tea.Request(); - request_.protocol = Util.defaultString(this._protocol, protocol); + let request_ = new $dara.Request(); + request_.protocol = this._protocol || protocol; request_.method = method; request_.pathname = "/"; let globalQueries : {[key: string ]: string} = { }; let globalHeaders : {[key: string ]: string} = { }; - if (!Util.isUnset(this._globalParameters)) { + if (!$dara.isNull(this._globalParameters)) { let globalParams = this._globalParameters; - if (!Util.isUnset(globalParams.queries)) { + if (!$dara.isNull(globalParams.queries)) { globalQueries = globalParams.queries; } - if (!Util.isUnset(globalParams.headers)) { + if (!$dara.isNull(globalParams.headers)) { globalHeaders = globalParams.headers; } @@ -382,13 +263,13 @@ export default class Client { let extendsHeaders : {[key: string ]: string} = { }; let extendsQueries : {[key: string ]: string} = { }; - if (!Util.isUnset(runtime.extendsParameters)) { + if (!$dara.isNull(runtime.extendsParameters)) { let extendsParameters = runtime.extendsParameters; - if (!Util.isUnset(extendsParameters.headers)) { + if (!$dara.isNull(extendsParameters.headers)) { extendsHeaders = extendsParameters.headers; } - if (!Util.isUnset(extendsParameters.queries)) { + if (!$dara.isNull(extendsParameters.queries)) { extendsQueries = extendsParameters.queries; } @@ -399,19 +280,19 @@ export default class Client { Format: "json", Version: version, Timestamp: OpenApiUtil.getTimestamp(), - SignatureNonce: Util.getNonce(), + SignatureNonce: OpenApiUtil.getNonce(), ...globalQueries, ...extendsQueries, ...request.query, }; let headers = this.getRpcHeaders(); - if (Util.isUnset(headers)) { + if ($dara.isNull(headers)) { // endpoint is setted in product client request_.headers = { host: this._endpoint, 'x-acs-version': version, 'x-acs-action': action, - 'user-agent': this.getUserAgent(), + 'user-agent': OpenApiUtil.getUserAgent(this._userAgent), ...globalHeaders, ...extendsHeaders, }; @@ -420,23 +301,23 @@ export default class Client { host: this._endpoint, 'x-acs-version': version, 'x-acs-action': action, - 'user-agent': this.getUserAgent(), + 'user-agent': OpenApiUtil.getUserAgent(this._userAgent), ...globalHeaders, ...extendsHeaders, ...headers, }; } - if (!Util.isUnset(request.body)) { - let m = Util.assertAsMap(request.body); - let tmp = Util.anyifyMapValue(OpenApiUtil.query(m)); - request_.body = new $tea.BytesReadable(Util.toFormString(tmp)); + if (!$dara.isNull(request.body)) { + let m = request.body; + let tmp = OpenApiUtil.query(m); + request_.body = new $dara.BytesReadable($dara.Form.toFormString(tmp)); request_.headers["content-type"] = "application/x-www-form-urlencoded"; } - if (!Util.equalString(authType, "Anonymous")) { - if (Util.isUnset(this._credential)) { - throw $tea.newError({ + if (authType != "Anonymous") { + if ($dara.isNull(this._credential)) { + throw new ClientError({ code: `InvalidCredentials`, message: `Please set up the credentials correctly. If you are setting them through environment variables, please ensure that ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set correctly. See https://help.aliyun.com/zh/sdk/developer-reference/configure-the-alibaba-cloud-accesskey-environment-variable-on-linux-macos-and-windows-systems for more details.`, }); @@ -444,7 +325,7 @@ export default class Client { let credentialModel = await this._credential.getCredential(); let credentialType = credentialModel.type; - if (Util.equalString(credentialType, "bearer")) { + if (credentialType == "bearer") { let bearerToken = credentialModel.bearerToken; request_.query["BearerToken"] = bearerToken; request_.query["SignatureType"] = "BEARERTOKEN"; @@ -452,7 +333,7 @@ export default class Client { let accessKeyId = credentialModel.accessKeyId; let accessKeySecret = credentialModel.accessKeySecret; let securityToken = credentialModel.securityToken; - if (!Util.empty(securityToken)) { + if (!$dara.isNull(securityToken)) { request_.query["SecurityToken"] = securityToken; } @@ -460,8 +341,8 @@ export default class Client { request_.query["SignatureVersion"] = "1.0"; request_.query["AccessKeyId"] = accessKeyId; let t : {[key: string ]: any} = null; - if (!Util.isUnset(request.body)) { - t = Util.assertAsMap(request.body); + if (!$dara.isNull(request.body)) { + t = request.body; } let signedParam = { @@ -473,54 +354,76 @@ export default class Client { } + let response_ = await $dara.doAction(request_, _runtime); _lastRequest = request_; - let response_ = await $tea.doAction(request_, _runtime); + _lastResponse = response_; + + if ((response_.statusCode >= 400) && (response_.statusCode < 600)) { + let _res = await $dara.Stream.readAsJSON(response_.body); + let err = _res; + let requestId = err["RequestId"] || err["requestId"]; + let code = err["Code"] || err["code"]; + if ((`${code}` == "Throttling") || (`${code}` == "Throttling.User") || (`${code}` == "Throttling.Api")) { + throw new ThrottlingError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + retryAfter: OpenApiUtil.getThrottlingTimeLeft(response_.headers), + requestId: `${requestId}`, + }); + } else if ((response_.statusCode >= 400) && (response_.statusCode < 500)) { + throw new ClientError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + accessDeniedDetail: this.getAccessDeniedDetail(err), + requestId: `${requestId}`, + }); + } else { + throw new ServerError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + requestId: `${requestId}`, + }); + } - if (Util.is4xx(response_.statusCode) || Util.is5xx(response_.statusCode)) { - let _res = await Util.readAsJSON(response_.body); - let err = Util.assertAsMap(_res); - let requestId = Client.defaultAny(err["RequestId"], err["requestId"]); - err["statusCode"] = response_.statusCode; - throw $tea.newError({ - code: `${Client.defaultAny(err["Code"], err["code"])}`, - message: `code: ${response_.statusCode}, ${Client.defaultAny(err["Message"], err["message"])} request id: ${requestId}`, - data: err, - description: `${Client.defaultAny(err["Description"], err["description"])}`, - accessDeniedDetail: Client.defaultAny(err["AccessDeniedDetail"], err["accessDeniedDetail"]), - }); } - if (Util.equalString(bodyType, "binary")) { + if (bodyType == "binary") { let resp = { body: response_.body, headers: response_.headers, statusCode: response_.statusCode, }; return resp; - } else if (Util.equalString(bodyType, "byte")) { - let byt = await Util.readAsBytes(response_.body); + } else if (bodyType == "byte") { + let byt = await $dara.Stream.readAsBytes(response_.body); return { body: byt, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(bodyType, "string")) { - let str = await Util.readAsString(response_.body); + } else if (bodyType == "string") { + let str = await $dara.Stream.readAsString(response_.body); return { body: str, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(bodyType, "json")) { - let obj = await Util.readAsJSON(response_.body); - let res = Util.assertAsMap(obj); + } else if (bodyType == "json") { + let obj = await $dara.Stream.readAsJSON(response_.body); + let res = obj; return { body: res, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(bodyType, "array")) { - let arr = await Util.readAsJSON(response_.body); + } else if (bodyType == "array") { + let arr = await $dara.Stream.readAsJSON(response_.body); return { body: arr, headers: response_.headers, @@ -534,80 +437,79 @@ export default class Client { } } catch (ex) { - if ($tea.isRetryable(ex)) { - continue; - } - throw ex; + _context = new $dara.RetryPolicyContext({ + retriesAttempted : _retriesAttempted, + httpRequest : _lastRequest, + httpResponse : _lastResponse, + exception : ex, + }); + continue; } } - throw $tea.newUnretryableError(_lastRequest); + throw $dara.newUnretryableError(_context); } /** + * @remarks * Encapsulate the request and invoke the network - * @param action api name - * @param version product version - * @param protocol http or https - * @param method e.g. GET - * @param authType authorization type e.g. AK - * @param pathname pathname of every api - * @param bodyType response body type e.g. String - * @param request object of OpenApiRequest - * @param runtime which controls some details of call api, such as retry times - * @return the response + * + * @param action - api name + * @param version - product version + * @param protocol - http or https + * @param method - e.g. GET + * @param authType - authorization type e.g. AK + * @param pathname - pathname of every api + * @param bodyType - response body type e.g. String + * @param request - object of OpenApiRequest + * @param runtime - which controls some details of call api, such as retry times + * @returns the response */ - async doROARequest(action: string, version: string, protocol: string, method: string, authType: string, pathname: string, bodyType: string, request: OpenApiRequest, runtime: $Util.RuntimeOptions): Promise<{[key: string]: any}> { + async doROARequest(action: string, version: string, protocol: string, method: string, authType: string, pathname: string, bodyType: string, request: $OpenApiUtil.OpenApiRequest, runtime: $dara.RuntimeOptions): Promise<{[key: string]: any}> { let _runtime: { [key: string]: any } = { - timeouted: "retry", - key: Util.defaultString(runtime.key, this._key), - cert: Util.defaultString(runtime.cert, this._cert), - ca: Util.defaultString(runtime.ca, this._ca), - readTimeout: Util.defaultNumber(runtime.readTimeout, this._readTimeout), - connectTimeout: Util.defaultNumber(runtime.connectTimeout, this._connectTimeout), - httpProxy: Util.defaultString(runtime.httpProxy, this._httpProxy), - httpsProxy: Util.defaultString(runtime.httpsProxy, this._httpsProxy), - noProxy: Util.defaultString(runtime.noProxy, this._noProxy), - socks5Proxy: Util.defaultString(runtime.socks5Proxy, this._socks5Proxy), - socks5NetWork: Util.defaultString(runtime.socks5NetWork, this._socks5NetWork), - maxIdleConns: Util.defaultNumber(runtime.maxIdleConns, this._maxIdleConns), - retry: { - retryable: runtime.autoretry, - maxAttempts: Util.defaultNumber(runtime.maxAttempts, 3), - }, - backoff: { - policy: Util.defaultString(runtime.backoffPolicy, "no"), - period: Util.defaultNumber(runtime.backoffPeriod, 1), - }, + key: runtime.key || this._key, + cert: runtime.cert || this._cert, + ca: runtime.ca || this._ca, + readTimeout: runtime.readTimeout || this._readTimeout, + connectTimeout: runtime.connectTimeout || this._connectTimeout, + httpProxy: runtime.httpProxy || this._httpProxy, + httpsProxy: runtime.httpsProxy || this._httpsProxy, + noProxy: runtime.noProxy || this._noProxy, + socks5Proxy: runtime.socks5Proxy || this._socks5Proxy, + socks5NetWork: runtime.socks5NetWork || this._socks5NetWork, + maxIdleConns: runtime.maxIdleConns || this._maxIdleConns, + retryOptions: this._retryOptions, ignoreSSL: runtime.ignoreSSL, } - let _lastRequest = null; - let _now = Date.now(); - let _retryTimes = 0; - while ($tea.allowRetry(_runtime['retry'], _retryTimes, _now)) { - if (_retryTimes > 0) { - let _backoffTime = $tea.getBackoffTime(_runtime['backoff'], _retryTimes); + let _retriesAttempted = 0; + let _lastRequest = null, _lastResponse = null; + let _context = new $dara.RetryPolicyContext({ + retriesAttempted: _retriesAttempted, + }); + while ($dara.shouldRetry(_runtime['retryOptions'], _context)) { + if (_retriesAttempted > 0) { + let _backoffTime = $dara.getBackoffDelay(_runtime['retryOptions'], _context); if (_backoffTime > 0) { - await $tea.sleep(_backoffTime); + await $dara.sleep(_backoffTime); } } - _retryTimes = _retryTimes + 1; + _retriesAttempted = _retriesAttempted + 1; try { - let request_ = new $tea.Request(); - request_.protocol = Util.defaultString(this._protocol, protocol); + let request_ = new $dara.Request(); + request_.protocol = this._protocol || protocol; request_.method = method; request_.pathname = pathname; let globalQueries : {[key: string ]: string} = { }; let globalHeaders : {[key: string ]: string} = { }; - if (!Util.isUnset(this._globalParameters)) { + if (!$dara.isNull(this._globalParameters)) { let globalParams = this._globalParameters; - if (!Util.isUnset(globalParams.queries)) { + if (!$dara.isNull(globalParams.queries)) { globalQueries = globalParams.queries; } - if (!Util.isUnset(globalParams.headers)) { + if (!$dara.isNull(globalParams.headers)) { globalHeaders = globalParams.headers; } @@ -615,34 +517,34 @@ export default class Client { let extendsHeaders : {[key: string ]: string} = { }; let extendsQueries : {[key: string ]: string} = { }; - if (!Util.isUnset(runtime.extendsParameters)) { + if (!$dara.isNull(runtime.extendsParameters)) { let extendsParameters = runtime.extendsParameters; - if (!Util.isUnset(extendsParameters.headers)) { + if (!$dara.isNull(extendsParameters.headers)) { extendsHeaders = extendsParameters.headers; } - if (!Util.isUnset(extendsParameters.queries)) { + if (!$dara.isNull(extendsParameters.queries)) { extendsQueries = extendsParameters.queries; } } request_.headers = { - date: Util.getDateUTCString(), + date: OpenApiUtil.getDateUTCString(), host: this._endpoint, accept: "application/json", - 'x-acs-signature-nonce': Util.getNonce(), + 'x-acs-signature-nonce': OpenApiUtil.getNonce(), 'x-acs-signature-method': "HMAC-SHA1", 'x-acs-signature-version': "1.0", 'x-acs-version': version, 'x-acs-action': action, - 'user-agent': Util.getUserAgent(this._userAgent), + 'user-agent': OpenApiUtil.getUserAgent(this._userAgent), ...globalHeaders, ...extendsHeaders, ...request.headers, }; - if (!Util.isUnset(request.body)) { - request_.body = new $tea.BytesReadable(Util.toJSONString(request.body)); + if (!$dara.isNull(request.body)) { + request_.body = new $dara.BytesReadable(JSON.stringify(request.body)); request_.headers["content-type"] = "application/json; charset=utf-8"; } @@ -650,16 +552,16 @@ export default class Client { ...globalQueries, ...extendsQueries, }; - if (!Util.isUnset(request.query)) { + if (!$dara.isNull(request.query)) { request_.query = { ...request_.query, ...request.query, }; } - if (!Util.equalString(authType, "Anonymous")) { - if (Util.isUnset(this._credential)) { - throw $tea.newError({ + if (authType != "Anonymous") { + if ($dara.isNull(this._credential)) { + throw new ClientError({ code: `InvalidCredentials`, message: `Please set up the credentials correctly. If you are setting them through environment variables, please ensure that ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set correctly. See https://help.aliyun.com/zh/sdk/developer-reference/configure-the-alibaba-cloud-accesskey-environment-variable-on-linux-macos-and-windows-systems for more details.`, }); @@ -667,7 +569,7 @@ export default class Client { let credentialModel = await this._credential.getCredential(); let credentialType = credentialModel.type; - if (Util.equalString(credentialType, "bearer")) { + if (credentialType == "bearer") { let bearerToken = credentialModel.bearerToken; request_.headers["x-acs-bearer-token"] = bearerToken; request_.headers["x-acs-signature-type"] = "BEARERTOKEN"; @@ -675,7 +577,7 @@ export default class Client { let accessKeyId = credentialModel.accessKeyId; let accessKeySecret = credentialModel.accessKeySecret; let securityToken = credentialModel.securityToken; - if (!Util.empty(securityToken)) { + if (!$dara.isNull(securityToken)) { request_.headers["x-acs-accesskey-id"] = accessKeyId; request_.headers["x-acs-security-token"] = securityToken; } @@ -686,61 +588,83 @@ export default class Client { } + let response_ = await $dara.doAction(request_, _runtime); _lastRequest = request_; - let response_ = await $tea.doAction(request_, _runtime); + _lastResponse = response_; - if (Util.equalNumber(response_.statusCode, 204)) { + if (response_.statusCode == 204) { return { headers: response_.headers, }; } - if (Util.is4xx(response_.statusCode) || Util.is5xx(response_.statusCode)) { - let _res = await Util.readAsJSON(response_.body); - let err = Util.assertAsMap(_res); - let requestId = Client.defaultAny(err["RequestId"], err["requestId"]); - requestId = Client.defaultAny(requestId, err["requestid"]); - err["statusCode"] = response_.statusCode; - throw $tea.newError({ - code: `${Client.defaultAny(err["Code"], err["code"])}`, - message: `code: ${response_.statusCode}, ${Client.defaultAny(err["Message"], err["message"])} request id: ${requestId}`, - data: err, - description: `${Client.defaultAny(err["Description"], err["description"])}`, - accessDeniedDetail: Client.defaultAny(err["AccessDeniedDetail"], err["accessDeniedDetail"]), - }); + if ((response_.statusCode >= 400) && (response_.statusCode < 600)) { + let _res = await $dara.Stream.readAsJSON(response_.body); + let err = _res; + let requestId = err["RequestId"] || err["requestId"]; + requestId = requestId || err["requestid"]; + let code = err["Code"] || err["code"]; + if ((`${code}` == "Throttling") || (`${code}` == "Throttling.User") || (`${code}` == "Throttling.Api")) { + throw new ThrottlingError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + retryAfter: OpenApiUtil.getThrottlingTimeLeft(response_.headers), + requestId: `${requestId}`, + }); + } else if ((response_.statusCode >= 400) && (response_.statusCode < 500)) { + throw new ClientError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + accessDeniedDetail: this.getAccessDeniedDetail(err), + requestId: `${requestId}`, + }); + } else { + throw new ServerError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + requestId: `${requestId}`, + }); + } + } - if (Util.equalString(bodyType, "binary")) { + if (bodyType == "binary") { let resp = { body: response_.body, headers: response_.headers, statusCode: response_.statusCode, }; return resp; - } else if (Util.equalString(bodyType, "byte")) { - let byt = await Util.readAsBytes(response_.body); + } else if (bodyType == "byte") { + let byt = await $dara.Stream.readAsBytes(response_.body); return { body: byt, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(bodyType, "string")) { - let str = await Util.readAsString(response_.body); + } else if (bodyType == "string") { + let str = await $dara.Stream.readAsString(response_.body); return { body: str, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(bodyType, "json")) { - let obj = await Util.readAsJSON(response_.body); - let res = Util.assertAsMap(obj); + } else if (bodyType == "json") { + let obj = await $dara.Stream.readAsJSON(response_.body); + let res = obj; return { body: res, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(bodyType, "array")) { - let arr = await Util.readAsJSON(response_.body); + } else if (bodyType == "array") { + let arr = await $dara.Stream.readAsJSON(response_.body); return { body: arr, headers: response_.headers, @@ -754,80 +678,79 @@ export default class Client { } } catch (ex) { - if ($tea.isRetryable(ex)) { - continue; - } - throw ex; + _context = new $dara.RetryPolicyContext({ + retriesAttempted : _retriesAttempted, + httpRequest : _lastRequest, + httpResponse : _lastResponse, + exception : ex, + }); + continue; } } - throw $tea.newUnretryableError(_lastRequest); + throw $dara.newUnretryableError(_context); } /** + * @remarks * Encapsulate the request and invoke the network with form body - * @param action api name - * @param version product version - * @param protocol http or https - * @param method e.g. GET - * @param authType authorization type e.g. AK - * @param pathname pathname of every api - * @param bodyType response body type e.g. String - * @param request object of OpenApiRequest - * @param runtime which controls some details of call api, such as retry times - * @return the response + * + * @param action - api name + * @param version - product version + * @param protocol - http or https + * @param method - e.g. GET + * @param authType - authorization type e.g. AK + * @param pathname - pathname of every api + * @param bodyType - response body type e.g. String + * @param request - object of OpenApiRequest + * @param runtime - which controls some details of call api, such as retry times + * @returns the response */ - async doROARequestWithForm(action: string, version: string, protocol: string, method: string, authType: string, pathname: string, bodyType: string, request: OpenApiRequest, runtime: $Util.RuntimeOptions): Promise<{[key: string]: any}> { + async doROARequestWithForm(action: string, version: string, protocol: string, method: string, authType: string, pathname: string, bodyType: string, request: $OpenApiUtil.OpenApiRequest, runtime: $dara.RuntimeOptions): Promise<{[key: string]: any}> { let _runtime: { [key: string]: any } = { - timeouted: "retry", - key: Util.defaultString(runtime.key, this._key), - cert: Util.defaultString(runtime.cert, this._cert), - ca: Util.defaultString(runtime.ca, this._ca), - readTimeout: Util.defaultNumber(runtime.readTimeout, this._readTimeout), - connectTimeout: Util.defaultNumber(runtime.connectTimeout, this._connectTimeout), - httpProxy: Util.defaultString(runtime.httpProxy, this._httpProxy), - httpsProxy: Util.defaultString(runtime.httpsProxy, this._httpsProxy), - noProxy: Util.defaultString(runtime.noProxy, this._noProxy), - socks5Proxy: Util.defaultString(runtime.socks5Proxy, this._socks5Proxy), - socks5NetWork: Util.defaultString(runtime.socks5NetWork, this._socks5NetWork), - maxIdleConns: Util.defaultNumber(runtime.maxIdleConns, this._maxIdleConns), - retry: { - retryable: runtime.autoretry, - maxAttempts: Util.defaultNumber(runtime.maxAttempts, 3), - }, - backoff: { - policy: Util.defaultString(runtime.backoffPolicy, "no"), - period: Util.defaultNumber(runtime.backoffPeriod, 1), - }, + key: runtime.key || this._key, + cert: runtime.cert || this._cert, + ca: runtime.ca || this._ca, + readTimeout: runtime.readTimeout || this._readTimeout, + connectTimeout: runtime.connectTimeout || this._connectTimeout, + httpProxy: runtime.httpProxy || this._httpProxy, + httpsProxy: runtime.httpsProxy || this._httpsProxy, + noProxy: runtime.noProxy || this._noProxy, + socks5Proxy: runtime.socks5Proxy || this._socks5Proxy, + socks5NetWork: runtime.socks5NetWork || this._socks5NetWork, + maxIdleConns: runtime.maxIdleConns || this._maxIdleConns, + retryOptions: this._retryOptions, ignoreSSL: runtime.ignoreSSL, } - let _lastRequest = null; - let _now = Date.now(); - let _retryTimes = 0; - while ($tea.allowRetry(_runtime['retry'], _retryTimes, _now)) { - if (_retryTimes > 0) { - let _backoffTime = $tea.getBackoffTime(_runtime['backoff'], _retryTimes); + let _retriesAttempted = 0; + let _lastRequest = null, _lastResponse = null; + let _context = new $dara.RetryPolicyContext({ + retriesAttempted: _retriesAttempted, + }); + while ($dara.shouldRetry(_runtime['retryOptions'], _context)) { + if (_retriesAttempted > 0) { + let _backoffTime = $dara.getBackoffDelay(_runtime['retryOptions'], _context); if (_backoffTime > 0) { - await $tea.sleep(_backoffTime); + await $dara.sleep(_backoffTime); } } - _retryTimes = _retryTimes + 1; + _retriesAttempted = _retriesAttempted + 1; try { - let request_ = new $tea.Request(); - request_.protocol = Util.defaultString(this._protocol, protocol); + let request_ = new $dara.Request(); + request_.protocol = this._protocol || protocol; request_.method = method; request_.pathname = pathname; let globalQueries : {[key: string ]: string} = { }; let globalHeaders : {[key: string ]: string} = { }; - if (!Util.isUnset(this._globalParameters)) { + if (!$dara.isNull(this._globalParameters)) { let globalParams = this._globalParameters; - if (!Util.isUnset(globalParams.queries)) { + if (!$dara.isNull(globalParams.queries)) { globalQueries = globalParams.queries; } - if (!Util.isUnset(globalParams.headers)) { + if (!$dara.isNull(globalParams.headers)) { globalHeaders = globalParams.headers; } @@ -835,35 +758,35 @@ export default class Client { let extendsHeaders : {[key: string ]: string} = { }; let extendsQueries : {[key: string ]: string} = { }; - if (!Util.isUnset(runtime.extendsParameters)) { + if (!$dara.isNull(runtime.extendsParameters)) { let extendsParameters = runtime.extendsParameters; - if (!Util.isUnset(extendsParameters.headers)) { + if (!$dara.isNull(extendsParameters.headers)) { extendsHeaders = extendsParameters.headers; } - if (!Util.isUnset(extendsParameters.queries)) { + if (!$dara.isNull(extendsParameters.queries)) { extendsQueries = extendsParameters.queries; } } request_.headers = { - date: Util.getDateUTCString(), + date: OpenApiUtil.getDateUTCString(), host: this._endpoint, accept: "application/json", - 'x-acs-signature-nonce': Util.getNonce(), + 'x-acs-signature-nonce': OpenApiUtil.getNonce(), 'x-acs-signature-method': "HMAC-SHA1", 'x-acs-signature-version': "1.0", 'x-acs-version': version, 'x-acs-action': action, - 'user-agent': Util.getUserAgent(this._userAgent), + 'user-agent': OpenApiUtil.getUserAgent(this._userAgent), ...globalHeaders, ...extendsHeaders, ...request.headers, }; - if (!Util.isUnset(request.body)) { - let m = Util.assertAsMap(request.body); - request_.body = new $tea.BytesReadable(OpenApiUtil.toForm(m)); + if (!$dara.isNull(request.body)) { + let m = request.body; + request_.body = new $dara.BytesReadable(OpenApiUtil.toForm(m)); request_.headers["content-type"] = "application/x-www-form-urlencoded"; } @@ -871,16 +794,16 @@ export default class Client { ...globalQueries, ...extendsQueries, }; - if (!Util.isUnset(request.query)) { + if (!$dara.isNull(request.query)) { request_.query = { ...request_.query, ...request.query, }; } - if (!Util.equalString(authType, "Anonymous")) { - if (Util.isUnset(this._credential)) { - throw $tea.newError({ + if (authType != "Anonymous") { + if ($dara.isNull(this._credential)) { + throw new ClientError({ code: `InvalidCredentials`, message: `Please set up the credentials correctly. If you are setting them through environment variables, please ensure that ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set correctly. See https://help.aliyun.com/zh/sdk/developer-reference/configure-the-alibaba-cloud-accesskey-environment-variable-on-linux-macos-and-windows-systems for more details.`, }); @@ -888,7 +811,7 @@ export default class Client { let credentialModel = await this._credential.getCredential(); let credentialType = credentialModel.type; - if (Util.equalString(credentialType, "bearer")) { + if (credentialType == "bearer") { let bearerToken = credentialModel.bearerToken; request_.headers["x-acs-bearer-token"] = bearerToken; request_.headers["x-acs-signature-type"] = "BEARERTOKEN"; @@ -896,7 +819,7 @@ export default class Client { let accessKeyId = credentialModel.accessKeyId; let accessKeySecret = credentialModel.accessKeySecret; let securityToken = credentialModel.securityToken; - if (!Util.empty(securityToken)) { + if (!$dara.isNull(securityToken)) { request_.headers["x-acs-accesskey-id"] = accessKeyId; request_.headers["x-acs-security-token"] = securityToken; } @@ -907,59 +830,82 @@ export default class Client { } + let response_ = await $dara.doAction(request_, _runtime); _lastRequest = request_; - let response_ = await $tea.doAction(request_, _runtime); + _lastResponse = response_; - if (Util.equalNumber(response_.statusCode, 204)) { + if (response_.statusCode == 204) { return { headers: response_.headers, }; } - if (Util.is4xx(response_.statusCode) || Util.is5xx(response_.statusCode)) { - let _res = await Util.readAsJSON(response_.body); - let err = Util.assertAsMap(_res); - err["statusCode"] = response_.statusCode; - throw $tea.newError({ - code: `${Client.defaultAny(err["Code"], err["code"])}`, - message: `code: ${response_.statusCode}, ${Client.defaultAny(err["Message"], err["message"])} request id: ${Client.defaultAny(err["RequestId"], err["requestId"])}`, - data: err, - description: `${Client.defaultAny(err["Description"], err["description"])}`, - accessDeniedDetail: Client.defaultAny(err["AccessDeniedDetail"], err["accessDeniedDetail"]), - }); + if ((response_.statusCode >= 400) && (response_.statusCode < 600)) { + let _res = await $dara.Stream.readAsJSON(response_.body); + let err = _res; + let requestId = err["RequestId"] || err["requestId"]; + let code = err["Code"] || err["code"]; + if ((`${code}` == "Throttling") || (`${code}` == "Throttling.User") || (`${code}` == "Throttling.Api")) { + throw new ThrottlingError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + retryAfter: OpenApiUtil.getThrottlingTimeLeft(response_.headers), + requestId: `${requestId}`, + }); + } else if ((response_.statusCode >= 400) && (response_.statusCode < 500)) { + throw new ClientError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + accessDeniedDetail: this.getAccessDeniedDetail(err), + requestId: `${requestId}`, + }); + } else { + throw new ServerError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + requestId: `${requestId}`, + }); + } + } - if (Util.equalString(bodyType, "binary")) { + if (bodyType == "binary") { let resp = { body: response_.body, headers: response_.headers, statusCode: response_.statusCode, }; return resp; - } else if (Util.equalString(bodyType, "byte")) { - let byt = await Util.readAsBytes(response_.body); + } else if (bodyType == "byte") { + let byt = await $dara.Stream.readAsBytes(response_.body); return { body: byt, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(bodyType, "string")) { - let str = await Util.readAsString(response_.body); + } else if (bodyType == "string") { + let str = await $dara.Stream.readAsString(response_.body); return { body: str, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(bodyType, "json")) { - let obj = await Util.readAsJSON(response_.body); - let res = Util.assertAsMap(obj); + } else if (bodyType == "json") { + let obj = await $dara.Stream.readAsJSON(response_.body); + let res = obj; return { body: res, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(bodyType, "array")) { - let arr = await Util.readAsJSON(response_.body); + } else if (bodyType == "array") { + let arr = await $dara.Stream.readAsJSON(response_.body); return { body: arr, headers: response_.headers, @@ -973,79 +919,78 @@ export default class Client { } } catch (ex) { - if ($tea.isRetryable(ex)) { - continue; - } - throw ex; + _context = new $dara.RetryPolicyContext({ + retriesAttempted : _retriesAttempted, + httpRequest : _lastRequest, + httpResponse : _lastResponse, + exception : ex, + }); + continue; } } - throw $tea.newUnretryableError(_lastRequest); + throw $dara.newUnretryableError(_context); } /** + * @remarks * Encapsulate the request and invoke the network - * @param action api name - * @param version product version - * @param protocol http or https - * @param method e.g. GET - * @param authType authorization type e.g. AK - * @param bodyType response body type e.g. String - * @param request object of OpenApiRequest - * @param runtime which controls some details of call api, such as retry times - * @return the response + * + * @param action - api name + * @param version - product version + * @param protocol - http or https + * @param method - e.g. GET + * @param authType - authorization type e.g. AK + * @param bodyType - response body type e.g. String + * @param request - object of OpenApiRequest + * @param runtime - which controls some details of call api, such as retry times + * @returns the response */ - async doRequest(params: Params, request: OpenApiRequest, runtime: $Util.RuntimeOptions): Promise<{[key: string]: any}> { + async doRequest(params: $OpenApiUtil.Params, request: $OpenApiUtil.OpenApiRequest, runtime: $dara.RuntimeOptions): Promise<{[key: string]: any}> { let _runtime: { [key: string]: any } = { - timeouted: "retry", - key: Util.defaultString(runtime.key, this._key), - cert: Util.defaultString(runtime.cert, this._cert), - ca: Util.defaultString(runtime.ca, this._ca), - readTimeout: Util.defaultNumber(runtime.readTimeout, this._readTimeout), - connectTimeout: Util.defaultNumber(runtime.connectTimeout, this._connectTimeout), - httpProxy: Util.defaultString(runtime.httpProxy, this._httpProxy), - httpsProxy: Util.defaultString(runtime.httpsProxy, this._httpsProxy), - noProxy: Util.defaultString(runtime.noProxy, this._noProxy), - socks5Proxy: Util.defaultString(runtime.socks5Proxy, this._socks5Proxy), - socks5NetWork: Util.defaultString(runtime.socks5NetWork, this._socks5NetWork), - maxIdleConns: Util.defaultNumber(runtime.maxIdleConns, this._maxIdleConns), - retry: { - retryable: runtime.autoretry, - maxAttempts: Util.defaultNumber(runtime.maxAttempts, 3), - }, - backoff: { - policy: Util.defaultString(runtime.backoffPolicy, "no"), - period: Util.defaultNumber(runtime.backoffPeriod, 1), - }, + key: runtime.key || this._key, + cert: runtime.cert || this._cert, + ca: runtime.ca || this._ca, + readTimeout: runtime.readTimeout || this._readTimeout, + connectTimeout: runtime.connectTimeout || this._connectTimeout, + httpProxy: runtime.httpProxy || this._httpProxy, + httpsProxy: runtime.httpsProxy || this._httpsProxy, + noProxy: runtime.noProxy || this._noProxy, + socks5Proxy: runtime.socks5Proxy || this._socks5Proxy, + socks5NetWork: runtime.socks5NetWork || this._socks5NetWork, + maxIdleConns: runtime.maxIdleConns || this._maxIdleConns, + retryOptions: this._retryOptions, ignoreSSL: runtime.ignoreSSL, } - let _lastRequest = null; - let _now = Date.now(); - let _retryTimes = 0; - while ($tea.allowRetry(_runtime['retry'], _retryTimes, _now)) { - if (_retryTimes > 0) { - let _backoffTime = $tea.getBackoffTime(_runtime['backoff'], _retryTimes); + let _retriesAttempted = 0; + let _lastRequest = null, _lastResponse = null; + let _context = new $dara.RetryPolicyContext({ + retriesAttempted: _retriesAttempted, + }); + while ($dara.shouldRetry(_runtime['retryOptions'], _context)) { + if (_retriesAttempted > 0) { + let _backoffTime = $dara.getBackoffDelay(_runtime['retryOptions'], _context); if (_backoffTime > 0) { - await $tea.sleep(_backoffTime); + await $dara.sleep(_backoffTime); } } - _retryTimes = _retryTimes + 1; + _retriesAttempted = _retriesAttempted + 1; try { - let request_ = new $tea.Request(); - request_.protocol = Util.defaultString(this._protocol, params.protocol); + let request_ = new $dara.Request(); + request_.protocol = this._protocol || params.protocol; request_.method = params.method; request_.pathname = params.pathname; let globalQueries : {[key: string ]: string} = { }; let globalHeaders : {[key: string ]: string} = { }; - if (!Util.isUnset(this._globalParameters)) { + if (!$dara.isNull(this._globalParameters)) { let globalParams = this._globalParameters; - if (!Util.isUnset(globalParams.queries)) { + if (!$dara.isNull(globalParams.queries)) { globalQueries = globalParams.queries; } - if (!Util.isUnset(globalParams.headers)) { + if (!$dara.isNull(globalParams.headers)) { globalHeaders = globalParams.headers; } @@ -1053,13 +998,13 @@ export default class Client { let extendsHeaders : {[key: string ]: string} = { }; let extendsQueries : {[key: string ]: string} = { }; - if (!Util.isUnset(runtime.extendsParameters)) { + if (!$dara.isNull(runtime.extendsParameters)) { let extendsParameters = runtime.extendsParameters; - if (!Util.isUnset(extendsParameters.headers)) { + if (!$dara.isNull(extendsParameters.headers)) { extendsHeaders = extendsParameters.headers; } - if (!Util.isUnset(extendsParameters.queries)) { + if (!$dara.isNull(extendsParameters.queries)) { extendsQueries = extendsParameters.queries; } @@ -1067,7 +1012,6 @@ export default class Client { request_.query = { ...globalQueries, - ...extendsQueries, ...request.query, }; // endpoint is setted in product client @@ -1075,17 +1019,17 @@ export default class Client { host: this._endpoint, 'x-acs-version': params.version, 'x-acs-action': params.action, - 'user-agent': this.getUserAgent(), + 'user-agent': OpenApiUtil.getUserAgent(this._userAgent), 'x-acs-date': OpenApiUtil.getTimestamp(), - 'x-acs-signature-nonce': Util.getNonce(), + 'x-acs-signature-nonce': OpenApiUtil.getNonce(), accept: "application/json", ...globalHeaders, ...extendsHeaders, ...request.headers, }; - if (Util.equalString(params.style, "RPC")) { + if (params.style == "RPC") { let headers = this.getRpcHeaders(); - if (!Util.isUnset(headers)) { + if (!$dara.isNull(headers)) { request_.headers = { ...request_.headers, ...headers, @@ -1094,29 +1038,29 @@ export default class Client { } - let signatureAlgorithm = Util.defaultString(this._signatureAlgorithm, "ACS3-HMAC-SHA256"); - let hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(Util.toBytes(""), signatureAlgorithm)); - if (!Util.isUnset(request.stream)) { - let tmp = await Util.readAsBytes(request.stream); - hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(tmp, signatureAlgorithm)); - request_.body = new $tea.BytesReadable(tmp); + let signatureAlgorithm = this._signatureAlgorithm || "ACS3-HMAC-SHA256"; + let hashedRequestPayload = OpenApiUtil.hash(Buffer.from("", "utf-8"), signatureAlgorithm); + if (!$dara.isNull(request.stream)) { + let tmp = await $dara.Stream.readAsBytes(request.stream); + hashedRequestPayload = OpenApiUtil.hash(tmp, signatureAlgorithm); + request_.body = new $dara.BytesReadable(tmp); request_.headers["content-type"] = "application/octet-stream"; } else { - if (!Util.isUnset(request.body)) { - if (Util.equalString(params.reqBodyType, "byte")) { - let byteObj = Util.assertAsBytes(request.body); - hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(byteObj, signatureAlgorithm)); - request_.body = new $tea.BytesReadable(byteObj); - } else if (Util.equalString(params.reqBodyType, "json")) { - let jsonObj = Util.toJSONString(request.body); - hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(Util.toBytes(jsonObj), signatureAlgorithm)); - request_.body = new $tea.BytesReadable(jsonObj); + if (!$dara.isNull(request.body)) { + if (params.reqBodyType == "byte") { + let byteObj = Buffer.from(request.body); + hashedRequestPayload = OpenApiUtil.hash(byteObj, signatureAlgorithm); + request_.body = new $dara.BytesReadable(byteObj); + } else if (params.reqBodyType == "json") { + let jsonObj = JSON.stringify(request.body); + hashedRequestPayload = OpenApiUtil.hash(Buffer.from(jsonObj, "utf8"), signatureAlgorithm); + request_.body = new $dara.BytesReadable(jsonObj); request_.headers["content-type"] = "application/json; charset=utf-8"; } else { - let m = Util.assertAsMap(request.body); + let m = request.body; let formObj = OpenApiUtil.toForm(m); - hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(Util.toBytes(formObj), signatureAlgorithm)); - request_.body = new $tea.BytesReadable(formObj); + hashedRequestPayload = OpenApiUtil.hash(Buffer.from(formObj, "utf8"), signatureAlgorithm); + request_.body = new $dara.BytesReadable(formObj); request_.headers["content-type"] = "application/x-www-form-urlencoded"; } @@ -1124,10 +1068,10 @@ export default class Client { } - request_.headers["x-acs-content-sha256"] = hashedRequestPayload; - if (!Util.equalString(params.authType, "Anonymous")) { - if (Util.isUnset(this._credential)) { - throw $tea.newError({ + request_.headers["x-acs-content-sha256"] = hashedRequestPayload.toString("hex"); + if (params.authType != "Anonymous") { + if ($dara.isNull(this._credential)) { + throw new ClientError({ code: `InvalidCredentials`, message: `Please set up the credentials correctly. If you are setting them through environment variables, please ensure that ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set correctly. See https://help.aliyun.com/zh/sdk/developer-reference/configure-the-alibaba-cloud-accesskey-environment-variable-on-linux-macos-and-windows-systems for more details.`, }); @@ -1135,10 +1079,10 @@ export default class Client { let credentialModel = await this._credential.getCredential(); let authType = credentialModel.type; - if (Util.equalString(authType, "bearer")) { + if (authType == "bearer") { let bearerToken = credentialModel.bearerToken; request_.headers["x-acs-bearer-token"] = bearerToken; - if (Util.equalString(params.style, "RPC")) { + if (params.style == "RPC") { request_.query["SignatureType"] = "BEARERTOKEN"; } else { request_.headers["x-acs-signature-type"] = "BEARERTOKEN"; @@ -1148,78 +1092,101 @@ export default class Client { let accessKeyId = credentialModel.accessKeyId; let accessKeySecret = credentialModel.accessKeySecret; let securityToken = credentialModel.securityToken; - if (!Util.empty(securityToken)) { + if (!$dara.isNull(securityToken)) { request_.headers["x-acs-accesskey-id"] = accessKeyId; request_.headers["x-acs-security-token"] = securityToken; } - request_.headers["Authorization"] = OpenApiUtil.getAuthorization(request_, signatureAlgorithm, hashedRequestPayload, accessKeyId, accessKeySecret); + request_.headers["Authorization"] = OpenApiUtil.getAuthorization(request_, signatureAlgorithm, hashedRequestPayload.toString("hex"), accessKeyId, accessKeySecret); } } + let response_ = await $dara.doAction(request_, _runtime); _lastRequest = request_; - let response_ = await $tea.doAction(request_, _runtime); + _lastResponse = response_; - if (Util.is4xx(response_.statusCode) || Util.is5xx(response_.statusCode)) { + if ((response_.statusCode >= 400) && (response_.statusCode < 600)) { let err : {[key: string ]: any} = { }; - if (!Util.isUnset(response_.headers["content-type"]) && Util.equalString(response_.headers["content-type"], "text/xml;charset=utf-8")) { - let _str = await Util.readAsString(response_.body); - let respMap = XML.parseXml(_str, null); - err = Util.assertAsMap(respMap["Error"]); + if (!$dara.isNull(response_.headers["content-type"]) && response_.headers["content-type"] == "text/xml;charset=utf-8") { + let _str = await $dara.Stream.readAsString(response_.body); + let respMap = $dara.XML.parseXml(_str, null); + err = respMap["Error"]; } else { - let _res = await Util.readAsJSON(response_.body); - err = Util.assertAsMap(_res); + let _res = await $dara.Stream.readAsJSON(response_.body); + err = _res; + } + + let requestId = err["RequestId"] || err["requestId"]; + let code = err["Code"] || err["code"]; + if ((`${code}` == "Throttling") || (`${code}` == "Throttling.User") || (`${code}` == "Throttling.Api")) { + throw new ThrottlingError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + retryAfter: OpenApiUtil.getThrottlingTimeLeft(response_.headers), + requestId: `${requestId}`, + }); + } else if ((response_.statusCode >= 400) && (response_.statusCode < 500)) { + throw new ClientError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + accessDeniedDetail: this.getAccessDeniedDetail(err), + requestId: `${requestId}`, + }); + } else { + throw new ServerError({ + statusCode: response_.statusCode, + code: `${code}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${requestId}`, + description: `${err["Description"] || err["description"]}`, + requestId: `${requestId}`, + }); } - err["statusCode"] = response_.statusCode; - throw $tea.newError({ - code: `${Client.defaultAny(err["Code"], err["code"])}`, - message: `code: ${response_.statusCode}, ${Client.defaultAny(err["Message"], err["message"])} request id: ${Client.defaultAny(err["RequestId"], err["requestId"])}`, - data: err, - description: `${Client.defaultAny(err["Description"], err["description"])}`, - accessDeniedDetail: Client.defaultAny(err["AccessDeniedDetail"], err["accessDeniedDetail"]), - }); } - if (Util.equalString(params.bodyType, "binary")) { + if (params.bodyType == "binary") { let resp = { body: response_.body, headers: response_.headers, statusCode: response_.statusCode, }; return resp; - } else if (Util.equalString(params.bodyType, "byte")) { - let byt = await Util.readAsBytes(response_.body); + } else if (params.bodyType == "byte") { + let byt = await $dara.Stream.readAsBytes(response_.body); return { body: byt, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(params.bodyType, "string")) { - let str = await Util.readAsString(response_.body); + } else if (params.bodyType == "string") { + let str = await $dara.Stream.readAsString(response_.body); return { body: str, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(params.bodyType, "json")) { - let obj = await Util.readAsJSON(response_.body); - let res = Util.assertAsMap(obj); + } else if (params.bodyType == "json") { + let obj = await $dara.Stream.readAsJSON(response_.body); + let res = obj; return { body: res, headers: response_.headers, statusCode: response_.statusCode, }; - } else if (Util.equalString(params.bodyType, "array")) { - let arr = await Util.readAsJSON(response_.body); + } else if (params.bodyType == "array") { + let arr = await $dara.Stream.readAsJSON(response_.body); return { body: arr, headers: response_.headers, statusCode: response_.statusCode, }; } else { - let anything = await Util.readAsString(response_.body); + let anything = await $dara.Stream.readAsString(response_.body); return { body: anything, headers: response_.headers, @@ -1228,79 +1195,78 @@ export default class Client { } } catch (ex) { - if ($tea.isRetryable(ex)) { - continue; - } - throw ex; + _context = new $dara.RetryPolicyContext({ + retriesAttempted : _retriesAttempted, + httpRequest : _lastRequest, + httpResponse : _lastResponse, + exception : ex, + }); + continue; } } - throw $tea.newUnretryableError(_lastRequest); + throw $dara.newUnretryableError(_context); } /** + * @remarks * Encapsulate the request and invoke the network - * @param action api name - * @param version product version - * @param protocol http or https - * @param method e.g. GET - * @param authType authorization type e.g. AK - * @param bodyType response body type e.g. String - * @param request object of OpenApiRequest - * @param runtime which controls some details of call api, such as retry times - * @return the response + * + * @param action - api name + * @param version - product version + * @param protocol - http or https + * @param method - e.g. GET + * @param authType - authorization type e.g. AK + * @param bodyType - response body type e.g. String + * @param request - object of OpenApiRequest + * @param runtime - which controls some details of call api, such as retry times + * @returns the response */ - async execute(params: Params, request: OpenApiRequest, runtime: $Util.RuntimeOptions): Promise<{[key: string]: any}> { + async execute(params: $OpenApiUtil.Params, request: $OpenApiUtil.OpenApiRequest, runtime: $dara.RuntimeOptions): Promise<{[key: string]: any}> { let _runtime: { [key: string]: any } = { - timeouted: "retry", - key: Util.defaultString(runtime.key, this._key), - cert: Util.defaultString(runtime.cert, this._cert), - ca: Util.defaultString(runtime.ca, this._ca), - readTimeout: Util.defaultNumber(runtime.readTimeout, this._readTimeout), - connectTimeout: Util.defaultNumber(runtime.connectTimeout, this._connectTimeout), - httpProxy: Util.defaultString(runtime.httpProxy, this._httpProxy), - httpsProxy: Util.defaultString(runtime.httpsProxy, this._httpsProxy), - noProxy: Util.defaultString(runtime.noProxy, this._noProxy), - socks5Proxy: Util.defaultString(runtime.socks5Proxy, this._socks5Proxy), - socks5NetWork: Util.defaultString(runtime.socks5NetWork, this._socks5NetWork), - maxIdleConns: Util.defaultNumber(runtime.maxIdleConns, this._maxIdleConns), - retry: { - retryable: runtime.autoretry, - maxAttempts: Util.defaultNumber(runtime.maxAttempts, 3), - }, - backoff: { - policy: Util.defaultString(runtime.backoffPolicy, "no"), - period: Util.defaultNumber(runtime.backoffPeriod, 1), - }, + key: runtime.key || this._key, + cert: runtime.cert || this._cert, + ca: runtime.ca || this._ca, + readTimeout: runtime.readTimeout || this._readTimeout, + connectTimeout: runtime.connectTimeout || this._connectTimeout, + httpProxy: runtime.httpProxy || this._httpProxy, + httpsProxy: runtime.httpsProxy || this._httpsProxy, + noProxy: runtime.noProxy || this._noProxy, + socks5Proxy: runtime.socks5Proxy || this._socks5Proxy, + socks5NetWork: runtime.socks5NetWork || this._socks5NetWork, + maxIdleConns: runtime.maxIdleConns || this._maxIdleConns, + retryOptions: this._retryOptions, ignoreSSL: runtime.ignoreSSL, - disableHttp2: Client.defaultAny(this._disableHttp2, false), + disableHttp2: this._disableHttp2 || false, } - let _lastRequest = null; - let _now = Date.now(); - let _retryTimes = 0; - while ($tea.allowRetry(_runtime['retry'], _retryTimes, _now)) { - if (_retryTimes > 0) { - let _backoffTime = $tea.getBackoffTime(_runtime['backoff'], _retryTimes); + let _retriesAttempted = 0; + let _lastRequest = null, _lastResponse = null; + let _context = new $dara.RetryPolicyContext({ + retriesAttempted: _retriesAttempted, + }); + while ($dara.shouldRetry(_runtime['retryOptions'], _context)) { + if (_retriesAttempted > 0) { + let _backoffTime = $dara.getBackoffDelay(_runtime['retryOptions'], _context); if (_backoffTime > 0) { - await $tea.sleep(_backoffTime); + await $dara.sleep(_backoffTime); } } - _retryTimes = _retryTimes + 1; + _retriesAttempted = _retriesAttempted + 1; try { - let request_ = new $tea.Request(); + let request_ = new $dara.Request(); // spi = new Gateway();//Gateway implements SPI,这一步在产品 SDK 中实例化 let headers = this.getRpcHeaders(); let globalQueries : {[key: string ]: string} = { }; let globalHeaders : {[key: string ]: string} = { }; - if (!Util.isUnset(this._globalParameters)) { + if (!$dara.isNull(this._globalParameters)) { let globalParams = this._globalParameters; - if (!Util.isUnset(globalParams.queries)) { + if (!$dara.isNull(globalParams.queries)) { globalQueries = globalParams.queries; } - if (!Util.isUnset(globalParams.headers)) { + if (!$dara.isNull(globalParams.headers)) { globalHeaders = globalParams.headers; } @@ -1308,13 +1274,13 @@ export default class Client { let extendsHeaders : {[key: string ]: string} = { }; let extendsQueries : {[key: string ]: string} = { }; - if (!Util.isUnset(runtime.extendsParameters)) { + if (!$dara.isNull(runtime.extendsParameters)) { let extendsParameters = runtime.extendsParameters; - if (!Util.isUnset(extendsParameters.headers)) { + if (!$dara.isNull(extendsParameters.headers)) { extendsHeaders = extendsParameters.headers; } - if (!Util.isUnset(extendsParameters.queries)) { + if (!$dara.isNull(extendsParameters.queries)) { extendsQueries = extendsParameters.queries; } @@ -1339,8 +1305,8 @@ export default class Client { productId: this._productId, action: params.action, version: params.version, - protocol: Util.defaultString(this._protocol, params.protocol), - method: Util.defaultString(this._method, params.method), + protocol: this._protocol || params.protocol, + method: this._method || params.method, authType: params.authType, bodyType: params.bodyType, reqBodyType: params.reqBodyType, @@ -1348,11 +1314,11 @@ export default class Client { credential: this._credential, signatureVersion: this._signatureVersion, signatureAlgorithm: this._signatureAlgorithm, - userAgent: this.getUserAgent(), + userAgent: OpenApiUtil.getUserAgent(this._userAgent), }); let configurationContext = new $SPI.InterceptorContextConfiguration({ regionId: this._regionId, - endpoint: Util.defaultString(request.endpointOverride, this._endpoint), + endpoint: request.endpointOverride || this._endpoint, endpointRule: this._endpointRule, endpointMap: this._endpointMap, endpointType: this._endpointType, @@ -1374,8 +1340,9 @@ export default class Client { request_.query = interceptorContext.request.query; request_.body = interceptorContext.request.stream; request_.headers = interceptorContext.request.headers; + let response_ = await $dara.doAction(request_, _runtime); _lastRequest = request_; - let response_ = await $tea.doAction(request_, _runtime); + _lastResponse = response_; let responseContext = new $SPI.InterceptorContextResponse({ statusCode: response_.statusCode, @@ -1391,29 +1358,225 @@ export default class Client { body: interceptorContext.response.deserializedBody, }; } catch (ex) { - if ($tea.isRetryable(ex)) { - continue; + _context = new $dara.RetryPolicyContext({ + retriesAttempted : _retriesAttempted, + httpRequest : _lastRequest, + httpResponse : _lastResponse, + exception : ex, + }); + continue; + } + } + + throw $dara.newUnretryableError(_context); + } + + async *callSSEApi(params: $OpenApiUtil.Params, request: $OpenApiUtil.OpenApiRequest, runtime: $dara.RuntimeOptions): AsyncGenerator { + let _runtime: { [key: string]: any } = { + key: runtime.key || this._key, + cert: runtime.cert || this._cert, + ca: runtime.ca || this._ca, + readTimeout: runtime.readTimeout || this._readTimeout, + connectTimeout: runtime.connectTimeout || this._connectTimeout, + httpProxy: runtime.httpProxy || this._httpProxy, + httpsProxy: runtime.httpsProxy || this._httpsProxy, + noProxy: runtime.noProxy || this._noProxy, + socks5Proxy: runtime.socks5Proxy || this._socks5Proxy, + socks5NetWork: runtime.socks5NetWork || this._socks5NetWork, + maxIdleConns: runtime.maxIdleConns || this._maxIdleConns, + retryOptions: this._retryOptions, + ignoreSSL: runtime.ignoreSSL, + } + + let _retriesAttempted = 0; + let _lastRequest = null, _lastResponse = null; + let _context = new $dara.RetryPolicyContext({ + retriesAttempted: _retriesAttempted, + }); + while ($dara.shouldRetry(_runtime['retryOptions'], _context)) { + if (_retriesAttempted > 0) { + let _backoffTime = $dara.getBackoffDelay(_runtime['retryOptions'], _context); + if (_backoffTime > 0) { + await $dara.sleep(_backoffTime); + } + } + + _retriesAttempted = _retriesAttempted + 1; + try { + let request_ = new $dara.Request(); + request_.protocol = this._protocol || params.protocol; + request_.method = params.method; + request_.pathname = params.pathname; + let globalQueries : {[key: string ]: string} = { }; + let globalHeaders : {[key: string ]: string} = { }; + if (!$dara.isNull(this._globalParameters)) { + let globalParams = this._globalParameters; + if (!$dara.isNull(globalParams.queries)) { + globalQueries = globalParams.queries; + } + + if (!$dara.isNull(globalParams.headers)) { + globalHeaders = globalParams.headers; + } + + } + + let extendsHeaders : {[key: string ]: string} = { }; + let extendsQueries : {[key: string ]: string} = { }; + if (!$dara.isNull(runtime.extendsParameters)) { + let extendsParameters = runtime.extendsParameters; + if (!$dara.isNull(extendsParameters.headers)) { + extendsHeaders = extendsParameters.headers; + } + + if (!$dara.isNull(extendsParameters.queries)) { + extendsQueries = extendsParameters.queries; + } + + } + + request_.query = { + ...globalQueries, + ...extendsQueries, + ...request.query, + }; + // endpoint is setted in product client + request_.headers = { + host: this._endpoint, + 'x-acs-version': params.version, + 'x-acs-action': params.action, + 'user-agent': OpenApiUtil.getUserAgent(this._userAgent), + 'x-acs-date': OpenApiUtil.getTimestamp(), + 'x-acs-signature-nonce': OpenApiUtil.getNonce(), + accept: "application/json", + ...extendsHeaders, + ...globalHeaders, + ...request.headers, + }; + if (params.style == "RPC") { + let headers = this.getRpcHeaders(); + if (!$dara.isNull(headers)) { + request_.headers = { + ...request_.headers, + ...headers, + }; + } + } - throw ex; + + let signatureAlgorithm = this._signatureAlgorithm || "ACS3-HMAC-SHA256"; + let hashedRequestPayload = OpenApiUtil.hash(Buffer.from("", "utf-8"), signatureAlgorithm); + if (!$dara.isNull(request.stream)) { + let tmp = await $dara.Stream.readAsBytes(request.stream); + hashedRequestPayload = OpenApiUtil.hash(tmp, signatureAlgorithm); + request_.body = new $dara.BytesReadable(tmp); + request_.headers["content-type"] = "application/octet-stream"; + } else { + if (!$dara.isNull(request.body)) { + if (params.reqBodyType == "byte") { + let byteObj = Buffer.from(request.body); + hashedRequestPayload = OpenApiUtil.hash(byteObj, signatureAlgorithm); + request_.body = new $dara.BytesReadable(byteObj); + } else if (params.reqBodyType == "json") { + let jsonObj = JSON.stringify(request.body); + hashedRequestPayload = OpenApiUtil.hash(Buffer.from(jsonObj, "utf8"), signatureAlgorithm); + request_.body = new $dara.BytesReadable(jsonObj); + request_.headers["content-type"] = "application/json; charset=utf-8"; + } else { + let m = request.body; + let formObj = OpenApiUtil.toForm(m); + hashedRequestPayload = OpenApiUtil.hash(Buffer.from(formObj, "utf8"), signatureAlgorithm); + request_.body = new $dara.BytesReadable(formObj); + request_.headers["content-type"] = "application/x-www-form-urlencoded"; + } + + } + + } + + request_.headers["x-acs-content-sha256"] = hashedRequestPayload.toString("hex"); + if (params.authType != "Anonymous") { + let credentialModel = await this._credential.getCredential(); + let authType = credentialModel.type; + if (authType == "bearer") { + let bearerToken = credentialModel.bearerToken; + request_.headers["x-acs-bearer-token"] = bearerToken; + } else { + let accessKeyId = credentialModel.accessKeyId; + let accessKeySecret = credentialModel.accessKeySecret; + let securityToken = credentialModel.securityToken; + if (!$dara.isNull(securityToken)) { + request_.headers["x-acs-accesskey-id"] = accessKeyId; + request_.headers["x-acs-security-token"] = securityToken; + } + + request_.headers["Authorization"] = OpenApiUtil.getAuthorization(request_, signatureAlgorithm, hashedRequestPayload.toString("hex"), accessKeyId, accessKeySecret); + } + + } + + let response_ = await $dara.doAction(request_, _runtime); + _lastRequest = request_; + _lastResponse = response_; + + if ((response_.statusCode >= 400) && (response_.statusCode < 600)) { + let err : {[key: string ]: any} = { }; + if (!$dara.isNull(response_.headers["content-type"]) && response_.headers["content-type"] == "text/xml;charset=utf-8") { + let _str = await $dara.Stream.readAsString(response_.body); + let respMap = $dara.XML.parseXml(_str, null); + err = respMap["Error"]; + } else { + let _res = await $dara.Stream.readAsJSON(response_.body); + err = _res; + } + + err["statusCode"] = response_.statusCode; + throw $dara.newError({ + code: `${err["Code"] || err["code"]}`, + message: `code: ${response_.statusCode}, ${err["Message"] || err["message"]} request id: ${err["RequestId"] || err["requestId"]}`, + data: err, + description: `${err["Description"] || err["description"]}`, + accessDeniedDetail: err["AccessDeniedDetail"] || err["accessDeniedDetail"], + }); + } + + let events = await $dara.Stream.readAsSSE(response_.body); + + for await (let event of events) { + yield new SSEResponse({ + statusCode: response_.statusCode, + headers: response_.headers, + event: event, + }); + } + return null; + } catch (ex) { + _context = new $dara.RetryPolicyContext({ + retriesAttempted : _retriesAttempted, + httpRequest : _lastRequest, + httpResponse : _lastResponse, + exception : ex, + }); + continue; } } - throw $tea.newUnretryableError(_lastRequest); + throw $dara.newUnretryableError(_context); } - async callApi(params: Params, request: OpenApiRequest, runtime: $Util.RuntimeOptions): Promise<{[key: string]: any}> { - if (Util.isUnset(params)) { - throw $tea.newError({ + async callApi(params: $OpenApiUtil.Params, request: $OpenApiUtil.OpenApiRequest, runtime: $dara.RuntimeOptions): Promise<{[key: string]: any}> { + if ($dara.isNull(params)) { + throw new ClientError({ code: "ParameterMissing", message: "'params' can not be unset", }); } - if (Util.isUnset(this._signatureAlgorithm) || !Util.equalString(this._signatureAlgorithm, "v2")) { + if ($dara.isNull(this._signatureAlgorithm) || this._signatureAlgorithm != "v2") { return await this.doRequest(params, request, runtime); - } else if (Util.equalString(params.style, "ROA") && Util.equalString(params.reqBodyType, "json")) { + } else if ((params.style == "ROA") && (params.reqBodyType == "json")) { return await this.doROARequest(params.action, params.version, params.protocol, params.method, params.authType, params.pathname, params.bodyType, request, runtime); - } else if (Util.equalString(params.style, "ROA")) { + } else if (params.style == "ROA") { return await this.doROARequestWithForm(params.action, params.version, params.protocol, params.method, params.authType, params.pathname, params.bodyType, request, runtime); } else { return await this.doRPCRequest(params.action, params.version, params.protocol, params.method, params.authType, params.bodyType, request, runtime); @@ -1422,20 +1585,12 @@ export default class Client { } /** - * Get user agent - * @return user agent - */ - getUserAgent(): string { - let userAgent = Util.getUserAgent(this._userAgent); - return userAgent; - } - - /** + * @remarks * Get accesskey id by using credential - * @return accesskey id + * @returns accesskey id */ async getAccessKeyId(): Promise { - if (Util.isUnset(this._credential)) { + if ($dara.isNull(this._credential)) { return ""; } @@ -1444,11 +1599,12 @@ export default class Client { } /** + * @remarks * Get accesskey secret by using credential - * @return accesskey secret + * @returns accesskey secret */ async getAccessKeySecret(): Promise { - if (Util.isUnset(this._credential)) { + if ($dara.isNull(this._credential)) { return ""; } @@ -1457,11 +1613,12 @@ export default class Client { } /** + * @remarks * Get security token by using credential - * @return security token + * @returns security token */ async getSecurityToken(): Promise { - if (Util.isUnset(this._credential)) { + if ($dara.isNull(this._credential)) { return ""; } @@ -1470,11 +1627,12 @@ export default class Client { } /** + * @remarks * Get bearer token by credential - * @return bearer token + * @returns bearer token */ async getBearerToken(): Promise { - if (Util.isUnset(this._credential)) { + if ($dara.isNull(this._credential)) { return ""; } @@ -1483,11 +1641,12 @@ export default class Client { } /** + * @remarks * Get credential type by credential - * @return credential type e.g. access_key + * @returns credential type e.g. access_key */ async getType(): Promise { - if (Util.isUnset(this._credential)) { + if ($dara.isNull(this._credential)) { return ""; } @@ -1496,26 +1655,14 @@ export default class Client { } /** - * If inputValue is not null, return it or return defaultValue - * @param inputValue users input value - * @param defaultValue default value - * @return the final result - */ - static defaultAny(inputValue: any, defaultValue: any): any { - if (Util.isUnset(inputValue)) { - return defaultValue; - } - - return inputValue; - } - - /** + * @remarks * If the endpointRule and config.endpoint are empty, throw error - * @param config config contains the necessary information to create a client + * + * @param config - config contains the necessary information to create a client */ - checkConfig(config: Config): void { - if (Util.empty(this._endpointRule) && Util.empty(config.endpoint)) { - throw $tea.newError({ + checkConfig(config: $OpenApiUtil.Config): void { + if ($dara.isNull(this._endpointRule) && $dara.isNull(config.endpoint)) { + throw new ClientError({ code: "ParameterMissing", message: "'config.endpoint' can not be empty", }); @@ -1524,22 +1671,27 @@ export default class Client { } /** + * @remarks * set gateway client - * @param spi. + * + * @param spi - . */ setGatewayClient(spi: SPI): void { this._spi = spi; } /** + * @remarks * set RPC header for debug - * @param headers headers for debug, this header can be used only once. + * + * @param headers - headers for debug, this header can be used only once. */ setRpcHeaders(headers: {[key: string ]: string}): void { this._headers = headers; } /** + * @remarks * get RPC header for debug */ getRpcHeaders(): {[key: string ]: string} { @@ -1548,4 +1700,17 @@ export default class Client { return headers; } + getAccessDeniedDetail(err: {[key: string ]: any}): {[key: string ]: any} { + let accessDeniedDetail : {[key: string ]: any} = null; + if (!$dara.isNull(err["AccessDeniedDetail"])) { + let detail1 = err["AccessDeniedDetail"]; + accessDeniedDetail = detail1; + } else if (!$dara.isNull(err["accessDeniedDetail"])) { + let detail2 = err["accessDeniedDetail"]; + accessDeniedDetail = detail2; + } + + return accessDeniedDetail; + } + } diff --git a/ts/src/utils.ts b/ts/src/utils.ts new file mode 100644 index 0000000..3257884 --- /dev/null +++ b/ts/src/utils.ts @@ -0,0 +1,1027 @@ +// This file is auto-generated, don't edit it +/** + * This is for OpenApi Util + */ +import * as $tea from '@alicloud/tea-typescript'; +import * as $dara from '@darabonba/typescript'; +import Credential from '@alicloud/credentials'; +import { Readable } from 'stream'; +import querystring from 'querystring'; +import crypto from 'crypto'; +import os from 'os'; + + +const PEM_BEGIN = "-----BEGIN PRIVATE KEY-----\n"; +const PEM_END = "\n-----END PRIVATE KEY-----"; +const DEFAULT_USER_AGENT = `AlibabaCloud (${os.platform()}; ${os.arch()}) Node.js/${process.version} Core/1.0.1 TeaDSL/2`; + + +export class GlobalParameters extends $tea.Model { + headers?: { [key: string]: string }; + queries?: { [key: string]: string }; + static names(): { [key: string]: string } { + return { + headers: 'headers', + queries: 'queries', + }; + } + + static types(): { [key: string]: any } { + return { + headers: { 'type': 'map', 'keyType': 'string', 'valueType': 'string' }, + queries: { 'type': 'map', 'keyType': 'string', 'valueType': 'string' }, + }; + } + + constructor(map?: { [key: string]: any }) { + super(map); + } +} + +/** + * @remarks + * Model for initing client + */ +export class Config extends $tea.Model { + /** + * @remarks + * accesskey id + */ + accessKeyId?: string; + /** + * @remarks + * accesskey secret + */ + accessKeySecret?: string; + /** + * @remarks + * security token + */ + securityToken?: string; + /** + * @remarks + * bearer token + * + * @example + * the-bearer-token + */ + bearerToken?: string; + /** + * @remarks + * http protocol + * + * @example + * http + */ + protocol?: string; + /** + * @remarks + * http method + * + * @example + * GET + */ + method?: string; + /** + * @remarks + * region id + * + * @example + * cn-hangzhou + */ + regionId?: string; + /** + * @remarks + * read timeout + * + * @example + * 10 + */ + readTimeout?: number; + /** + * @remarks + * connect timeout + * + * @example + * 10 + */ + connectTimeout?: number; + /** + * @remarks + * http proxy + * + * @example + * http://localhost + */ + httpProxy?: string; + /** + * @remarks + * https proxy + * + * @example + * https://localhost + */ + httpsProxy?: string; + /** + * @remarks + * credential + */ + credential?: Credential; + /** + * @remarks + * endpoint + * + * @example + * cs.aliyuncs.com + */ + endpoint?: string; + /** + * @remarks + * proxy white list + * + * @example + * http://localhost + */ + noProxy?: string; + /** + * @remarks + * max idle conns + * + * @example + * 3 + */ + maxIdleConns?: number; + /** + * @remarks + * network for endpoint + * + * @example + * public + */ + network?: string; + /** + * @remarks + * user agent + * + * @example + * Alibabacloud/1 + */ + userAgent?: string; + /** + * @remarks + * suffix for endpoint + * + * @example + * aliyun + */ + suffix?: string; + /** + * @remarks + * socks5 proxy + */ + socks5Proxy?: string; + /** + * @remarks + * socks5 network + * + * @example + * TCP + */ + socks5NetWork?: string; + /** + * @remarks + * endpoint type + * + * @example + * internal + */ + endpointType?: string; + /** + * @remarks + * OpenPlatform endpoint + * + * @example + * openplatform.aliyuncs.com + */ + openPlatformEndpoint?: string; + /** + * @remarks + * credential type + * + * @example + * access_key + * + * @deprecated + */ + type?: string; + /** + * @remarks + * Signature Version + * + * @example + * v1 + */ + signatureVersion?: string; + /** + * @remarks + * Signature Algorithm + * + * @example + * ACS3-HMAC-SHA256 + */ + signatureAlgorithm?: string; + /** + * @remarks + * Global Parameters + */ + globalParameters?: GlobalParameters; + /** + * @remarks + * privite key for client certificate + * + * @example + * MIIEvQ + */ + key?: string; + /** + * @remarks + * client certificate + * + * @example + * -----BEGIN CERTIFICATE----- + * xxx-----END CERTIFICATE----- + */ + cert?: string; + /** + * @remarks + * server certificate + * + * @example + * -----BEGIN CERTIFICATE----- + * xxx-----END CERTIFICATE----- + */ + ca?: string; + /** + * @remarks + * disable HTTP/2 + * + * @example + * false + */ + disableHttp2?: boolean; + /** + * @remarks + * retry options + */ + retryOptions?: $dara.RetryOptions; + static names(): { [key: string]: string } { + return { + accessKeyId: 'accessKeyId', + accessKeySecret: 'accessKeySecret', + securityToken: 'securityToken', + bearerToken: 'bearerToken', + protocol: 'protocol', + method: 'method', + regionId: 'regionId', + readTimeout: 'readTimeout', + connectTimeout: 'connectTimeout', + httpProxy: 'httpProxy', + httpsProxy: 'httpsProxy', + credential: 'credential', + endpoint: 'endpoint', + noProxy: 'noProxy', + maxIdleConns: 'maxIdleConns', + network: 'network', + userAgent: 'userAgent', + suffix: 'suffix', + socks5Proxy: 'socks5Proxy', + socks5NetWork: 'socks5NetWork', + endpointType: 'endpointType', + openPlatformEndpoint: 'openPlatformEndpoint', + type: 'type', + signatureVersion: 'signatureVersion', + signatureAlgorithm: 'signatureAlgorithm', + globalParameters: 'globalParameters', + key: 'key', + cert: 'cert', + ca: 'ca', + disableHttp2: 'disableHttp2', + retryOptions: 'retryOptions', + }; + } + + static types(): { [key: string]: any } { + return { + accessKeyId: 'string', + accessKeySecret: 'string', + securityToken: 'string', + bearerToken: 'string', + protocol: 'string', + method: 'string', + regionId: 'string', + readTimeout: 'number', + connectTimeout: 'number', + httpProxy: 'string', + httpsProxy: 'string', + credential: Credential, + endpoint: 'string', + noProxy: 'string', + maxIdleConns: 'number', + network: 'string', + userAgent: 'string', + suffix: 'string', + socks5Proxy: 'string', + socks5NetWork: 'string', + endpointType: 'string', + openPlatformEndpoint: 'string', + type: 'string', + signatureVersion: 'string', + signatureAlgorithm: 'string', + globalParameters: GlobalParameters, + key: 'string', + cert: 'string', + ca: 'string', + disableHttp2: 'boolean', + retryOptions: $dara.RetryOptions, + }; + } + + constructor(map?: { [key: string]: any }) { + super(map); + } +} + +export class OpenApiRequest extends $tea.Model { + headers?: { [key: string]: string }; + query?: { [key: string]: string }; + body?: any; + stream?: Readable; + hostMap?: { [key: string]: string }; + endpointOverride?: string; + static names(): { [key: string]: string } { + return { + headers: 'headers', + query: 'query', + body: 'body', + stream: 'stream', + hostMap: 'hostMap', + endpointOverride: 'endpointOverride', + }; + } + + static types(): { [key: string]: any } { + return { + headers: { 'type': 'map', 'keyType': 'string', 'valueType': 'string' }, + query: { 'type': 'map', 'keyType': 'string', 'valueType': 'string' }, + body: 'any', + stream: 'Readable', + hostMap: { 'type': 'map', 'keyType': 'string', 'valueType': 'string' }, + endpointOverride: 'string', + }; + } + + constructor(map?: { [key: string]: any }) { + super(map); + } +} + +export class Params extends $tea.Model { + action: string; + version: string; + protocol: string; + pathname: string; + method: string; + authType: string; + bodyType: string; + reqBodyType: string; + style?: string; + static names(): { [key: string]: string } { + return { + action: 'action', + version: 'version', + protocol: 'protocol', + pathname: 'pathname', + method: 'method', + authType: 'authType', + bodyType: 'bodyType', + reqBodyType: 'reqBodyType', + style: 'style', + }; + } + + static types(): { [key: string]: any } { + return { + action: 'string', + version: 'string', + protocol: 'string', + pathname: 'string', + method: 'string', + authType: 'string', + bodyType: 'string', + reqBodyType: 'string', + style: 'string', + }; + } + + constructor(map?: { [key: string]: any }) { + super(map); + } +} + +function replaceRepeatList(target: { [key: string]: string }, repeat: any[], prefix: string) { + if (prefix) { + prefix = prefix + '.'; + } + for (var i = 0; i < repeat.length; i++) { + var item = repeat[i]; + let key = prefix + (i + 1); + if (typeof item === 'undefined' || item == null) { + continue; + } + if (Array.isArray(item)) { + replaceRepeatList(target, item, key); + } else if (item instanceof Object) { + flatMap(target, item, key); + } else { + target[key] = item.toString(); + } + } +} + +function flatMap(target: { [key: string]: any }, params: { [key: string]: any }, prefix: string = '') { + if (prefix) { + prefix = prefix + '.'; + } + params = toMap(params); + let keys = Object.keys(params); + for (let i = 0; i < keys.length; i++) { + let key = keys[i]; + let value = params[key]; + key = prefix + key; + if (typeof value === 'undefined' || value == null) { + continue; + } + + if (Array.isArray(value)) { + replaceRepeatList(target, value, key); + } else if (value instanceof Object) { + flatMap(target, value, key); + } else { + target[key] = value.toString(); + } + } + return target; +} + +function filter(value: string): string { + return value.replace(/[\t\n\r\f]/g, ' '); +} + +function getCanonicalizedHeaders(headers: { [key: string]: string }): string { + const prefix = 'x-acs-'; + const keys = Object.keys(headers); + + const canonicalizedKeys = []; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (key.startsWith(prefix)) { + canonicalizedKeys.push(key); + } + } + + canonicalizedKeys.sort(); + + var result = ''; + for (let i = 0; i < canonicalizedKeys.length; i++) { + const key = canonicalizedKeys[i]; + result += `${key}:${filter(headers[key]).trim()}\n`; + } + + return result; +} + +function getCanonicalizedResource(uriPattern: string, query: { [key: string]: string }): string { + const keys = !query ? [] : Object.keys(query).sort(); + + if (keys.length === 0) { + return uriPattern; + } + + var result = []; + for (var i = 0; i < keys.length; i++) { + const key = keys[i]; + result.push(`${key}=${query[key]}`); + } + + return `${uriPattern}?${result.join('&')}`; +} + +function getAuthorizationQueryString(query: { [key: string]: string }): string { + let canonicalQueryArray = []; + const keys = !query ? [] : Object.keys(query).sort(); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + let param = key + '=' + if (typeof query[key] !== 'undefined' && query[key] !== null) { + param = param + encode(query[key]) + } + canonicalQueryArray.push(param) + } + return canonicalQueryArray.join('&'); +} + +function getAuthorizationHeaders(header: { [key: string]: string }): {} { + let canonicalheaders = ""; + let tmp = {}; + const keys = !header ? [] : Object.keys(header); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const lowerKey = keys[i].toLowerCase(); + if (lowerKey.startsWith("x-acs-") || lowerKey === "host" || lowerKey === "content-type") { + if (tmp[lowerKey]) { + tmp[lowerKey].push((header[key] || "").trim()); + } else { + tmp[lowerKey] = [(header[key] || "").trim()]; + } + } + } + var hsKeys = Object.keys(tmp).sort(); + for (let i = 0; i < hsKeys.length; i++) { + const hsKey = hsKeys[i]; + let listSort = tmp[hsKey].sort(); + canonicalheaders += `${hsKey}:${listSort.join(",")}\n`; + } + + return { canonicalheaders, hsKeys }; +} + +function encode(str: string) { + var result = encodeURIComponent(str); + + return result.replace(/!/g, '%21') + .replace(/'/g, '%27') + .replace(/\(/g, '%28') + .replace(/\)/g, '%29') + .replace(/\*/g, '%2A'); +} + +function normalize(params: { [key: string]: any }) { + var list = []; + var flated: { [key: string]: string } = {}; + flatMap(flated, params); + var keys = Object.keys(flated).sort(); + for (let i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = flated[key]; + list.push([encode(key), encode(value)]); + } + return list; +} + +function canonicalize(normalized: any[]) { + var fields = []; + for (var i = 0; i < normalized.length; i++) { + var [key, value] = normalized[i]; + fields.push(key + '=' + value); + } + return fields.join('&'); +} + +function isModelClass(t: any): boolean { + if (!t) { + return false; + } + return typeof t.types === 'function' && typeof t.names === 'function'; +} + +function isObjectOrArray(t: any): boolean { + return Array.isArray(t) || (t instanceof Object && typeof t !== 'function'); +} + +function getTimeLeft(rateLimit: string | null): number | null { + if (rateLimit) { + const pairs = rateLimit.split(','); + for (const pair of pairs) { + const kv = pair.split(':'); + if (kv.length === 2) { + const key = kv[0].trim(); + const value = kv[1].trim(); + if (key === 'TimeLeft') { + const timeLeftValue = parseInt(value, 10); + if (isNaN(timeLeftValue)) { + return null; + } + return timeLeftValue; + } + } + } + } + return null; +} + +function toMap(input: any) { + if (!isObjectOrArray(input)) { + return null; + } else if (input instanceof $tea.Model) { + return $tea.toMap(input); + } else if (input && input.toMap && typeof input.toMap === 'function') { + // 解决跨版本 Model 不互认的问题 + return input.toMap(); + } else if (Array.isArray(input)) { + const result = []; + input.forEach((value) => { + if (isObjectOrArray(value)) { + result.push(toMap(value)); + } else { + result.push(value); + } + }); + + return result; + } else if (input instanceof Object) { + const result = {}; + Object.entries(input).forEach(([key, value]) => { + if (isObjectOrArray(value)) { + result[key] = toMap(value); + } else { + result[key] = value; + } + }); + + return result; + } +} + +export default class Client { + + /** + * Convert all params of body other than type of readable into content + * @param body source Model + * @param content target Model + * @return void + */ + static convert(input: $tea.Model, output: $tea.Model): void { + if (!output) { + return; + } + let inputModel = Object.assign({}, input); + let constructor = output.constructor; + let types = constructor.types(); + // let constructor = output.constructor; + for (let key of Object.keys(constructor.names())) { + if (inputModel[key] !== null && inputModel[key] !== undefined) { + if (isModelClass(types[key])) { + output[key] = new types[key](output[key]); + Client.convert(inputModel[key], output[key]); + } else if (types[key] && types[key].type === 'array') { + output[key] = inputModel[key].map(function (d) { + if (isModelClass(types[key].itemType)) { + var item = new types[key].itemType({}); + Client.convert(d, item); + return item; + } + return d; + }); + } else if (types[key] && types[key].type === 'map') { + output[key] = {}; + Object.keys(inputModel[key]).map(function (d) { + if (isModelClass(types[key].valueType)) { + var item = new types[key].valueType({}); + Client.convert(inputModel[key][d], item); + output[key][d] = item; + } else { + output[key][d] = inputModel[key][d]; + } + }); + } else { + output[key] = inputModel[key]; + } + } + } + } + + /** + * If endpointType is internal, use internal endpoint + * If serverUse is true and endpointType is accelerate, use accelerate endpoint + * Default return endpoint + * @param serverUse whether use accelerate endpoint + * @param endpointType value must be internal or accelerate + * @return the final endpoint + */ + static getEndpoint(endpoint: string, serverUse: boolean, endpointType: string): string { + if (endpointType == "internal") { + let strs = endpoint.split("."); + strs[0] += "-internal"; + endpoint = strs.join(".") + } + if (serverUse && endpointType == "accelerate") { + return "oss-accelerate.aliyuncs.com" + } + + return endpoint + } + + /** + * Get throttling param + * @param the response headers + * @return time left + */ + static getThrottlingTimeLeft(headers: {[key: string ]: string}): number { + const rateLimitForUserApi = headers["x-ratelimit-user-api"]; + const rateLimitForUser = headers["x-ratelimit-user"]; + const timeLeftForUserApi = getTimeLeft(rateLimitForUserApi); + const timeLeftForUser = getTimeLeft(rateLimitForUser); + + if (timeLeftForUserApi > timeLeftForUser) { + return timeLeftForUserApi; + } else { + return timeLeftForUser; + } + } + + /** + * Hash the raw data with signatureAlgorithm + * @param raw hashing data + * @param signatureAlgorithm the autograph method + * @return hashed bytes + */ + static hash(raw: Buffer, signatureAlgorithm: string): Buffer { + if (signatureAlgorithm === "ACS3-HMAC-SHA256" || signatureAlgorithm === "ACS3-RSA-SHA256") { + const obj = crypto.createHash('sha256'); + obj.update(raw); + return obj.digest(); + } else if (signatureAlgorithm == "ACS3-HMAC-SM3") { + const obj = crypto.createHash('sm3'); + obj.update(raw); + return obj.digest(); + } + } + + /** + * Generate a nonce string + * @return the nonce string + */ + static getNonce(): string { + let counter = 0; + let last; + const machine = os.hostname(); + const pid = process.pid; + + var val = Math.floor(Math.random() * 1000000000000); + if (val === last) { + counter++; + } else { + counter = 0; + } + + last = val; + + var uid = `${machine}${pid}${val}${counter}`; + var shasum = crypto.createHash('md5'); + shasum.update(uid); + return shasum.digest('hex'); + } + + /** + * Get the string to be signed according to request + * @param request which contains signed messages + * @return the signed string + */ + static getStringToSign(request: $tea.Request): string { + const method = request.method; + const accept = request.headers['accept']; + const contentMD5 = request.headers['content-md5'] || ''; + const contentType = request.headers['content-type'] || ''; + const date = request.headers['date'] || ''; + const header = `${method}\n${accept}\n${contentMD5}\n${contentType}\n${date}\n`; + const canonicalizedHeaders = getCanonicalizedHeaders(request.headers); + const canonicalizedResource = getCanonicalizedResource(request.pathname, request.query); + + return `${header}${canonicalizedHeaders}${canonicalizedResource}`; + } + + /** + * Get signature according to stringToSign, secret + * @param stringToSign the signed string + * @param secret accesskey secret + * @return the signature + */ + static getROASignature(stringToSign: string, secret: string): string { + const utf8Buff = Buffer.from(stringToSign, 'utf8'); + return crypto.createHmac('sha1', secret).update(utf8Buff).digest('base64') + } + + /** + * Parse filter into a form string + * @param filter object + * @return the string + */ + static toForm(filter: {[key: string]: any}): string { + if (!filter) { + return ''; + } + let target = {}; + flatMap(target, filter); + return $dara.Form.toFormString(target); + } + + /** + * Get timestamp + * @return the timestamp string + */ + static getTimestamp(): string { + let date = new Date(); + let YYYY = date.getUTCFullYear(); + let MM =`${date.getUTCMonth() + 1}`.padStart(2, '0'); + let DD =`${date.getUTCDate()}`.padStart(2, '0'); + let HH =`${date.getUTCHours()}`.padStart(2, '0'); + let mm =`${date.getUTCMinutes()}`.padStart(2, '0'); + let ss =`${date.getUTCSeconds()}`.padStart(2, '0'); + return `${YYYY}-${MM}-${DD}T${HH}:${mm}:${ss}Z`; + } + + /** + * Get UTC string + * @return the UTC string + */ + static getDateUTCString(): string { + const now = new Date(); + return now.toUTCString(); + } + + /** + * Parse filter into a object which's type is map[string]string + * @param filter query param + * @return the object + */ + static query(filter: {[key: string]: any}): {[key: string ]: string} { + if (!filter) { + return {}; + } + let ret: { [key: string]: string } = {}; + flatMap(ret, filter); + return ret; + } + + /** + * Get signature according to signedParams, method and secret + * @param signedParams params which need to be signed + * @param method http method e.g. GET + * @param secret AccessKeySecret + * @return the signature + */ + static getRPCSignature(signedParams: {[key: string ]: string}, method: string, secret: string): string { + var normalized = normalize(signedParams); + var canonicalized = canonicalize(normalized); + var stringToSign = `${method}&${encode('/')}&${encode(canonicalized)}`; + const key = secret + '&'; + return crypto.createHmac('sha1', key).update(stringToSign).digest('base64'); + } + + /** + * Parse array into a string with specified style + * @param array the array + * @param prefix the prefix string + * @style specified style e.g. repeatList + * @return the string + */ + static arrayToStringWithSpecifiedStyle(array: any, prefix: string, style: string): string { + if (!array) { + return ''; + } + if (style === 'repeatList') { + let target = {}; + replaceRepeatList(target, array, prefix); + return querystring.stringify(target, '&&'); + } else if (style === 'json') { + return JSON.stringify(toMap(array)); + } else if (style === 'simple') { + return array.join(','); + } else if (style === 'spaceDelimited') { + return array.join(' '); + } else if (style === 'pipeDelimited') { + return array.join('|'); + } else { + return ''; + } + } + + static stringifyMapValue(m: { [key: string]: any }): { [key: string]: string } { + if (!m) { + return m; + } + + const result: { [key: string]: string } = {}; + for (const [key, value] of Object.entries(m)) { + if (typeof value === 'undefined' || value === null) { + continue; + } + result[key] = String(value); + } + return result; + } + + + static toArray(input: any): { [key: string]: any }[] { + if (!(input instanceof Array)) { + return null; + } + let ret = []; + input.forEach((model) => { + if (!model) { + return; + } + ret.push($tea.toMap(model)); + }) + return ret; + } + + static getEndpointRules(product: string, regionId: string, endpointType: string, network: string, suffix: string): string { + let result; + if (network && network.length && network != "public") { + network = "-" + network; + } else { + network = ""; + } + suffix = suffix || ""; + if (suffix.length) { + suffix = "-" + suffix; + } + if (endpointType == "regional") { + if (!regionId || !regionId.length) { + throw new Error("RegionId is empty, please set a valid RegionId"); + } + result = `${product}${suffix}${network}.${regionId}.aliyuncs.com`; + } else { + result = `${product}${suffix}${network}.aliyuncs.com`; + } + return result; + } + + /** + * Transform input as map. + */ + static parseToMap(input: any): {[key: string ]: any} { + return toMap(input); + } + + /** + * Get the authorization + * @param request request params + * @param signatureAlgorithm the autograph method + * @param payload the hashed request + * @param accessKey the accessKey string + * @param accessKeySecret the accessKeySecret string + * @return authorization string + */ + static getAuthorization(request: $tea.Request, signatureAlgorithm: string, payload: string, accessKey: string, accessKeySecret: string): string { + const canonicalURI = (request.pathname || "").replace("+", "%20").replace("*", "%2A").replace("%7E", "~"); + const method = request.method; + const canonicalQueryString = getAuthorizationQueryString(request.query); + const tuple = getAuthorizationHeaders(request.headers); + const canonicalheaders = tuple["canonicalheaders"]; + const signedHeaders = tuple["hsKeys"]; + + const canonicalRequest = method + "\n" + canonicalURI + "\n" + canonicalQueryString + "\n" + canonicalheaders + "\n" + + signedHeaders.join(";") + "\n" + payload; + let raw = Buffer.from(canonicalRequest); + const stringToSign = signatureAlgorithm + "\n" + Client.hash(raw, signatureAlgorithm).toString("hex"); + const signature = Client.signatureMethod(accessKeySecret, stringToSign, signatureAlgorithm).toString("hex"); + const auth = `${signatureAlgorithm} Credential=${accessKey},SignedHeaders=${signedHeaders.join(';')},Signature=${signature}`; + + return auth; + } + + static getUserAgent(userAgent: string): string { + if (!userAgent || !userAgent.length) { + return DEFAULT_USER_AGENT; + } + return DEFAULT_USER_AGENT + " " + userAgent; + } + + static signatureMethod(secret: string, source: string, signatureAlgorithm: string): Buffer { + if (signatureAlgorithm === "ACS3-HMAC-SHA256") { + const obj = crypto.createHmac('sha256', secret); + obj.update(source); + return obj.digest(); + } else if (signatureAlgorithm === "ACS3-HMAC-SM3") { + const obj = crypto.createHmac('sm3', secret); + obj.update(source); + return obj.digest(); + } else if (signatureAlgorithm === "ACS3-RSA-SHA256") { + + if (!secret.startsWith(PEM_BEGIN)) { + secret = PEM_BEGIN + secret; + } + if (!secret.endsWith(PEM_END)) { + secret = secret + PEM_END; + } + + var signerObject = crypto.createSign("RSA-SHA256"); + signerObject.update(source); + var signature = signerObject.sign({ key: secret, padding: crypto.constants.RSA_PKCS1_PADDING }); + return signature; + } + } + +} diff --git a/ts/test/client.spec.ts b/ts/test/client.spec.ts index f4a37d5..6be6912 100644 --- a/ts/test/client.spec.ts +++ b/ts/test/client.spec.ts @@ -8,14 +8,12 @@ import { AddressInfo } from 'net'; import { Readable } from 'stream'; import OpenApi, * as $OpenApi from "../src/client"; -import OpenApiUtil from '@alicloud/openapi-util'; -import Util, * as $Util from '@alicloud/tea-util'; +import OpenApiUtil, * as $OpenApiUtil from '../src/utils'; import Credential, * as $Credential from '@alicloud/credentials'; -import * as $tea from '@alicloud/tea-typescript'; +import * as $dara from '@darabonba/typescript'; import POP, * as $POP from '@alicloud/gateway-pop'; const server = http.createServer((req, res) => { - if (req.headers['timeout'] === 'true') { const timeout = setTimeout(() => { res.writeHead(500, { 'Content-Type': 'text/plain' }); @@ -39,6 +37,7 @@ const server = http.createServer((req, res) => { let key = keys[index]; headers[key] = req.headers[key]; } + headers = { ...headers, 'pathname': urlObj.pathname, @@ -47,6 +46,23 @@ const server = http.createServer((req, res) => { 'raw-body': data, 'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4', }; + if(urlObj.pathname === '/sse') { + res.writeHead(200, { + ...headers, + }); + let count = 0; + const timer = setInterval(() => { + if (count >= 5) { + clearInterval(timer); + res.end(); + return; + } + res.write(`data: ${JSON.stringify({ count: count })}\nevent: flow\nid: sse-test\nretry: 3\n:heartbeat\n\n`); + count++; + }, 100); + return; + } + let responseBody = "{\"AppId\":\"test\", \"ClassId\":\"test\", \"UserId\":123}"; switch (headers['bodytype']) { case 'array': @@ -104,8 +120,8 @@ class BytesReadable extends Readable { } } -function createConfig(): $OpenApi.Config { - let globalParameters = new $OpenApi.GlobalParameters({ +function createConfig(): $OpenApiUtil.Config { + let globalParameters = new $OpenApiUtil.GlobalParameters({ headers: { 'global-key': "global-value", }, @@ -113,7 +129,7 @@ function createConfig(): $OpenApi.Config { 'global-query': "global-value", }, }); - let config = new $OpenApi.Config({ + let config = new $OpenApiUtil.Config({ accessKeyId: "ak", accessKeySecret: "secret", securityToken: "token", @@ -129,29 +145,29 @@ function createConfig(): $OpenApi.Config { return config; } -function createBearerTokenConfig(): $OpenApi.Config { +function createBearerTokenConfig(): $OpenApiUtil.Config { let creConfig = new $Credential.Config({ bearerToken: "token", type: "bearer", }); let credential = new Credential(creConfig); - let config = new $OpenApi.Config({ + let config = new $OpenApiUtil.Config({ credential: credential, }); return config; } -function createAnonymousConfig(): $OpenApi.Config { - return new $OpenApi.Config(); +function createAnonymousConfig(): $OpenApiUtil.Config { + return new $OpenApiUtil.Config(); } -function createRuntimeOptions(): $Util.RuntimeOptions { - let extendsParameters = new $Util.ExtendsParameters({ +function createRuntimeOptions(): $dara.RuntimeOptions { + let extendsParameters = new $dara.ExtendsParameters({ headers: { 'extends-key': "extends-value", }, }); - let runtime = new $Util.RuntimeOptions({ + let runtime = new $dara.RuntimeOptions({ readTimeout: 4000, connectTimeout: 4000, maxIdleConns: 100, @@ -165,7 +181,7 @@ function createRuntimeOptions(): $Util.RuntimeOptions { return runtime; } -function createOpenApiRequest(): $OpenApi.OpenApiRequest { +function createOpenApiRequest(): $OpenApiUtil.OpenApiRequest { let query: { [key: string]: any } = {}; query["key1"] = "value"; query["key2"] = 1; @@ -177,7 +193,7 @@ function createOpenApiRequest(): $OpenApi.OpenApiRequest { let headers: { [key: string]: string } = { 'for-test': "sdk", }; - let req = new $OpenApi.OpenApiRequest({ + let req = new $OpenApiUtil.OpenApiRequest({ headers: headers, query: OpenApiUtil.query(query), body: OpenApiUtil.parseToMap(body), @@ -197,7 +213,7 @@ describe('$openapi', function () { }); it('config should ok', async function () { - let globalParameters = new $OpenApi.GlobalParameters({ + let globalParameters = new $OpenApiUtil.GlobalParameters({ headers: { 'global-key': "global-value", }, @@ -205,7 +221,7 @@ describe('$openapi', function () { 'global-query': "global-value", }, }); - let config = new $OpenApi.Config({ + let config = new $OpenApiUtil.Config({ endpoint: "config.endpoint", endpointType: "public", network: "config.network", @@ -328,7 +344,7 @@ describe('$openapi', function () { config.endpoint = `127.0.0.1:${port}`; let client = new OpenApi(config); let request = createOpenApiRequest(); - let params = new $OpenApi.Params({ + let params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -344,7 +360,7 @@ describe('$openapi', function () { assert.strictEqual(headers["raw-body"], "key1=value&key2=1&key3=true"); let regexp = /Action=TestAPI&Format=json&Version=2022-06-01&Timestamp=.+&SignatureNonce=.+&global-query=global-value&key1=value&key2=1&key3=true&SecurityToken=token&SignatureMethod=HMAC-SHA1&SignatureVersion=1\.0&AccessKeyId=ak&Signature=.+/; assert.ok(regexp.test(headers["raw-query"])); - assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/1 config.userAgent")); + assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/2 config.userAgent")); assert.strictEqual(headers["global-key"], "global-value"); assert.strictEqual(headers["extends-key"], "extends-value"); assert.strictEqual(headers["x-acs-version"], "2022-06-01"); @@ -396,7 +412,7 @@ describe('$openapi', function () { config.endpoint = `127.0.0.1:${port}`; let client = new OpenApi(config); let request = createOpenApiRequest(); - let params = new $OpenApi.Params({ + let params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -412,7 +428,7 @@ describe('$openapi', function () { assert.strictEqual(headers["raw-body"], "key1=value&key2=1&key3=true"); let regexp = /Action=TestAPI&Format=json&Version=2022-06-01&Timestamp=.+&SignatureNonce=.+&global-query=global-value&key1=value&key2=1&key3=true/; assert.ok(regexp.test(headers["raw-query"])); - assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/1 config.userAgent")); + assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/2 config.userAgent")); assert.strictEqual(headers["global-key"], "global-value"); assert.strictEqual(headers["extends-key"], "extends-value"); assert.strictEqual(headers["x-acs-version"], "2022-06-01"); @@ -439,7 +455,7 @@ describe('$openapi', function () { config.endpoint = `127.0.0.1:${port}`; let client = new OpenApi(config); let request = createOpenApiRequest(); - let params = new $OpenApi.Params({ + let params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -454,7 +470,7 @@ describe('$openapi', function () { let headers = result["headers"]; assert.strictEqual(headers["raw-body"], "key1=value&key2=1&key3=true"); assert.strictEqual(headers["raw-query"], "global-query=global-value&key1=value&key2=1&key3=true"); - assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/1 config.userAgent")); + assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/2 config.userAgent")); assert.strictEqual(headers["x-acs-version"], "2022-06-01"); assert.strictEqual(headers["x-acs-action"], "TestAPI"); assert.strictEqual(headers["content-type"], "application/x-www-form-urlencoded"); @@ -515,7 +531,7 @@ describe('$openapi', function () { config.signatureAlgorithm = "v2"; config.endpoint = `127.0.0.1:${port}`; client = new OpenApi(config); - params = new $OpenApi.Params({ + params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -560,7 +576,7 @@ describe('$openapi', function () { config.endpoint = `127.0.0.1:${port}`; let client = new OpenApi(config); let request = createOpenApiRequest(); - let params = new $OpenApi.Params({ + let params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -575,7 +591,7 @@ describe('$openapi', function () { let headers = result["headers"]; assert.strictEqual(headers["raw-body"], "{\"key1\":\"value\",\"key2\":1,\"key3\":true}"); assert.strictEqual(headers["raw-query"], "global-query=global-value&key1=value&key2=1&key3=true"); - assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/1 config.userAgent")); + assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/2 config.userAgent")); assert.strictEqual(headers["x-acs-version"], "2022-06-01"); assert.strictEqual(headers["x-acs-action"], "TestAPI"); assert.strictEqual(headers["content-type"], "application/json; charset=utf-8"); @@ -607,7 +623,7 @@ describe('$openapi', function () { config.endpoint = `127.0.0.1:${port}`; let client = new OpenApi(config); let request = createOpenApiRequest(); - let params = new $OpenApi.Params({ + let params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -622,7 +638,7 @@ describe('$openapi', function () { let headers = result["headers"]; assert.strictEqual(headers["raw-body"], "key1=value&key2=1&key3=true"); assert.strictEqual(headers["raw-query"], "global-query=global-value&key1=value&key2=1&key3=true"); - assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/1 config.userAgent")); + assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/2 config.userAgent")); assert.strictEqual(headers["x-acs-version"], "2022-06-01"); assert.strictEqual(headers["x-acs-action"], "TestAPI"); assert.strictEqual(headers["content-type"], "application/x-www-form-urlencoded"); @@ -688,7 +704,7 @@ describe('$openapi', function () { config.endpoint = `127.0.0.1:${port}`; let client = new OpenApi(config); let request = createOpenApiRequest(); - let params = new $OpenApi.Params({ + let params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -703,7 +719,7 @@ describe('$openapi', function () { let headers = result["headers"]; assert.strictEqual(headers["raw-body"], "{\"key1\":\"value\",\"key2\":1,\"key3\":true}"); assert.strictEqual(headers["raw-query"], "global-query=global-value&key1=value&key2=1&key3=true"); - assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/1 config.userAgent")); + assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/2 config.userAgent")); assert.strictEqual(headers["x-acs-version"], "2022-06-01"); assert.strictEqual(headers["x-acs-action"], "TestAPI"); assert.strictEqual(headers["content-type"], "application/json; charset=utf-8"); @@ -733,7 +749,7 @@ describe('$openapi', function () { config.endpoint = `127.0.0.1:${port}`; let client = new OpenApi(config); let request = createOpenApiRequest(); - let params = new $OpenApi.Params({ + let params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -748,7 +764,7 @@ describe('$openapi', function () { let headers = result["headers"]; assert.strictEqual(headers["raw-body"], "key1=value&key2=1&key3=true"); assert.strictEqual(headers["raw-query"], "global-query=global-value&key1=value&key2=1&key3=true"); - assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/1 config.userAgent")); + assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/2 config.userAgent")); assert.strictEqual(headers["x-acs-version"], "2022-06-01"); assert.strictEqual(headers["x-acs-action"], "TestAPI"); assert.strictEqual(headers["content-type"], "application/x-www-form-urlencoded"); @@ -813,7 +829,7 @@ describe('$openapi', function () { config.endpoint = `127.0.0.1:${port}`; let client = new OpenApi(config); let request = createOpenApiRequest(); - let params = new $OpenApi.Params({ + let params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -828,7 +844,7 @@ describe('$openapi', function () { let headers = result["headers"]; assert.strictEqual(headers["raw-body"], "{\"key1\":\"value\",\"key2\":1,\"key3\":true}"); assert.strictEqual(headers["raw-query"], "global-query=global-value&key1=value&key2=1&key3=true"); - assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/1 config.userAgent")); + assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/2 config.userAgent")); assert.strictEqual(headers["x-acs-version"], "2022-06-01"); assert.strictEqual(headers["x-acs-action"], "TestAPI"); assert.strictEqual(headers["content-type"], "application/json; charset=utf-8"); @@ -850,10 +866,81 @@ describe('$openapi', function () { assert.strictEqual(result["statusCode"], 200); }); + it("call api for SSE With V3Sign AK should ok", async function () { + let config = createConfig(); + let runtime = createRuntimeOptions(); + config.protocol = "HTTP"; + let port = (server.address() as AddressInfo).port; + config.endpoint = `127.0.0.1:${port}`; + let client = new OpenApi(config); + let request = createOpenApiRequest(); + let params = new $OpenApiUtil.Params({ + action: "TestAPI", + version: "2022-06-01", + protocol: "HTTPS", + pathname: "/sse", + method: "POST", + authType: "AK", + style: "ROA", + reqBodyType: "json", + bodyType: "sse", + }); + let result = client.callSSEApi(params, request, runtime); + const events: $dara.SSEEvent[] = []; + for await (const event of result) { + let headers = event["headers"]; + assert.strictEqual(headers["raw-body"], "{\"key1\":\"value\",\"key2\":1,\"key3\":true}"); + assert.strictEqual(headers["raw-query"], "global-query=global-value&key1=value&key2=1&key3=true"); + assert.ok(String(headers["user-agent"]).endsWith("TeaDSL/2 config.userAgent")); + assert.strictEqual(headers["x-acs-version"], "2022-06-01"); + assert.strictEqual(headers["x-acs-action"], "TestAPI"); + assert.strictEqual(headers["content-type"], "application/json; charset=utf-8"); + assert.strictEqual(headers["x-acs-request-id"], "A45EE076-334D-5012-9746-A8F828D20FD4"); + assert.strictEqual(headers["http-method"], "POST"); + assert.strictEqual(headers["pathname"], "/sse"); + assert.strictEqual(headers["connection"], "keep-alive"); + assert.strictEqual(headers["for-test"], "sdk"); + assert.strictEqual(headers["global-key"], "global-value"); + assert.strictEqual(headers["extends-key"], "extends-value"); + assert.ok(headers["x-acs-signature-nonce"].length > 0); + assert.ok(headers["x-acs-date"].length > 0); + assert.strictEqual(headers["accept"], "application/json"); + events.push(event.event); + } + assert.strictEqual(events.length, 5); + + assert.deepStrictEqual([new $dara.SSEEvent({ + data: '{"count":0}', + event: 'flow', + id: 'sse-test', + retry: 3, + }), new $dara.SSEEvent({ + data: '{"count":1}', + event: 'flow', + id: 'sse-test', + retry: 3, + }), new $dara.SSEEvent({ + data: '{"count":2}', + event: 'flow', + id: 'sse-test', + retry: 3, + }), new $dara.SSEEvent({ + data: '{"count":3}', + event: 'flow', + id: 'sse-test', + retry: 3, + }), new $dara.SSEEvent({ + data: '{"count":4}', + event: 'flow', + id: 'sse-test', + retry: 3, + })], events); + }); + it("response body should ok", async function () { let config = createConfig(); let runtime = createRuntimeOptions(); - let extendsParameters = new $Util.ExtendsParameters(); + let extendsParameters = new $dara.ExtendsParameters(); extendsParameters.headers = runtime.extendsParameters?.headers || {}; extendsParameters.headers['bodyType'] = 'json'; runtime.extendsParameters = extendsParameters; @@ -863,7 +950,7 @@ describe('$openapi', function () { config.endpoint = `127.0.0.1:${port}`; let client = new OpenApi(config); let request = createOpenApiRequest(); - let params = new $OpenApi.Params({ + let params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -928,7 +1015,7 @@ describe('$openapi', function () { runtime.extendsParameters = extendsParameters; params.bodyType = "binary"; result = await client.callApi(params, request, runtime); - body = await Util.readAsBytes(result["body"]); + body = await $dara.Stream.readAsBytes(result["body"]); assert.ok(body instanceof Buffer); assert.strictEqual(body.toString(), "{\"AppId\":\"test\", \"ClassId\":\"test\", \"UserId\":123}"); assert.strictEqual(result["statusCode"], 200); @@ -978,7 +1065,7 @@ describe('$openapi', function () { port = (server.address() as AddressInfo).port; config.endpoint = `127.0.0.1:${port}`; client = new OpenApi(config); - params = new $OpenApi.Params({ + params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -1049,7 +1136,7 @@ describe('$openapi', function () { runtime.extendsParameters = extendsParameters; params.bodyType = "binary"; result = await client.callApi(params, request, runtime); - body = await Util.readAsBytes(result["body"]); + body = await $dara.Stream.readAsBytes(result["body"]); assert.ok(body instanceof Buffer); assert.strictEqual(body.toString(), "{\"AppId\":\"test\", \"ClassId\":\"test\", \"UserId\":123}"); assert.strictEqual(result["statusCode"], 200); @@ -1099,7 +1186,7 @@ describe('$openapi', function () { port = (server.address() as AddressInfo).port; config.endpoint = `127.0.0.1:${port}`; client = new OpenApi(config); - params = new $OpenApi.Params({ + params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -1170,7 +1257,7 @@ describe('$openapi', function () { runtime.extendsParameters = extendsParameters; params.bodyType = "binary"; result = await client.callApi(params, request, runtime); - body = await Util.readAsBytes(result["body"]); + body = await $dara.Stream.readAsBytes(result["body"]); assert.ok(body instanceof Buffer); assert.strictEqual(body.toString(), "{\"AppId\":\"test\", \"ClassId\":\"test\", \"UserId\":123}"); assert.strictEqual(result["statusCode"], 200); @@ -1221,7 +1308,7 @@ describe('$openapi', function () { config.endpoint = `127.0.0.1:${port}`; config.signatureAlgorithm = undefined; client = new OpenApi(config); - params = new $OpenApi.Params({ + params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -1292,7 +1379,7 @@ describe('$openapi', function () { runtime.extendsParameters = extendsParameters; params.bodyType = "binary"; result = await client.callApi(params, request, runtime); - body = await Util.readAsBytes(result["body"]); + body = await $dara.Stream.readAsBytes(result["body"]); assert.ok(body instanceof Buffer); assert.strictEqual(body.toString(), "{\"AppId\":\"test\", \"ClassId\":\"test\", \"UserId\":123}"); assert.strictEqual(result["statusCode"], 200); @@ -1349,7 +1436,7 @@ describe('$openapi', function () { config.endpoint = `127.0.0.1:${port}`; let client = new OpenApi(config); // formData - let params = new $OpenApi.Params({ + let params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -1364,7 +1451,7 @@ describe('$openapi', function () { body["key1"] = "value"; body["key2"] = 1; body["key3"] = true; - let request = new $OpenApi.OpenApiRequest({ + let request = new $OpenApiUtil.OpenApiRequest({ body: OpenApiUtil.parseToMap(body), }); let result = await client.callApi(params, request, runtime); @@ -1381,8 +1468,8 @@ describe('$openapi', function () { // byte params.reqBodyType = "byte"; - let byteBody = Util.toBytes("test byte"); - request = new $OpenApi.OpenApiRequest({ + let byteBody = Buffer.from("test byte"); + request = new $OpenApiUtil.OpenApiRequest({ body: byteBody, }); result = await client.callApi(params, request, runtime); @@ -1392,7 +1479,7 @@ describe('$openapi', function () { // stream params.reqBodyType = "binary"; - request = new $OpenApi.OpenApiRequest({ + request = new $OpenApiUtil.OpenApiRequest({ stream: new BytesReadable(byteBody), }); result = await client.callApi(params, request, runtime); @@ -1408,9 +1495,9 @@ describe('$openapi', function () { runtime.maxAttempts = 1; runtime.backoffPolicy = "fix"; runtime.backoffPeriod = 1; - runtime.connectTimeout = 10; + runtime.connectTimeout = 100; runtime.readTimeout = 10; - let extendsParameters = new $Util.ExtendsParameters(); + let extendsParameters = new $dara.ExtendsParameters(); extendsParameters.headers = runtime.extendsParameters?.headers || {}; extendsParameters.headers['timeout'] = 'true'; runtime.extendsParameters = extendsParameters; @@ -1421,7 +1508,7 @@ describe('$openapi', function () { let client = new OpenApi(config); let request = createOpenApiRequest(); - let params = new $OpenApi.Params({ + let params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -1439,7 +1526,7 @@ describe('$openapi', function () { assert.ok(error.message.indexOf('ReadTimeout(10)') !== -1); } - params = new $OpenApi.Params({ + params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -1457,7 +1544,7 @@ describe('$openapi', function () { assert.ok(error.message.indexOf('ReadTimeout(10)') !== -1); } - params = new $OpenApi.Params({ + params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -1477,7 +1564,7 @@ describe('$openapi', function () { config.signatureAlgorithm = undefined; client = new OpenApi(config); - params = new $OpenApi.Params({ + params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -1497,7 +1584,7 @@ describe('$openapi', function () { client._productId = "test"; client.setGatewayClient(new POP()); - params = new $OpenApi.Params({ + params = new $OpenApiUtil.Params({ action: "TestAPI", version: "2022-06-01", protocol: "HTTPS", @@ -1517,4 +1604,4 @@ describe('$openapi', function () { }); -}); +}); \ No newline at end of file diff --git a/utils.dara b/utils.dara new file mode 100644 index 0000000..76a7e62 --- /dev/null +++ b/utils.dara @@ -0,0 +1,224 @@ +@clientName("Utils") +@overwrite(false) +/** + * This is for OpenApi Util + */ +import Credential; + +model GlobalParameters { + headers?: map[string]string, + queries?: map[string]string, +} + + +/** + * Model for initing client + */ +model Config { + accessKeyId?: string(description='accesskey id',default=''), + accessKeySecret?: string(description='accesskey secret',default=''), + securityToken?: string(description='security token',example='',default=''), + bearerToken?: string(description='bearer token',example='the-bearer-token',default=''), + protocol?: string(description='http protocol',example='http',default='http'), + method?: string(description='http method',example='GET',default=''), + regionId?: string(description='region id',example='cn-hangzhou',default=''), + readTimeout?: integer(description='read timeout',example='10',default=''), + connectTimeout?: integer(description='connect timeout',example='10',default=''), + httpProxy?: string(description='http proxy',example='http://localhost',default=''), + httpsProxy?: string(description='https proxy',example='https://localhost',default=''), + credential?: Credential(description='credential',example='',default=''), + endpoint?: string(description='endpoint',example='cs.aliyuncs.com',default=''), + noProxy?: string(description='proxy white list',example='http://localhost',default=''), + maxIdleConns?: integer(description='max idle conns',example='3',default=''), + network?: string(description='network for endpoint',example='public',default=''), + userAgent?: string(description='user agent',example='Alibabacloud/1',default=''), + suffix?: string(description='suffix for endpoint',example='aliyun',default=''), + socks5Proxy?: string(description='socks5 proxy',default=''), + socks5NetWork?: string(description='socks5 network',example='TCP',default=''), + endpointType?: string(description='endpoint type',example='internal',default=''), + openPlatformEndpoint?: string(description='OpenPlatform endpoint',example='openplatform.aliyuncs.com',default=''), + type?: string(description='credential type',example='access_key',default='',deprecated=true), + signatureVersion?: string(description='Signature Version',example='v1',default=''), + signatureAlgorithm?: string(description='Signature Algorithm',example='ACS3-HMAC-SHA256',default=''), + globalParameters?: GlobalParameters(description='Global Parameters'), + key?: string(description='privite key for client certificate', example='MIIEvQ',default=''), + cert?: string(description='client certificate', example='-----BEGIN CERTIFICATE-----\nxxx-----END CERTIFICATE-----',default=''), + ca?: string(description='server certificate', example='-----BEGIN CERTIFICATE-----\nxxx-----END CERTIFICATE-----',default=''), + disableHttp2?: boolean(description='disable HTTP/2', example='false'), + retryOptions?: $RetryOptions(description='retry options'), +} + + +model Params = { + action: string, + version: string, + protocol: string, + pathname: string, + method: string, + authType: string, + bodyType: string, + reqBodyType: string, + style?: string +} + + +model OpenApiRequest { + headers?: map[string]string, + query?: map[string]string, + body?: any, + stream?: readable, + hostMap?: map[string]string, + endpointOverride?: string, +} + +/** + * Convert all params of body other than type of readable into content + * @param body source Model + * @param content target Model + * @return void + */ +static function convert(body: $Model, content: $Model): void; + + +/** + * If endpointType is internal, use internal endpoint + * If serverUse is true and endpointType is accelerate, use accelerate endpoint + * Default return endpoint + * @param serverUse whether use accelerate endpoint + * @param endpointType value must be internal or accelerate + * @return the final endpoint + */ +static function getEndpoint(endpoint: string, serverUse: boolean, endpointType: string): string; + +/** + * Get throttling param + * @param the response headers + * @return time left + */ +static function getThrottlingTimeLeft(headers: map[string]string): long; + +/** + * Hash the raw data with signatureAlgorithm + * @param raw hashing data + * @param signatureAlgorithm the autograph method + * @return hashed bytes + */ +static function hash(raw: bytes, signatureAlgorithm: string): bytes; + +/** + * Get throttling param + * @param the response headers + * @return time left + */ +static function flatMap(params: map[string]any, prefix: string): map[string]string; + +/** + * Generate a nonce string + * @return the nonce string + */ +static function getNonce(): string; + +/** + * Get the string to be signed according to request + * @param request which contains signed messages + * @return the signed string + */ +static function getStringToSign(request: $Request): string; + +/** + * Get signature according to stringToSign, secret + * @param stringToSign the signed string + * @param secret accesskey secret + * @return the signature + */ +static function getROASignature(stringToSign: string, secret: string): string; + +/** + * Parse filter into a form string + * @param filter object + * @return the string + */ +static function toForm(filter: object): string; + +/** + * Get timestamp + * @return the timestamp string + */ +static function getTimestamp(): string; + + +/** + * Get UTC string + * @return the UTC string + */ +static function getDateUTCString(): string; + +/** + * Parse filter into a object which's type is map[string]string + * @param filter query param + * @return the object + */ +static function query(filter: object): map[string]string; + +/** + * Get signature according to signedParams, method and secret + * @param signedParams params which need to be signed + * @param method http method e.g. GET + * @param secret AccessKeySecret + * @return the signature + */ +static function getRPCSignature(signedParams: map[string]string, method: string, secret: string): string; + +/** + * Parse array into a string with specified style + * @param array the array + * @param prefix the prefix string + * @style specified style e.g. repeatList + * @return the string + */ +static function arrayToStringWithSpecifiedStyle(array: any, prefix: string, style: string): string; + +/** + * Stringify the value of map + * @return the new stringified map + */ +static function stringifyMapValue(m: map[string]any): map[string]string; + +/** + * Transform input as array. + */ +static function toArray(input: any): [ map[string]any ]; + +/** + * Parse map with flat style + * + * @param any the input + * @return any + */ +static function mapToFlatStyle(input: any): any; + +/** + * Transform input as map. + */ +static function parseToMap(input: any): map[string]any; + + +/** + * Get the authorization + * @param request request params + * @param signatureAlgorithm the autograph method + * @param payload the hashed request + * @param accesskey the accesskey string + * @param accessKeySecret the accessKeySecret string + * @return authorization string + */ +static function getAuthorization(request: $Request, signatureAlgorithm: string, payload: string, accesskey: string, accessKeySecret: string): string; + + +static function getUserAgent(userAgent: string): string; + +/** + * Get endpoint according to productId, regionId, endpointType, network and suffix + * @return endpoint + */ +static function getEndpointRules(product: string, regionId: string, endpointType: string, network: string, suffix: string) throws: string; \ No newline at end of file