From 7a01b3d99c2cb74e22b502d33af8491c33e2aae8 Mon Sep 17 00:00:00 2001 From: yini-chen Date: Thu, 6 Jun 2024 14:37:36 +0800 Subject: [PATCH 1/5] fix: fixed icons of request params --- media/package.json | 2 +- media/src/components/APIPage/API.tsx | 21 ++++++ media/yarn.lock | 98 ++++++++++++---------------- package.json | 1 - 4 files changed, 63 insertions(+), 59 deletions(-) diff --git a/media/package.json b/media/package.json index 1c641d9..3b31612 100644 --- a/media/package.json +++ b/media/package.json @@ -48,7 +48,7 @@ "@vitejs/plugin-react": "^1.3.2", "autoprefixer": "^10.0.1", "eslint": "^8", - "eslint-config-next": "14.2.3", + "eslint-config-next": "14.1.4", "less": "^4.2.0", "postcss": "^8", "prettier": "^3.2.5", diff --git a/media/src/components/APIPage/API.tsx b/media/src/components/APIPage/API.tsx index ec5424e..3c3c036 100644 --- a/media/src/components/APIPage/API.tsx +++ b/media/src/components/APIPage/API.tsx @@ -157,6 +157,27 @@ export const API: React.FC = (props) => { { + return ( +
{ + onExpand(node); + }} + > + +
+ ); + }} renderEmpty={() => { return ( diff --git a/media/yarn.lock b/media/yarn.lock index 55859c1..660e199 100644 --- a/media/yarn.lock +++ b/media/yarn.lock @@ -651,10 +651,10 @@ resolved "https://registry.npmmirror.com/@next/env/-/env-14.0.4.tgz#d5cda0c4a862d70ae760e58c0cd96a8899a2e49a" integrity sha512-irQnbMLbUNQpP1wcE5NstJtbuA/69kRfzBrpAD7Gsn8zm/CY6YQYc3HQBz8QPxwISG26tIm5afvvVbu508oBeQ== -"@next/eslint-plugin-next@14.2.3": - version "14.2.3" - resolved "https://registry.yarnpkg.com/@next/eslint-plugin-next/-/eslint-plugin-next-14.2.3.tgz#287ad8620e7061ba01e8d3313d464db6d217b6df" - integrity sha512-L3oDricIIjgj1AVnRdRor21gI7mShlSwU/1ZGHmqM3LzHhXXhdkrfeNY5zif25Bi5Dd7fiJHsbhoZCHfXYvlAw== +"@next/eslint-plugin-next@14.1.4": + version "14.1.4" + resolved "https://registry.npmmirror.com/@next/eslint-plugin-next/-/eslint-plugin-next-14.1.4.tgz#d7372b5ffede0e466af8af2ff534386418827fc8" + integrity sha512-n4zYNLSyCo0Ln5b7qxqQeQ34OZKXwgbdcx6kmkQbywr+0k6M3Vinft0T72R6CDAcDrne2IAgSud4uWCzFgc5HA== dependencies: glob "10.3.10" @@ -936,37 +936,37 @@ resolved "https://registry.npmmirror.com/@types/vscode/-/vscode-1.85.0.tgz#46beb07f0f626665b52d1e2294382b2bc63b602e" integrity sha512-CF/RBon/GXwdfmnjZj0WTUMZN5H6YITOfBCP4iEZlOtVQXuzw6t7Le7+cR+7JzdMrnlm7Mfp49Oj2TuSXIWo3g== -"@typescript-eslint/parser@^5.4.2 || ^6.0.0 || 7.0.0 - 7.2.0": - version "7.2.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-7.2.0.tgz#44356312aea8852a3a82deebdacd52ba614ec07a" - integrity sha512-5FKsVcHTk6TafQKQbuIVkXq58Fnbkd2wDL4LB7AURN7RUOu1utVP+G8+6u3ZhEroW3DF6hyo3ZEXxgKgp4KeCg== +"@typescript-eslint/parser@^5.4.2 || ^6.0.0": + version "6.21.0" + resolved "https://registry.npmmirror.com/@typescript-eslint/parser/-/parser-6.21.0.tgz#af8fcf66feee2edc86bc5d1cf45e33b0630bf35b" + integrity sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ== dependencies: - "@typescript-eslint/scope-manager" "7.2.0" - "@typescript-eslint/types" "7.2.0" - "@typescript-eslint/typescript-estree" "7.2.0" - "@typescript-eslint/visitor-keys" "7.2.0" + "@typescript-eslint/scope-manager" "6.21.0" + "@typescript-eslint/types" "6.21.0" + "@typescript-eslint/typescript-estree" "6.21.0" + "@typescript-eslint/visitor-keys" "6.21.0" debug "^4.3.4" -"@typescript-eslint/scope-manager@7.2.0": - version "7.2.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-7.2.0.tgz#cfb437b09a84f95a0930a76b066e89e35d94e3da" - integrity sha512-Qh976RbQM/fYtjx9hs4XkayYujB/aPwglw2choHmf3zBjB4qOywWSdt9+KLRdHubGcoSwBnXUH2sR3hkyaERRg== +"@typescript-eslint/scope-manager@6.21.0": + version "6.21.0" + resolved "https://registry.npmmirror.com/@typescript-eslint/scope-manager/-/scope-manager-6.21.0.tgz#ea8a9bfc8f1504a6ac5d59a6df308d3a0630a2b1" + integrity sha512-OwLUIWZJry80O99zvqXVEioyniJMa+d2GrqpUTqi5/v5D5rOrppJVBPa0yKCblcigC0/aYAzxxqQ1B+DS2RYsg== dependencies: - "@typescript-eslint/types" "7.2.0" - "@typescript-eslint/visitor-keys" "7.2.0" + "@typescript-eslint/types" "6.21.0" + "@typescript-eslint/visitor-keys" "6.21.0" -"@typescript-eslint/types@7.2.0": - version "7.2.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-7.2.0.tgz#0feb685f16de320e8520f13cca30779c8b7c403f" - integrity sha512-XFtUHPI/abFhm4cbCDc5Ykc8npOKBSJePY3a3s+lwumt7XWJuzP5cZcfZ610MIPHjQjNsOLlYK8ASPaNG8UiyA== +"@typescript-eslint/types@6.21.0": + version "6.21.0" + resolved "https://registry.npmmirror.com/@typescript-eslint/types/-/types-6.21.0.tgz#205724c5123a8fef7ecd195075fa6e85bac3436d" + integrity sha512-1kFmZ1rOm5epu9NZEZm1kckCDGj5UJEf7P1kliH4LKu/RkwpsfqqGmY2OOcUs18lSlQBKLDYBOGxRVtrMN5lpg== -"@typescript-eslint/typescript-estree@7.2.0": - version "7.2.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-7.2.0.tgz#5beda2876c4137f8440c5a84b4f0370828682556" - integrity sha512-cyxS5WQQCoBwSakpMrvMXuMDEbhOo9bNHHrNcEWis6XHx6KF518tkF1wBvKIn/tpq5ZpUYK7Bdklu8qY0MsFIA== +"@typescript-eslint/typescript-estree@6.21.0": + version "6.21.0" + resolved "https://registry.npmmirror.com/@typescript-eslint/typescript-estree/-/typescript-estree-6.21.0.tgz#c47ae7901db3b8bddc3ecd73daff2d0895688c46" + integrity sha512-6npJTkZcO+y2/kr+z0hc4HwNfrrP4kNYh57ek7yCNlrBjWQ1Y0OS7jiZTkgumrvkX5HkEKXFZkkdFNkaW2wmUQ== dependencies: - "@typescript-eslint/types" "7.2.0" - "@typescript-eslint/visitor-keys" "7.2.0" + "@typescript-eslint/types" "6.21.0" + "@typescript-eslint/visitor-keys" "6.21.0" debug "^4.3.4" globby "^11.1.0" is-glob "^4.0.3" @@ -974,12 +974,12 @@ semver "^7.5.4" ts-api-utils "^1.0.1" -"@typescript-eslint/visitor-keys@7.2.0": - version "7.2.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-7.2.0.tgz#5035f177752538a5750cca1af6044b633610bf9e" - integrity sha512-c6EIQRHhcpl6+tO8EMR+kjkkV+ugUNXOmeASA1rlzkd8EPIriavpWoiEz1HR/VLhbVIdhqnV6E7JZm00cBDx2A== +"@typescript-eslint/visitor-keys@6.21.0": + version "6.21.0" + resolved "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-6.21.0.tgz#87a99d077aa507e20e238b11d56cc26ade45fe47" + integrity sha512-JJtkDduxLi9bivAB+cYOVMtbkqdPOhZ+ZI5LC47MIRrDV4Yn2o+ZnW10Nkmr28xRpSpdJ6Sm42Hjf2+REYXm0A== dependencies: - "@typescript-eslint/types" "7.2.0" + "@typescript-eslint/types" "6.21.0" eslint-visitor-keys "^3.4.1" "@uiw/copy-to-clipboard@~1.0.12": @@ -2328,14 +2328,14 @@ escape-string-regexp@^5.0.0: resolved "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz#4683126b500b61762f2dbebace1806e8be31b1c8" integrity sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw== -eslint-config-next@14.2.3: - version "14.2.3" - resolved "https://registry.yarnpkg.com/eslint-config-next/-/eslint-config-next-14.2.3.tgz#2fb0f7c4eccda530a4b5054438162b2303786d4f" - integrity sha512-ZkNztm3Q7hjqvB1rRlOX8P9E/cXRL9ajRcs8jufEtwMfTVYRqnmtnaSu57QqHyBlovMuiB8LEzfLBkh5RYV6Fg== +eslint-config-next@14.1.4: + version "14.1.4" + resolved "https://registry.npmmirror.com/eslint-config-next/-/eslint-config-next-14.1.4.tgz#22f2ba4c0993e991249d863656a64c204bae542c" + integrity sha512-cihIahbhYAWwXJwZkAaRPpUi5t9aOi/HdfWXOjZeUOqNWXHD8X22kd1KG58Dc3MVaRx3HoR/oMGk2ltcrqDn8g== dependencies: - "@next/eslint-plugin-next" "14.2.3" + "@next/eslint-plugin-next" "14.1.4" "@rushstack/eslint-patch" "^1.3.3" - "@typescript-eslint/parser" "^5.4.2 || ^6.0.0 || 7.0.0 - 7.2.0" + "@typescript-eslint/parser" "^5.4.2 || ^6.0.0" eslint-import-resolver-node "^0.3.6" eslint-import-resolver-typescript "^3.5.2" eslint-plugin-import "^2.28.1" @@ -5665,16 +5665,7 @@ string-convert@^0.2.0: resolved "https://registry.npmmirror.com/string-convert/-/string-convert-0.2.1.tgz#6982cc3049fbb4cd85f8b24568b9d9bf39eeff97" integrity sha512-u/1tdPl4yQnPBjnVrmdLo9gtuLvELKsAoRapekWggdiQNvvvum+jYF329d84NAa660KQw7pB2n36KrIKVoXa3A== -"string-width-cjs@npm:string-width@^4.2.0": - version "4.2.3" - resolved "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" - integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== - dependencies: - emoji-regex "^8.0.0" - is-fullwidth-code-point "^3.0.0" - strip-ansi "^6.0.1" - -string-width@^4.1.0: +"string-width-cjs@npm:string-width@^4.2.0", string-width@^4.1.0: version "4.2.3" resolved "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== @@ -5745,14 +5736,7 @@ string_decoder@^1.1.1: dependencies: safe-buffer "~5.2.0" -"strip-ansi-cjs@npm:strip-ansi@^6.0.1": - version "6.0.1" - resolved "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" - integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== - dependencies: - ansi-regex "^5.0.1" - -strip-ansi@^6.0.0, strip-ansi@^6.0.1: +"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1: version "6.0.1" resolved "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== diff --git a/package.json b/package.json index 90539a9..03d17cc 100644 --- a/package.json +++ b/package.json @@ -284,7 +284,6 @@ "@types/fs-extra": "^5.1.0", "@types/lodash": "^4.14.182", "@types/mocha": "^10.0.3", - "@types/node": "18.x", "@types/react": "^18.0.8", "@types/react-dom": "^18.0.3", "@types/vscode": "^1.47.0", From a8d67d2b68121c9d9ed9f9534ace71fcfe431f51 Mon Sep 17 00:00:00 2001 From: yini-chen Date: Tue, 11 Jun 2024 16:57:34 +0800 Subject: [PATCH 2/5] feat: add user agent in headers --- src/Service.ts | 23 +++-- src/openApiService/lib/client.ts | 155 ++++++++++++++++--------------- src/plugins/generate.ts | 38 +++++--- src/productExplorer.ts | 13 ++- 4 files changed, 127 insertions(+), 102 deletions(-) diff --git a/src/Service.ts b/src/Service.ts index e2c8b73..35a057a 100644 --- a/src/Service.ts +++ b/src/Service.ts @@ -145,19 +145,21 @@ export class AlicloudAPIService { * @description 根据 API 查询是否有 CodeSample */ async requestSamplesByAPI(product: string, version: string, api: string) { - const resStr = await fetch( - `https://api.aliyun.com/api/samples/product/${product}/version/${version}/api/${api}`, - {}, - ).then((res) => res.text()); + const resStr = await fetch(`https://api.aliyun.com/api/samples/product/${product}/version/${version}/api/${api}`, { + headers: { + "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + }, + }).then((res) => res.text()); const res = JSON.parse(resStr); return res?.data || []; } async requestEndpoints(product: string) { - const resStr = await fetch( - `https://api.aliyun.com/meta/v1/products/${product}/endpoints.json?language=zh-CN`, - {}, - ).then((res) => res.text()); + const resStr = await fetch(`https://api.aliyun.com/meta/v1/products/${product}/endpoints.json?language=zh-CN`, { + headers: { + "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + }, + }).then((res) => res.text()); const res = JSON.parse(resStr); return res?.data?.endpoints || []; } @@ -256,7 +258,10 @@ export class AlicloudAPIService { const resStr = await fetch(`https://api.aliyun.com/api/product/makeCode`, { method: "post", body: JSON.stringify(body), - headers: { "Content-Type": "application/json" }, + headers: { + "Content-Type": "application/json", + "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + }, }).then((res) => res.text()); const res = JSON.parse(resStr); return res; diff --git a/src/openApiService/lib/client.ts b/src/openApiService/lib/client.ts index 8fcb8d6..9013c20 100644 --- a/src/openApiService/lib/client.ts +++ b/src/openApiService/lib/client.ts @@ -1,10 +1,12 @@ -'use strict'; +"use strict"; -const { default: OpenApiUtil } = require('@alicloud/openapi-util'); -const { default: Util } = require('@alicloud/tea-util'); -const $Credential = require('@alicloud/credentials'); -const $tea = require('@alicloud/tea-typescript'); -const { default: Credential } = require('@alicloud/credentials'); +const { default: OpenApiUtil } = require("@alicloud/openapi-util"); +const { default: Util } = require("@alicloud/tea-util"); +const $Credential = require("@alicloud/credentials"); +const $tea = require("@alicloud/tea-typescript"); +const { default: Credential } = require("@alicloud/credentials"); +const vscode = require("vscode"); +const os = require("os"); export class OpenAPIClient { private _credential: any; @@ -25,7 +27,7 @@ export class OpenAPIClient { constructor(config) { if (Util.isUnset($tea.toMap(config))) { throw $tea.newError({ - code: 'ParameterMissing', + code: "ParameterMissing", message: "'config' can not be unset", }); } @@ -34,9 +36,9 @@ export class OpenAPIClient { this._credential = config.credential; } else if (!Util.empty(config.accessKeyId) && !Util.empty(config.accessKeySecret)) { if (!Util.empty(config.securityToken)) { - config.type = 'sts'; + config.type = "sts"; } else { - config.type = 'access_key'; + config.type = "access_key"; } let credentialConfig = new $Credential.Config({ @@ -66,7 +68,7 @@ export class OpenAPIClient { async getAccessKeyId() { if (Util.isUnset(this._credential)) { - return ''; + return ""; } let accessKeyId = await this._credential.getAccessKeyId(); @@ -79,7 +81,7 @@ export class OpenAPIClient { */ async getAccessKeySecret() { if (Util.isUnset(this._credential)) { - return ''; + return ""; } let secret = await this._credential.getAccessKeySecret(); @@ -88,7 +90,7 @@ export class OpenAPIClient { async getSecurityToken() { if (Util.isUnset(this._credential)) { - return ''; + return ""; } let token = await this._credential.getSecurityToken(); @@ -105,7 +107,7 @@ export class OpenAPIClient { async doRequest(params, request, runtime) { let _runtime = { - timeouted: 'retry', + timeouted: "retry", readTimeout: Util.defaultNumber(runtime.readTimeout, this._readTimeout), connectTimeout: Util.defaultNumber(runtime.connectTimeout, this._connectTimeout), httpProxy: Util.defaultString(runtime.httpProxy, this._httpProxy), @@ -117,7 +119,7 @@ export class OpenAPIClient { maxAttempts: Util.defaultNumber(runtime.maxAttempts, 3), }, backoff: { - policy: Util.defaultString(runtime.backoffPolicy, 'no'), + policy: Util.defaultString(runtime.backoffPolicy, "no"), period: Util.defaultNumber(runtime.backoffPeriod, 1), }, ignoreSSL: runtime.ignoreSSL, @@ -126,9 +128,9 @@ export class OpenAPIClient { let _lastRequest = null; let _now = Date.now(); let _retryTimes = 0; - while ($tea.allowRetry(_runtime['retry'], _retryTimes, _now)) { + while ($tea.allowRetry(_runtime["retry"], _retryTimes, _now)) { if (_retryTimes > 0) { - let _backoffTime = $tea.getBackoffTime(_runtime['backoff'], _retryTimes); + let _backoffTime = $tea.getBackoffTime(_runtime["backoff"], _retryTimes); if (_backoffTime > 0) { await $tea.sleep(_backoffTime); } @@ -145,139 +147,143 @@ export class OpenAPIClient { // endpoint is setted in product client request_.headers = { host: this._endpoint, - 'x-acs-version': params.version, - 'x-acs-action': params.action, - 'user-agent': 'Alibaba Cloud API Toolkit', - 'x-acs-date': OpenApiUtil.getTimestamp(), - 'x-acs-signature-nonce': Util.getNonce(), - accept: 'application/json', + "x-acs-version": params.version, + "x-acs-action": params.action, + "user-agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "x-acs-date": OpenApiUtil.getTimestamp(), + "x-acs-signature-nonce": Util.getNonce(), + accept: "application/json", ...request.headers, }; - if (request.headers && request.headers['Host']) { - delete request_.headers['Host']; - request_.headers['host'] = request.headers['Host']; + if (request.headers && request.headers["Host"]) { + delete request_.headers["Host"]; + request_.headers["host"] = request.headers["Host"]; } - let signatureAlgorithm = Util.defaultString(this._signatureAlgorithm, 'ACS3-HMAC-SHA256'); - let hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(Util.toBytes(''), signatureAlgorithm)); + 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); - request_.headers['content-type'] = 'application/octet-stream'; - } - else { + request_.headers["content-type"] = "application/octet-stream"; + } else { if (!Util.isUnset(request.body)) { - if (Util.equalString(params.reqBodyType, 'json')) { + 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); - request_.headers['content-type'] = 'application/json; charset=utf-8'; - } - else { + request_.headers["content-type"] = "application/json; charset=utf-8"; + } else { let m = Util.assertAsMap(request.body); let formObj = OpenApiUtil.toForm(m); hashedRequestPayload = OpenApiUtil.hexEncode(OpenApiUtil.hash(Util.toBytes(formObj), signatureAlgorithm)); request_.body = new $tea.BytesReadable(formObj); - request_.headers['content-type'] = 'application/x-www-form-urlencoded'; + request_.headers["content-type"] = "application/x-www-form-urlencoded"; } } } - request_.headers['x-acs-content-sha256'] = hashedRequestPayload; - if (!Util.equalString(params.authType, 'Anonymous')) { + request_.headers["x-acs-content-sha256"] = hashedRequestPayload; + if (!Util.equalString(params.authType, "Anonymous")) { let accessKeyId = await this.getAccessKeyId(); let accessKeySecret = await this.getAccessKeySecret(); let securityToken = await this.getSecurityToken(); if (!Util.empty(securityToken)) { - request_.headers['x-acs-accesskey-id'] = accessKeyId; - request_.headers['x-acs-security-token'] = 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, + accessKeyId, + accessKeySecret, + ); } - request_.headers['host'] = this._endpoint; - if (request.headers && request.headers['Host']) { - request_.headers['Host'] = request.headers['Host']; + request_.headers["host"] = this._endpoint; + if (request.headers && request.headers["Host"]) { + request_.headers["Host"] = request.headers["Host"]; } _lastRequest = request_; - console.log("_lastRequest",_lastRequest) - + console.log("_lastRequest", _lastRequest); + let response_ = await $tea.doAction(request_, _runtime); - entry = { + entry = { request: { - headers: request_.headers + headers: request_.headers, }, response: { statusCode: response_.statusCode, headers: response_.headers, - } + }, }; if (Util.is4xx(response_.statusCode) || Util.is5xx(response_.statusCode)) { let _res = await Util.readAsJSON(response_.body); let err = Util.assertAsMap(_res); return { - format: 'json', + format: "json", result: err, - entry + entry, }; } - if (response_.statusCode === 204 && (Util.isUnset(response_.headers['content-type']) || Util.isUnset(response_.headers['content-length']))) { + if ( + response_.statusCode === 204 && + (Util.isUnset(response_.headers["content-type"]) || Util.isUnset(response_.headers["content-length"])) + ) { let str = await Util.readAsString(response_.body); return { - format: 'string', + format: "string", result: str, - entry + entry, }; } - if (Util.equalString(params.bodyType, 'binary')) { + if (Util.equalString(params.bodyType, "binary")) { return { - format: 'binary', + format: "binary", result: response_.body, - entry + entry, }; - } else if (Util.equalString(params.bodyType, 'byte')) { + } else if (Util.equalString(params.bodyType, "byte")) { let byt = await Util.readAsBytes(response_.body); return { - format: 'byte', + format: "byte", result: byt, - entry + entry, }; - } else if (Util.equalString(params.bodyType, 'string')) { + } else if (Util.equalString(params.bodyType, "string")) { let str = await Util.readAsString(response_.body); return { - format: 'string', + format: "string", result: str, - entry + entry, }; - } else if (Util.equalString(params.bodyType, 'json')) { + } else if (Util.equalString(params.bodyType, "json")) { let obj = await Util.readAsJSON(response_.body); let res = Util.assertAsMap(obj); return { - format: 'json', + format: "json", result: res, - entry + entry, }; - } else if (Util.equalString(params.bodyType, 'array')) { + } else if (Util.equalString(params.bodyType, "array")) { let arr = await Util.readAsJSON(response_.body); return { - format: 'json', + format: "json", result: arr, - entry + entry, }; - } + } let str = await Util.readAsString(response_.body); return { - format: 'string', + format: "string", result: str, - entry + entry, }; - - } catch (ex) { if ($tea.isRetryable(ex)) { continue; @@ -291,6 +297,5 @@ export class OpenAPIClient { } } - exports.Client = OpenAPIClient; export default OpenAPIClient; diff --git a/src/plugins/generate.ts b/src/plugins/generate.ts index f4fcd56..d88e144 100644 --- a/src/plugins/generate.ts +++ b/src/plugins/generate.ts @@ -4,6 +4,8 @@ import { PontSpec } from "pontx-spec"; import { InnerOriginConfig, PontManager } from "pontx-manager"; import { getRequiredParamsValue } from "../utils"; import fetch from "node-fetch"; +import * as vscode from "vscode"; +import os from "os"; const mySnippetsProvider: SnippetsProvider = (info) => { return []; @@ -22,7 +24,14 @@ const myGetFilesBySpecs: GetFilesBySpecs = async (origins) => { return fileStructure; }; -const codeSampleProvider = async (info:{language:string,product:string,version:string,apiName:string,params?:any, simplify?:boolean}):Promise => { +const codeSampleProvider = async (info: { + language: string; + product: string; + version: string; + apiName: string; + params?: any; + simplify?: boolean; +}): Promise => { const body = { apiName: info?.apiName, apiVersion: info?.version, @@ -40,25 +49,26 @@ const codeSampleProvider = async (info:{language:string,product:string,version:s const makeCodeStr = await fetch(`https://api.aliyun.com/api/product/makeCode`, { method: "post", body: JSON.stringify(body), - headers: { "Content-Type": "application/json" }, + headers: { + "Content-Type": "application/json", + "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + }, }).then((res) => res.text()); const sdkDemos = JSON.parse(makeCodeStr); - const asyncFetchedCodes = (Object.keys(sdkDemos?.data?.demoSdk || {}))?.map( - (key)=>{ - return { - name: key, - language: key, - code: sdkDemos?.data?.demoSdk[key]?.codeSample, - importList: sdkDemos?.data?.demoSdk[key]?.importList - } - } - ) + const asyncFetchedCodes = Object.keys(sdkDemos?.data?.demoSdk || {})?.map((key) => { + return { + name: key, + language: key, + code: sdkDemos?.data?.demoSdk[key]?.codeSample, + importList: sdkDemos?.data?.demoSdk[key]?.importList, + }; + }); return asyncFetchedCodes || []; -} +}; export const AlicloudApiMetaGeneratePlugin: any = createPontxGeneratePlugin({ snippetsProvider: mySnippetsProvider, getFilesBySpecs: myGetFilesBySpecs, }); -export { getFilesBySpecs, snippetsProvider,codeSampleProvider }; +export { getFilesBySpecs, snippetsProvider, codeSampleProvider }; diff --git a/src/productExplorer.ts b/src/productExplorer.ts index c9f4b87..9256cdf 100644 --- a/src/productExplorer.ts +++ b/src/productExplorer.ts @@ -1,5 +1,7 @@ import { Product } from "./types"; import fetch from "node-fetch"; +import * as vscode from "vscode"; +import os from "os"; let productRequest = null; @@ -7,8 +9,12 @@ export class ProductExplorer { products: Array; async requestProducts() { - const productsResponse = await fetch("https://api.aliyun.com/meta/v1/products", {}).then((res) => res.text()); - this.products = JSON.parse(productsResponse); + const productsResponse = await fetch("https://api.aliyun.com/meta/v1/products", { + headers: { + "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + }, + }).then((res) => res.text()); + this.products = JSON.parse(productsResponse); return JSON.parse(productsResponse); } @@ -29,9 +35,8 @@ function createProductRequestInstance() { } export function getProductRequestInstance(): ProductExplorer { - if (!productRequest) { productRequest = createProductRequestInstance(); } - return productRequest + return productRequest; } From d15bd1fdf68e251163ee96f3a81dd9254565ebf4 Mon Sep 17 00:00:00 2001 From: yini-chen Date: Tue, 11 Jun 2024 17:23:53 +0800 Subject: [PATCH 3/5] feat: add user agent in headers --- src/Service.ts | 6 +++--- src/openApiService/lib/client.ts | 2 +- src/plugins/generate.ts | 2 +- src/productExplorer.ts | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Service.ts b/src/Service.ts index 35a057a..1778c0e 100644 --- a/src/Service.ts +++ b/src/Service.ts @@ -147,7 +147,7 @@ export class AlicloudAPIService { async requestSamplesByAPI(product: string, version: string, api: string) { const resStr = await fetch(`https://api.aliyun.com/api/samples/product/${product}/version/${version}/api/${api}`, { headers: { - "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, }, }).then((res) => res.text()); const res = JSON.parse(resStr); @@ -157,7 +157,7 @@ export class AlicloudAPIService { async requestEndpoints(product: string) { const resStr = await fetch(`https://api.aliyun.com/meta/v1/products/${product}/endpoints.json?language=zh-CN`, { headers: { - "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, }, }).then((res) => res.text()); const res = JSON.parse(resStr); @@ -260,7 +260,7 @@ export class AlicloudAPIService { body: JSON.stringify(body), headers: { "Content-Type": "application/json", - "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, }, }).then((res) => res.text()); const res = JSON.parse(resStr); diff --git a/src/openApiService/lib/client.ts b/src/openApiService/lib/client.ts index 9013c20..0d7d555 100644 --- a/src/openApiService/lib/client.ts +++ b/src/openApiService/lib/client.ts @@ -149,7 +149,7 @@ export class OpenAPIClient { host: this._endpoint, "x-acs-version": params.version, "x-acs-action": params.action, - "user-agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "user-agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, "x-acs-date": OpenApiUtil.getTimestamp(), "x-acs-signature-nonce": Util.getNonce(), accept: "application/json", diff --git a/src/plugins/generate.ts b/src/plugins/generate.ts index d88e144..5a785f0 100644 --- a/src/plugins/generate.ts +++ b/src/plugins/generate.ts @@ -51,7 +51,7 @@ const codeSampleProvider = async (info: { body: JSON.stringify(body), headers: { "Content-Type": "application/json", - "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, }, }).then((res) => res.text()); const sdkDemos = JSON.parse(makeCodeStr); diff --git a/src/productExplorer.ts b/src/productExplorer.ts index 9256cdf..68b6a37 100644 --- a/src/productExplorer.ts +++ b/src/productExplorer.ts @@ -11,7 +11,7 @@ export class ProductExplorer { async requestProducts() { const productsResponse = await fetch("https://api.aliyun.com/meta/v1/products", { headers: { - "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, }, }).then((res) => res.text()); this.products = JSON.parse(productsResponse); From 3870df7544e61a4dc3340713641e810a28d49358 Mon Sep 17 00:00:00 2001 From: yini-chen Date: Wed, 12 Jun 2024 09:59:58 +0800 Subject: [PATCH 4/5] fix: getUserAgent --- src/Service.ts | 8 ++++---- src/openApiService/lib/client.ts | 4 +++- src/plugins/generate.ts | 6 ++---- src/productExplorer.ts | 3 ++- src/utils.ts | 25 +++++++++++++++---------- 5 files changed, 26 insertions(+), 20 deletions(-) diff --git a/src/Service.ts b/src/Service.ts index 1778c0e..b101440 100644 --- a/src/Service.ts +++ b/src/Service.ts @@ -6,7 +6,7 @@ import { PontSpec } from "pontx-spec"; import { PontAPIExplorer, AlicloudApiExplorer } from "./explorer"; import { AlicloudApiCommands } from "./commands"; import * as _ from "lodash"; -import { batchDispose, getFormatValues, showProgress, VSCodeLogger } from "./utils"; +import { batchDispose, getFormatValues, getUserAgent, showProgress, VSCodeLogger } from "./utils"; import { request } from "./openApiService/request/request"; import fs from "fs"; import fsx from "fs/promises"; @@ -147,7 +147,7 @@ export class AlicloudAPIService { async requestSamplesByAPI(product: string, version: string, api: string) { const resStr = await fetch(`https://api.aliyun.com/api/samples/product/${product}/version/${version}/api/${api}`, { headers: { - "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "User-Agent": getUserAgent(), }, }).then((res) => res.text()); const res = JSON.parse(resStr); @@ -157,7 +157,7 @@ export class AlicloudAPIService { async requestEndpoints(product: string) { const resStr = await fetch(`https://api.aliyun.com/meta/v1/products/${product}/endpoints.json?language=zh-CN`, { headers: { - "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "User-Agent": getUserAgent(), }, }).then((res) => res.text()); const res = JSON.parse(resStr); @@ -260,7 +260,7 @@ export class AlicloudAPIService { body: JSON.stringify(body), headers: { "Content-Type": "application/json", - "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "User-Agent": getUserAgent(), }, }).then((res) => res.text()); const res = JSON.parse(resStr); diff --git a/src/openApiService/lib/client.ts b/src/openApiService/lib/client.ts index 0d7d555..593310d 100644 --- a/src/openApiService/lib/client.ts +++ b/src/openApiService/lib/client.ts @@ -1,5 +1,7 @@ "use strict"; +import { getUserAgent } from "../../utils"; + const { default: OpenApiUtil } = require("@alicloud/openapi-util"); const { default: Util } = require("@alicloud/tea-util"); const $Credential = require("@alicloud/credentials"); @@ -149,7 +151,7 @@ export class OpenAPIClient { host: this._endpoint, "x-acs-version": params.version, "x-acs-action": params.action, - "user-agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "user-agent": getUserAgent(), "x-acs-date": OpenApiUtil.getTimestamp(), "x-acs-signature-nonce": Util.getNonce(), accept: "application/json", diff --git a/src/plugins/generate.ts b/src/plugins/generate.ts index 5a785f0..23f3915 100644 --- a/src/plugins/generate.ts +++ b/src/plugins/generate.ts @@ -2,10 +2,8 @@ import { getFilesBySpecs, snippetsProvider } from "pontx-sdk-plugin-core"; import { createPontxGeneratePlugin, SnippetsProvider, PontxGeneratorPlugin, GetFilesBySpecs } from "pontx-generate"; import { PontSpec } from "pontx-spec"; import { InnerOriginConfig, PontManager } from "pontx-manager"; -import { getRequiredParamsValue } from "../utils"; +import { getRequiredParamsValue, getUserAgent } from "../utils"; import fetch from "node-fetch"; -import * as vscode from "vscode"; -import os from "os"; const mySnippetsProvider: SnippetsProvider = (info) => { return []; @@ -51,7 +49,7 @@ const codeSampleProvider = async (info: { body: JSON.stringify(body), headers: { "Content-Type": "application/json", - "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "User-Agent": getUserAgent(), }, }).then((res) => res.text()); const sdkDemos = JSON.parse(makeCodeStr); diff --git a/src/productExplorer.ts b/src/productExplorer.ts index 68b6a37..80bd44c 100644 --- a/src/productExplorer.ts +++ b/src/productExplorer.ts @@ -2,6 +2,7 @@ import { Product } from "./types"; import fetch from "node-fetch"; import * as vscode from "vscode"; import os from "os"; +import { getUserAgent } from "./utils"; let productRequest = null; @@ -11,7 +12,7 @@ export class ProductExplorer { async requestProducts() { const productsResponse = await fetch("https://api.aliyun.com/meta/v1/products", { headers: { - "User-Agent": `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`, + "User-Agent": getUserAgent(), }, }).then((res) => res.text()); this.products = JSON.parse(productsResponse); diff --git a/src/utils.ts b/src/utils.ts index 2aa892c..247e07f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -11,6 +11,7 @@ import { alicloudAPIMessageService } from "./Service"; import { AlicloudApiCommands } from "./commands"; import { AlicloudApiExplorer } from "./explorer"; const configSchema = require("pontx-spec/configSchema.json"); +import os from "os"; const { createServerContent } = require("../media/lib/index"); @@ -59,8 +60,8 @@ export const findAlicloudAPIConfig = async (context: vscode.ExtensionContext) => url: product.url, }; }), - } - if(!_.isEqual(publicConfig, oldConfig)){ + }; + if (!_.isEqual(publicConfig, oldConfig)) { const publicConfigUint8Array = new Uint8Array(Buffer.from(JSON.stringify(publicConfig), "utf-8")); await vscode.workspace.fs.writeFile(pontxConfigUri, publicConfigUint8Array); } @@ -512,13 +513,13 @@ export type SpecInfo = { }; export const getSpecInfoFromName = (name: string): SpecInfo => { - if(typeof name !== "string" ){ + if (typeof name !== "string") { return { product: "", - version: "" - } + version: "", + }; } - if ((name).includes("::")) { + if (name.includes("::")) { return { product: name.split("::")[0], version: name.split("::")[1], @@ -536,7 +537,11 @@ export const getSpecInfoFromName = (name: string): SpecInfo => { }; }; -export const formatName = (name:string):string => { - const {product, version} = getSpecInfoFromName(name) - return `${product}__${version}` -} +export const formatName = (name: string): string => { + const { product, version } = getSpecInfoFromName(name); + return `${product}__${version}`; +}; + +export const getUserAgent = () => { + return `Toolkit (${os.type()}; ${os.release()}) alibababcloud-api-toolkit/${vscode.extensions.getExtension("alibabacloud-openapi.vscode-alicloud-api").packageJSON.version} VS Code/${vscode.version}`; +}; From f234439f9b304b4558eb611061fad7f502f9b96a Mon Sep 17 00:00:00 2001 From: yini-chen Date: Wed, 12 Jun 2024 10:15:23 +0800 Subject: [PATCH 5/5] fix: type error --- media/src/components/APIPage/APIDocument/ApiErrorCode.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/media/src/components/APIPage/APIDocument/ApiErrorCode.tsx b/media/src/components/APIPage/APIDocument/ApiErrorCode.tsx index be95bc9..11afee1 100644 --- a/media/src/components/APIPage/APIDocument/ApiErrorCode.tsx +++ b/media/src/components/APIPage/APIDocument/ApiErrorCode.tsx @@ -47,7 +47,6 @@ export const ApiErrorCode: React.FC = (props) => { | React.ReactElement> | Iterable // import isEmpty from 'lodash/isEmpty' | React.ReactPortal - | React.PromiseLikeOfReactNode | null | undefined, index: any,