diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml index fa2795c8f..5f9e868b3 100644 --- a/.github/sync-repo-settings.yaml +++ b/.github/sync-repo-settings.yaml @@ -11,9 +11,9 @@ branchProtectionRules: - docs - lint-gax - lint-tools - - test-gax (14) + - test-gax (18) - test-gax (16) - - test-tools (14) + - test-tools (18) - test-tools (16) - cla/google - windows-gax diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index c686ad3bd..acb365ab3 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [14, 16] + node: [18, 20] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -30,7 +30,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [14, 16] + node: [18, 16] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -51,7 +51,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [14, 16] + node: [18, 20] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -72,7 +72,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [14, 16] + node: [18, 20] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -95,7 +95,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd gax; npm install - run: cd gax; npm test env: @@ -106,7 +106,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd tools; npm install - run: cd tools; npm test env: @@ -117,7 +117,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd logging-utils; npm install - run: cd logging-utils; npm test env: @@ -128,7 +128,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd gax; npm install - run: cd gax; npm run lint lint-tools: @@ -137,7 +137,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd tools; npm install - run: cd tools; npm run lint lint-logging-utils: @@ -146,7 +146,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd logging-utils; npm install - run: cd logging-utils; npm run lint docs: @@ -155,7 +155,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 - run: cd gax; npm install - run: cd gax; npm run docs - uses: JustinBeckwith/linkinator-action@v1 diff --git a/.kokoro/common.cfg b/.kokoro/common.cfg index bda58c77b..a205e8ffe 100644 --- a/.kokoro/common.cfg +++ b/.kokoro/common.cfg @@ -16,7 +16,7 @@ build_file: "gax-nodejs/.kokoro/trampoline_v2.sh" # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } env_vars: { key: "TRAMPOLINE_BUILD_FILE" diff --git a/.kokoro/continuous/node14/common.cfg b/.kokoro/continuous/node14/common.cfg deleted file mode 100644 index bda58c77b..000000000 --- a/.kokoro/continuous/node14/common.cfg +++ /dev/null @@ -1,24 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "gax-nodejs/.kokoro/trampoline_v2.sh" - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" -} -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/test.sh" -} diff --git a/.kokoro/continuous/node14/lint.cfg b/.kokoro/continuous/node14/lint.cfg deleted file mode 100644 index 018ec7aa0..000000000 --- a/.kokoro/continuous/node14/lint.cfg +++ /dev/null @@ -1,4 +0,0 @@ -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/lint.sh" -} diff --git a/.kokoro/continuous/node14/samples-test.cfg b/.kokoro/continuous/node14/samples-test.cfg deleted file mode 100644 index 3fb9c46ca..000000000 --- a/.kokoro/continuous/node14/samples-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/samples-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/continuous/node14/system-test.cfg b/.kokoro/continuous/node14/system-test.cfg deleted file mode 100644 index 8a980142a..000000000 --- a/.kokoro/continuous/node14/system-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/system-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/continuous/node14/test.cfg b/.kokoro/continuous/node14/test.cfg deleted file mode 100644 index e69de29bb..000000000 diff --git a/.kokoro/presubmit/node14/common.cfg b/.kokoro/presubmit/node14/common.cfg deleted file mode 100644 index bda58c77b..000000000 --- a/.kokoro/presubmit/node14/common.cfg +++ /dev/null @@ -1,24 +0,0 @@ -# Format: //devtools/kokoro/config/proto/build.proto - -# Build logs will be here -action { - define_artifacts { - regex: "**/*sponge_log.xml" - } -} - -# Download trampoline resources. -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" - -# Use the trampoline script to run in docker. -build_file: "gax-nodejs/.kokoro/trampoline_v2.sh" - -# Configure the docker image for kokoro-trampoline. -env_vars: { - key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" -} -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/test.sh" -} diff --git a/.kokoro/presubmit/node14/samples-test.cfg b/.kokoro/presubmit/node14/samples-test.cfg deleted file mode 100644 index 3fb9c46ca..000000000 --- a/.kokoro/presubmit/node14/samples-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/samples-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/presubmit/node14/system-test.cfg b/.kokoro/presubmit/node14/system-test.cfg deleted file mode 100644 index 8a980142a..000000000 --- a/.kokoro/presubmit/node14/system-test.cfg +++ /dev/null @@ -1,12 +0,0 @@ -# Download resources for system tests (service account key, etc.) -gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" - -env_vars: { - key: "TRAMPOLINE_BUILD_FILE" - value: "github/gax-nodejs/.kokoro/system-test.sh" -} - -env_vars: { - key: "SECRET_MANAGER_KEYS" - value: "long-door-651-kokoro-system-test-service-account" -} \ No newline at end of file diff --git a/.kokoro/presubmit/node14/test.cfg b/.kokoro/presubmit/node14/test.cfg deleted file mode 100644 index e69de29bb..000000000 diff --git a/.kokoro/release/docs.cfg b/.kokoro/release/docs.cfg index e83e720e8..7256aba7a 100644 --- a/.kokoro/release/docs.cfg +++ b/.kokoro/release/docs.cfg @@ -11,7 +11,7 @@ before_action { # doc publications use a Python image. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } # Download trampoline resources. diff --git a/.kokoro/release/publish.cfg b/.kokoro/release/publish.cfg index 6e0e6efc9..f2b47538f 100644 --- a/.kokoro/release/publish.cfg +++ b/.kokoro/release/publish.cfg @@ -30,7 +30,7 @@ build_file: "gax-nodejs/.kokoro/trampoline_v2.sh" # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/node:14-user" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" } env_vars: { diff --git a/.kokoro/samples-test.sh b/.kokoro/samples-test.sh index 8c5d108cb..c1cb0fc77 100755 --- a/.kokoro/samples-test.sh +++ b/.kokoro/samples-test.sh @@ -56,7 +56,7 @@ fi # codecov combines coverage across integration and unit tests. Include # the logic below for any environment you wish to collect coverage for: -COVERAGE_NODE=14 +COVERAGE_NODE=18 if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then NYC_BIN=./node_modules/nyc/bin/nyc.js if [ -f "$NYC_BIN" ]; then diff --git a/.kokoro/system-test.sh b/.kokoro/system-test.sh index 1f6a2f6ac..1a7df166e 100755 --- a/.kokoro/system-test.sh +++ b/.kokoro/system-test.sh @@ -51,7 +51,7 @@ npm run system-test # codecov combines coverage across integration and unit tests. Include # the logic below for any environment you wish to collect coverage for: -COVERAGE_NODE=14 +COVERAGE_NODE=18 if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then NYC_BIN=./node_modules/nyc/bin/nyc.js if [ -f "$NYC_BIN" ]; then diff --git a/.kokoro/test.bat b/.kokoro/test.bat index 0bb124052..baa52982b 100644 --- a/.kokoro/test.bat +++ b/.kokoro/test.bat @@ -21,7 +21,7 @@ cd .. @rem we upgrade Node.js in the image: SET PATH=%PATH%;/cygdrive/c/Program Files/nodejs/npm -call nvm use v14.17.3 +call nvm use v18 call which node call npm install || goto :error diff --git a/.kokoro/test.sh b/.kokoro/test.sh index 862d478d3..0d9f6392a 100755 --- a/.kokoro/test.sh +++ b/.kokoro/test.sh @@ -39,7 +39,7 @@ npm test # codecov combines coverage across integration and unit tests. Include # the logic below for any environment you wish to collect coverage for: -COVERAGE_NODE=14 +COVERAGE_NODE=18 if npx check-node-version@3.3.0 --silent --node $COVERAGE_NODE; then NYC_BIN=./node_modules/nyc/bin/nyc.js if [ -f "$NYC_BIN" ]; then diff --git a/gax/.eslintignore b/gax/.eslintignore index ea5b04aeb..07a7bd357 100644 --- a/gax/.eslintignore +++ b/gax/.eslintignore @@ -5,3 +5,7 @@ build/ docs/ protos/ samples/generated/ +test/browser-test/ +test/showcase-echo-client/src/ +test/showcase-server/ +test/test-application/src/ \ No newline at end of file diff --git a/gax/package.json b/gax/package.json index dece0f0cd..014e25a12 100644 --- a/gax/package.json +++ b/gax/package.json @@ -10,61 +10,60 @@ "!build/src/**/*.map" ], "dependencies": { - "@grpc/grpc-js": "^1.10.9", + "@grpc/grpc-js": "^1.12.6", "@grpc/proto-loader": "^0.7.13", "@types/long": "^5.0.0", "abort-controller": "^3.0.0", - "duplexify": "^4.0.0", - "google-auth-library": "^9.3.0", - "node-fetch": "^2.7.0", + "duplexify": "^4.1.3", + "google-auth-library": "^9.15.1", + "node-fetch": "^3.3.2", "object-hash": "^3.0.0", - "proto3-json-serializer": "^2.0.2", - "retry-request": "^7.0.0", - "uuid": "^9.0.1", - "protobufjs": "^7.3.2" + "proto3-json-serializer": "^3.0.0", + "protobufjs": "^7.4.0", + "retry-request": "^8.0.0" }, "devDependencies": { - "@types/uuid": "^9.0.7", "@babel/plugin-proposal-private-methods": "^7.18.6", - "@types/mocha": "^9.0.0", - "@types/ncp": "^2.0.1", + "@types/mocha": "^10.0.10", + "@types/ncp": "^2.0.8", "@types/node": "^20.5.0", - "@types/node-fetch": "^2.6.11", - "@types/object-hash": "^3.0.0", - "@types/proxyquire": "^1.3.28", - "@types/pumpify": "^1.4.1", - "@types/sinon": "^17.0.0", - "@types/uglify-js": "^3.17.0", - "c8": "^9.0.0", - "cheerio": "1.0.0-rc.12", - "codecov": "^3.1.0", + "@types/node-fetch": "^2.6.12", + "@types/object-hash": "^3.0.6", + "@types/proxyquire": "^1.3.31", + "@types/pumpify": "^1.4.4", + "@types/sinon": "^17.0.3", + "@types/uglify-js": "^3.17.5", + "assert": "^2.1.0", + "c8": "^10.1.3", + "cheerio": "^1.0.0", + "codecov": "^3.8.3", "execa": "^5.0.0", "glob": "10.4.5", "google-proto-files": "^4.2.0", - "gts": "^5.0.0", - "jackspeak": "3.4.3", - "jsdoc": "^4.0.0", + "gts": "^6.0.2", + "jackspeak": "^3.0.2", + "jsdoc": "^4.0.4", "jsdoc-fresh": "^3.0.0", "jsdoc-region-tag": "^3.0.0", - "linkinator": "^4.0.0", - "lru-cache": "10.4.3", - "long": "^5.0.0", - "mkdirp": "^2.0.0", - "mocha": "^9.0.0", + "linkinator": "^6.1.2", + "long": "^5.2.4", + "lru-cache": "^10.0.0", + "mkdirp": "^3.0.1", + "mocha": "^11.1.0", "ncp": "^2.0.0", - "null-loader": "^4.0.0", - "pdfmake": "0.2.12", - "protobufjs-cli": "1.1.3", - "proxyquire": "^2.0.1", - "pumpify": "^2.0.0", - "sinon": "^18.0.0", - "stream-events": "^1.0.4", + "null-loader": "^4.0.1", + "pdfmake": "^0.2.18", + "protobufjs-cli": "^1.1.3", + "proxyquire": "^2.1.3", + "pumpify": "^2.0.1", + "sinon": "^19.0.2", + "stream-events": "^1.0.5", "ts-loader": "^8.0.0", - "typescript": "^5.1.6", - "uglify-js": "^3.17.0", - "walkdir": "^0.4.0", - "webpack": "^4.0.0", - "webpack-cli": "^4.0.0" + "typescript": "^5.7.3", + "uglify-js": "^3.19.3", + "walkdir": "^0.4.1", + "webpack": "^5.97.1", + "webpack-cli": "^6.0.1" }, "scripts": { "docs": "jsdoc -c .jsdoc.js", @@ -95,6 +94,12 @@ "keywords": [ "grpc" ], + "exports": { + ".": "./build/src/index.js", + "./fallback": "./build/src/fallback.js", + "./gax": "./build/src/gax.js", + "./build/src/protobuf": "./build/src/protobuf.js" + }, "repository": { "type": "git", "url": "https://github.com/googleapis/gax-nodejs.git", @@ -107,7 +112,7 @@ }, "homepage": "https://github.com/googleapis/gax-nodejs#readme", "engines": { - "node": ">=14" + "node": ">=18" }, "browser": "build/src/fallback.js" } diff --git a/gax/samples/package.json b/gax/samples/package.json index fe458a230..525850957 100644 --- a/gax/samples/package.json +++ b/gax/samples/package.json @@ -3,7 +3,7 @@ "license": "Apache-2.0", "author": "Google LLC", "engines": { - "node": ">=10" + "node": ">=18" }, "repository": "googleapis/gax-nodejs", "private": true, @@ -20,4 +20,4 @@ "c8": "^9.0.0", "mocha": "^9.0.0" } -} +} \ No newline at end of file diff --git a/gax/samples/pagination.js b/gax/samples/pagination.js index ad8ca6d97..a175bf34b 100644 --- a/gax/samples/pagination.js +++ b/gax/samples/pagination.js @@ -54,14 +54,14 @@ async function main() { const pageDescriptor = new gax.PageDescriptor( /* requestPageTokenField: */ 'pageToken', /* responsePageTokenField: */ 'nextPageToken', - /* resourceField: */ 'animals' + /* resourceField: */ 'animals', ); // Create API call: const wrappedFunction = gax.createApiCall( /* func: */ doStuff, /* settings: */ settings, - /* descriptor: */ pageDescriptor + /* descriptor: */ pageDescriptor, ); // Call it! diff --git a/gax/samples/quickstart.js b/gax/samples/quickstart.js index 35fc0bfd1..01463c8bb 100644 --- a/gax/samples/quickstart.js +++ b/gax/samples/quickstart.js @@ -45,7 +45,7 @@ async function main() { const settings = new gax.CallSettings(); settings.retry = gax.createRetryOptions( /* retryCodes: */ [42], - /* backoffSettings: */ gax.createDefaultBackoffSettings() + /* backoffSettings: */ gax.createDefaultBackoffSettings(), ); // and use createApiCall to get a promisifed function that handles retries! diff --git a/gax/src/apiCaller.ts b/gax/src/apiCaller.ts index 5c9590f1d..80857cb87 100644 --- a/gax/src/apiCaller.ts +++ b/gax/src/apiCaller.ts @@ -39,20 +39,20 @@ export interface APICaller { apiCall: SimpleCallbackFunction, argument: {}, settings: {}, - canceller: OngoingCallPromise | OngoingCall | StreamProxy + canceller: OngoingCallPromise | OngoingCall | StreamProxy, ): void; fail( canceller: OngoingCallPromise | OngoingCall | CancellableStream, - err: GoogleError + err: GoogleError, ): void; result( - canceller: OngoingCallPromise | OngoingCall | CancellableStream + canceller: OngoingCallPromise | OngoingCall | CancellableStream, ): CancellablePromise | CancellableStream; } export function createAPICaller( settings: CallSettings, - descriptor: Descriptor | undefined + descriptor: Descriptor | undefined, ): APICaller { if (!descriptor) { return new NormalApiCaller(); diff --git a/gax/src/apitypes.ts b/gax/src/apitypes.ts index 8a6d49087..6004cc63a 100644 --- a/gax/src/apitypes.ts +++ b/gax/src/apitypes.ts @@ -59,7 +59,7 @@ export type APICallback = ( err: GoogleError | null, response?: ResponseType, next?: NextPageRequestType, - rawResponse?: RawResponseType + rawResponse?: RawResponseType, ) => void; // The following five types mimic various gRPC calls (regular UnaryCall and @@ -68,21 +68,21 @@ export type UnaryCall = ( argument: {}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) => GRPCCallResult; export type ServerStreamingCall = ( argument: {}, metadata: {}, - options: {} + options: {}, ) => Duplex & GRPCCallResult; export type ClientStreamingCall = ( metadata: {}, options: {}, - callback?: APICallback + callback?: APICallback, ) => Duplex & GRPCCallResult; export type BiDiStreamingCall = ( metadata: {}, - options: {} + options: {}, ) => Duplex & GRPCCallResult; export type GRPCCall = | UnaryCall @@ -98,21 +98,21 @@ export interface GaxCallPromise { ( argument: {}, callOptions?: CallOptions, - callback?: APICallback + callback?: APICallback, ): CancellablePromise; } export interface GaxCallStream { ( argument: {}, callOptions?: CallOptions, - callback?: APICallback + callback?: APICallback, ): CancellableStream; } export interface GaxCall { ( argument: {}, callOptions?: CallOptions, - callback?: APICallback + callback?: APICallback, ): GaxCallResult; } export interface GRPCCallOtherArgs { diff --git a/gax/src/bundlingCalls/bundleApiCaller.ts b/gax/src/bundlingCalls/bundleApiCaller.ts index 78952a238..cb8c9097a 100644 --- a/gax/src/bundlingCalls/bundleApiCaller.ts +++ b/gax/src/bundlingCalls/bundleApiCaller.ts @@ -49,7 +49,7 @@ export class BundleApiCaller implements APICaller { apiCall: SimpleCallbackFunction, argument: {}, settings: CallSettings, - status: OngoingCallPromise + status: OngoingCallPromise, ) { if (!settings.isBundling) { throw new GoogleError('Bundling enabled with no isBundling!'); diff --git a/gax/src/bundlingCalls/bundleDescriptor.ts b/gax/src/bundlingCalls/bundleDescriptor.ts index cb6daad86..5765fe887 100644 --- a/gax/src/bundlingCalls/bundleDescriptor.ts +++ b/gax/src/bundlingCalls/bundleDescriptor.ts @@ -62,7 +62,7 @@ export class BundleDescriptor implements Descriptor { bundledField: string, requestDiscriminatorFields: string[], subresponseField: string | null, - byteLengthFunction: Function + byteLengthFunction: Function, ) { if (!byteLengthFunction && typeof subresponseField === 'function') { byteLengthFunction = subresponseField; @@ -80,7 +80,7 @@ export class BundleDescriptor implements Descriptor { return new NormalApiCaller(); } return new BundleApiCaller( - new BundleExecutor(settings.bundleOptions!, this) + new BundleExecutor(settings.bundleOptions!, this), ); } } diff --git a/gax/src/bundlingCalls/bundleExecutor.ts b/gax/src/bundlingCalls/bundleExecutor.ts index 21f7ffdb3..61c8dbb8e 100644 --- a/gax/src/bundlingCalls/bundleExecutor.ts +++ b/gax/src/bundlingCalls/bundleExecutor.ts @@ -86,7 +86,7 @@ export class BundleExecutor { */ constructor( bundleOptions: BundleOptions, - bundleDescriptor: BundleDescriptor + bundleDescriptor: BundleDescriptor, ) { this._options = bundleOptions; this._descriptor = bundleDescriptor; @@ -107,11 +107,11 @@ export class BundleExecutor { schedule( apiCall: SimpleCallbackFunction, request: {[index: string]: Array<{}> | string}, - callback?: TaskCallback + callback?: TaskCallback, ) { const bundleId = computeBundleId( request, - this._descriptor.requestDiscriminatorFields + this._descriptor.requestDiscriminatorFields, ); callback = (callback || noop) as TaskCallback; if (bundleId === undefined) { @@ -119,7 +119,7 @@ export class BundleExecutor { 'bundling_schedule_bundleid_undefined', 'The request does not have enough information for request bundling. ' + `Invoking immediately. Request: ${JSON.stringify(request)} ` + - `discriminator fields: ${this._descriptor.requestDiscriminatorFields}` + `discriminator fields: ${this._descriptor.requestDiscriminatorFields}`, ); return apiCall(request, callback); } @@ -127,7 +127,7 @@ export class BundleExecutor { warn( 'bundling_no_bundled_field', `Request does not contain field ${this._descriptor.bundledField} that must present for bundling. ` + - `Invoking immediately. Request: ${JSON.stringify(request)}` + `Invoking immediately. Request: ${JSON.stringify(request)}`, ); return apiCall(request, callback); } @@ -137,7 +137,7 @@ export class BundleExecutor { apiCall, request, this._descriptor.bundledField, - this._descriptor.subresponseField + this._descriptor.subresponseField, ); } let task = this._tasks[bundleId]; @@ -194,7 +194,7 @@ export class BundleExecutor { apiCall, request, this._descriptor.bundledField, - this._descriptor.subresponseField + this._descriptor.subresponseField, ); task = this._tasks[bundleId]; } diff --git a/gax/src/bundlingCalls/bundlingUtils.ts b/gax/src/bundlingCalls/bundlingUtils.ts index 20a04b029..e058f567e 100644 --- a/gax/src/bundlingCalls/bundlingUtils.ts +++ b/gax/src/bundlingCalls/bundlingUtils.ts @@ -33,7 +33,7 @@ import {RequestType} from '../apitypes'; */ export function computeBundleId( obj: RequestType, - discriminatorFields: string[] + discriminatorFields: string[], ) { const ids: unknown[] = []; let hasIds = false; diff --git a/gax/src/bundlingCalls/task.ts b/gax/src/bundlingCalls/task.ts index f4a72c583..c3dbafda9 100644 --- a/gax/src/bundlingCalls/task.ts +++ b/gax/src/bundlingCalls/task.ts @@ -54,7 +54,7 @@ export interface TaskCallback extends APICallback { export function deepCopyForResponse( // eslint-disable-next-line @typescript-eslint/no-explicit-any obj: any, - subresponseInfo: SubResponseInfo | null + subresponseInfo: SubResponseInfo | null, ) { // eslint-disable-next-line @typescript-eslint/no-explicit-any let result: any; @@ -91,7 +91,7 @@ export function deepCopyForResponse( // those subresponses are not shared among callbacks. result[key] = obj[key].slice( subresponseInfo.start, - subresponseInfo.end + subresponseInfo.end, ); } else { result[key] = deepCopyForResponse(obj[key], null); @@ -126,7 +126,7 @@ export class Task { apiCall: SimpleCallbackFunction, bundlingRequest: {}, bundledField: string, - subresponseField?: string | null + subresponseField?: string | null, ) { this._apiCall = apiCall; this._request = bundlingRequest; @@ -210,7 +210,7 @@ export class Task { self._data[i].callback(err, responses[i]); } } - } + }, ); return ids; } diff --git a/gax/src/call.ts b/gax/src/call.ts index b2fddacf0..8484e36d2 100644 --- a/gax/src/call.ts +++ b/gax/src/call.ts @@ -84,11 +84,11 @@ export class OngoingCall { err: GoogleError | null, response?: ResponseType, next?: NextPageRequestType, - rawResponse?: RawResponseType + rawResponse?: RawResponseType, ) => { this.completed = true; setImmediate(this.callback!, err, response, next, rawResponse); - } + }, ); if (canceller instanceof Promise) { canceller.catch(err => { @@ -113,14 +113,14 @@ export class OngoingCallPromise extends OngoingCall { */ constructor() { let resolveCallback: ( - result: [ResponseType, NextPageRequestType, RawResponseType] + result: [ResponseType, NextPageRequestType, RawResponseType], ) => void; let rejectCallback: (err: Error) => void; const callback: APICallback = ( err: GoogleError | null, response?: ResponseType, next?: NextPageRequestType, - rawResponse?: RawResponseType + rawResponse?: RawResponseType, ) => { if (err) { // If gRPC metadata exist, parsed google.rpc.status details. diff --git a/gax/src/clientInterface.ts b/gax/src/clientInterface.ts index 810892762..b9f3bd8b8 100644 --- a/gax/src/clientInterface.ts +++ b/gax/src/clientInterface.ts @@ -60,7 +60,7 @@ export interface Callback< err: Error | null | undefined, value?: ResponseObject | null, nextRequest?: NextRequestObject, - rawResponse?: RawResponseObject + rawResponse?: RawResponseObject, ): void; } @@ -80,7 +80,7 @@ export interface PaginationCallback< err: Error | null, values?: ResponseType[], nextPageRequest?: RequestObject, - rawResponse?: ResponseObject + rawResponse?: ResponseObject, ): void; } diff --git a/gax/src/createApiCall.ts b/gax/src/createApiCall.ts index e36b98e4e..b3fdee987 100644 --- a/gax/src/createApiCall.ts +++ b/gax/src/createApiCall.ts @@ -58,7 +58,7 @@ export function createApiCall( settings: CallSettings, descriptor?: Descriptor, // eslint-disable-next-line @typescript-eslint/no-unused-vars - _fallback?: boolean | 'proto' | 'rest' // unused here, used in fallback.ts implementation + _fallback?: boolean | 'proto' | 'rest', // unused here, used in fallback.ts implementation ): GaxCall { // we want to be able to accept both promise resolving to a function and a // function. Currently client librares are only calling this method with a @@ -70,7 +70,7 @@ export function createApiCall( return ( request: RequestType, callOptions?: CallOptions, - callback?: APICallback + callback?: APICallback, ) => { let currentApiCaller = apiCaller; @@ -81,7 +81,7 @@ export function createApiCall( // If Gax streaming retries are enabled, check settings passed at call time and convert parameters if needed const convertedRetryOptions = convertRetryOptions( callOptions, - gaxStreamingRetries + gaxStreamingRetries, ); thisSettings = settings.merge(convertedRetryOptions); } else { @@ -109,7 +109,7 @@ export function createApiCall( if (retry.retryCodes.length > 0 && retry.shouldRetryFn) { warn( 'either_retrycodes_or_shouldretryfn', - 'Only one of retryCodes or shouldRetryFn may be defined. Ignoring retryCodes.' + 'Only one of retryCodes or shouldRetryFn may be defined. Ignoring retryCodes.', ); retry.retryCodes = []; } @@ -119,19 +119,19 @@ export function createApiCall( retry.getResumptionRequestFn ) { throw new Error( - 'getResumptionRequestFn can only be used when gaxStreamingRetries is set to true.' + 'getResumptionRequestFn can only be used when gaxStreamingRetries is set to true.', ); } } if (!streaming && retry) { if (retry.shouldRetryFn) { throw new Error( - 'Using a function to determine retry eligibility is only supported with server streaming calls' + 'Using a function to determine retry eligibility is only supported with server streaming calls', ); } if (retry.getResumptionRequestFn) { throw new Error( - 'Resumption strategy can only be used with server streaming retries' + 'Resumption strategy can only be used with server streaming retries', ); } if (retry.retryCodes && retry.retryCodes.length > 0) { @@ -141,14 +141,14 @@ export function createApiCall( func, thisSettings.retry!, thisSettings.otherArgs as GRPCCallOtherArgs, - thisSettings.apiName + thisSettings.apiName, ); } } return addTimeoutArg( func, thisSettings.timeout, - thisSettings.otherArgs as GRPCCallOtherArgs + thisSettings.otherArgs as GRPCCallOtherArgs, ); }) .then((apiCall: SimpleCallbackFunction) => { diff --git a/gax/src/fallback.ts b/gax/src/fallback.ts index 9e779f027..0d156c879 100644 --- a/gax/src/fallback.ts +++ b/gax/src/fallback.ts @@ -15,7 +15,7 @@ */ import {OutgoingHttpHeaders} from 'http'; -import * as objectHash from 'object-hash'; +import objectHash from 'object-hash'; import * as protobuf from 'protobufjs'; import * as gax from './gax'; import * as routingHeader from './routingHeader'; @@ -126,13 +126,13 @@ export class GrpcClient { * A string is accepted for compatibility, all non-empty string values enable the HTTP REST fallback. */ fallback?: boolean | string; - } = {} + } = {}, ) { if (!isNodeJS()) { if (!options.auth) { throw new Error( JSON.stringify(options) + - 'You need to pass auth instance to use gRPC-fallback client in browser or other non-Node.js environments. Use OAuth2Client from google-auth-library.' + 'You need to pass auth instance to use gRPC-fallback client in browser or other non-Node.js environments. Use OAuth2Client from google-auth-library.', ); } this.auth = options.auth as OAuth2Client; @@ -196,7 +196,7 @@ export class GrpcClient { serviceName: string, clientConfig: gax.ClientConfig, configOverrides: gax.ClientConfig, - headers: OutgoingHttpHeaders + headers: OutgoingHttpHeaders, ) { function buildMetadata(abTests: {}, moreHeaders: OutgoingHttpHeaders) { const metadata: OutgoingHttpHeaders = {}; @@ -220,7 +220,7 @@ export class GrpcClient { )[0] ) { clientVersions.push( - ...(metadata[CLIENT_VERSION_HEADER] as string[])[0].split(' ') + ...(metadata[CLIENT_VERSION_HEADER] as string[])[0].split(' '), ); } clientVersions.push(`grpc-web/${version}`); @@ -244,7 +244,7 @@ export class GrpcClient { ).push(...value); } else { throw new Error( - `Can not add value ${value} to the call metadata.` + `Can not add value ${value} to the call metadata.`, ); } } @@ -260,7 +260,7 @@ export class GrpcClient { clientConfig, configOverrides, Status, - {metadataBuilder: buildMetadata} + {metadataBuilder: buildMetadata}, ); } @@ -280,7 +280,7 @@ export class GrpcClient { opts: ClientStubOptions, // For consistency with createStub in grpc.ts, customServicePath is defined: // eslint-disable-next-line @typescript-eslint/no-unused-vars - customServicePath?: boolean + customServicePath?: boolean, ) { if (!this.authClient) { if (this.auth && 'getClient' in this.auth) { @@ -300,7 +300,7 @@ export class GrpcClient { if (universeFromAuth && opts.universeDomain !== universeFromAuth) { throw new Error( `The configured universe domain (${opts.universeDomain}) does not match the universe domain found in the credentials (${universeFromAuth}). ` + - "If you haven't configured the universe domain explicitly, googleapis.com is the default." + "If you haven't configured the universe domain explicitly, googleapis.com is the default.", ); } } @@ -319,7 +319,7 @@ export class GrpcClient { } if (!servicePath) { throw new Error( - `Cannot determine service API path for service ${service.name}.` + `Cannot determine service API path for service ${service.name}.`, ); } @@ -346,7 +346,7 @@ export class GrpcClient { encoder, decoder, this.numericEnums, - this.minifyJson + this.minifyJson, ); return serviceStub; @@ -411,7 +411,7 @@ export function createApiCall( settings: gax.CallSettings, descriptor?: Descriptor, // eslint-disable-next-line @typescript-eslint/no-unused-vars - _fallback?: boolean | string // unused; for compatibility only + _fallback?: boolean | string, // unused; for compatibility only ): GaxCall { if ( descriptor && @@ -420,14 +420,14 @@ export function createApiCall( ) { return () => { throw new Error( - 'The REST transport currently does not support client-streaming or bidi-stream calls.' + 'The REST transport currently does not support client-streaming or bidi-stream calls.', ); }; } if (descriptor && 'streaming' in descriptor && !isNodeJS()) { return () => { throw new Error( - 'Server streaming over the REST transport is only supported in Node.js.' + 'Server streaming over the REST transport is only supported in Node.js.', ); }; } diff --git a/gax/src/fallbackRest.ts b/gax/src/fallbackRest.ts index 87984f03e..b6e5f7621 100644 --- a/gax/src/fallbackRest.ts +++ b/gax/src/fallbackRest.ts @@ -29,7 +29,7 @@ export function encodeRequest( servicePort: number, request: {}, numericEnums: boolean, - minifyJson: boolean + minifyJson: boolean, ): FetchParameters { const headers: {[key: string]: string} = { 'Content-Type': 'application/json', @@ -51,7 +51,7 @@ export function encodeRequest( throw new Error( `Cannot build HTTP request for ${JSON.stringify(json)}, method: ${ rpc.name - }` + }`, ); } @@ -75,7 +75,7 @@ export function encodeRequest( const body = JSON.stringify(transcoded.data); const url = `${protocol}://${servicePath}:${servicePort}/${transcoded.url.replace( /^\//, - '' + '', )}?${transcoded.queryString}`; return { @@ -89,7 +89,7 @@ export function encodeRequest( export function decodeResponse( rpc: protobuf.Method, ok: boolean, - response: Buffer | ArrayBuffer + response: Buffer | ArrayBuffer, ): {} { // eslint-disable-next-line n/no-unsupported-features/node-builtins const decodedString = new TextDecoder().decode(response); @@ -104,7 +104,7 @@ export function decodeResponse( const message = serializer.fromProto3JSON(rpc.resolvedResponseType!, json); if (!message) { throw new Error( - `Received null or malformed response from JSON serializer from RPC ${rpc.name}` + `Received null or malformed response from JSON serializer from RPC ${rpc.name}`, ); } return rpc.resolvedResponseType!.toObject(message, defaultToObjectOptions); diff --git a/gax/src/fallbackServiceStub.ts b/gax/src/fallbackServiceStub.ts index cf28522b8..4fcd1db58 100644 --- a/gax/src/fallbackServiceStub.ts +++ b/gax/src/fallbackServiceStub.ts @@ -17,17 +17,20 @@ /* global window */ /* global AbortController */ -import nodeFetch from 'node-fetch'; -import {Response as NodeFetchResponse, RequestInit} from 'node-fetch'; +import type { + Response as NodeFetchResponse, + RequestInit, +} from 'node-fetch' with {'resolution-mode': 'import'}; import {AbortController as NodeAbortController} from 'abort-controller'; - +import type nodeFetch from 'node-fetch' with {'resolution-mode': 'import'}; import {hasWindowFetch, hasAbortController, isNodeJS} from './featureDetection'; import {AuthClient} from './fallback'; import {StreamArrayParser} from './streamArrayParser'; import {pipeline, PipelineSource} from 'stream'; import type {Agent as HttpAgent} from 'http'; import type {Agent as HttpsAgent} from 'https'; - +const fetchNode = (...args: Parameters) => + import('node-fetch').then(({default: fetch}) => fetch(...args)); interface NodeFetchType { (url: RequestInfo, init?: RequestInit): Promise; } @@ -58,7 +61,7 @@ export interface FallbackServiceStub { request: {}, options?: {}, metadata?: {}, - callback?: (err?: Error, response?: {} | undefined) => void + callback?: (err?: Error, response?: {} | undefined) => void, ) => StreamArrayParser | {cancel: () => void}; } @@ -84,19 +87,19 @@ export function generateServiceStub( servicePort: number, request: {}, numericEnums: boolean, - minifyJson: boolean + minifyJson: boolean, ) => FetchParameters, responseDecoder: ( rpc: protobuf.Method, ok: boolean, - response: Buffer | ArrayBuffer + response: Buffer | ArrayBuffer, ) => {}, numericEnums: boolean, - minifyJson: boolean + minifyJson: boolean, ) { const fetch = hasWindowFetch() ? window.fetch - : (nodeFetch as unknown as NodeFetchType); + : (fetchNode as unknown as NodeFetchType); const serviceStub: FallbackServiceStub = { // close method should close all cancel controllers. If this feature request in the future, we can have a cancelControllerFactory that tracks created cancel controllers, and abort them all in close method. @@ -109,7 +112,7 @@ export function generateServiceStub( request: {}, options?: {[name: string]: string}, _metadata?: {} | Function, - callback?: Function + callback?: Function, ) => { options ??= {}; @@ -125,7 +128,7 @@ export function generateServiceStub( servicePort, request, numericEnums, - minifyJson + minifyJson, ); } catch (err) { // we could not encode parameters; pass error to the callback @@ -158,11 +161,7 @@ export function generateServiceStub( ...authHeader, ...headers, }, - body: fetchParameters.body as - | string - | Buffer - | Uint8Array - | undefined, + body: fetchParameters.body as string | Buffer | undefined, method: fetchParameters.method, signal: cancelSignal, }; @@ -193,7 +192,7 @@ export function generateServiceStub( } streamArrayParser.emit('error', err); } - } + }, ); return; } else { diff --git a/gax/src/gax.ts b/gax/src/gax.ts index 64f381443..a38152c24 100644 --- a/gax/src/gax.ts +++ b/gax/src/gax.ts @@ -86,7 +86,7 @@ export class RetryOptions { retryCodes: number[], backoffSettings: BackoffSettings, shouldRetryFn?: (error: GoogleError) => boolean, - getResumptionRequestFn?: (request: RequestType) => RequestType + getResumptionRequestFn?: (request: RequestType) => RequestType, ) { this.retryCodes = retryCodes; this.backoffSettings = backoffSettings; @@ -324,7 +324,7 @@ export class CallSettings { */ export function convertRetryOptions( options?: CallOptions, - gaxStreamingRetries?: boolean + gaxStreamingRetries?: boolean, ): CallOptions | undefined { // options will be undefined if no CallOptions object is passed at call time if (!options) { @@ -343,21 +343,21 @@ export function convertRetryOptions( warn( 'retry_request_options', 'objectMode override is not supported. It is set to true internally by default in gax.', - 'UnsupportedParameterWarning' + 'UnsupportedParameterWarning', ); } if (options.retryRequestOptions.noResponseRetries !== undefined) { warn( 'retry_request_options', 'noResponseRetries override is not supported. Please specify retry codes or a function to determine retry eligibility.', - 'UnsupportedParameterWarning' + 'UnsupportedParameterWarning', ); } if (options.retryRequestOptions.currentRetryAttempt !== undefined) { warn( 'retry_request_options', 'currentRetryAttempt override is not supported. Retry attempts are tracked internally.', - 'UnsupportedParameterWarning' + 'UnsupportedParameterWarning', ); } @@ -392,7 +392,7 @@ export function convertRetryOptions( warn( 'retry_request_options_no_max_retries_timeout', 'Neither maxRetries nor totalTimeout were passed. Defaulting to totalTimeout of 30000ms.', - 'MissingParameterWarning' + 'MissingParameterWarning', ); } } @@ -408,14 +408,14 @@ export function convertRetryOptions( const convertedRetryOptions = createRetryOptions( retryCodes, backoffSettings, - shouldRetryFn + shouldRetryFn, ); options.retry = convertedRetryOptions; delete options.retryRequestOptions; // completely remove them to avoid any further confusion warn( 'retry_request_options', 'retryRequestOptions will be deprecated in a future release. Please use retryOptions to pass retry options at call time', - 'DeprecationWarning' + 'DeprecationWarning', ); } return options; @@ -436,7 +436,7 @@ export function createRetryOptions( retryCodes: number[], backoffSettings: BackoffSettings, shouldRetryFn?: (error: GoogleError) => boolean, - getResumptionRequestFn?: (request: RequestType) => RequestType + getResumptionRequestFn?: (request: RequestType) => RequestType, ): RetryOptions { return { retryCodes, @@ -478,7 +478,7 @@ export function createBackoffSettings( initialRpcTimeoutMillis: number | null, rpcTimeoutMultiplier: number | null, maxRpcTimeoutMillis: number | null, - totalTimeoutMillis: number | null + totalTimeoutMillis: number | null, ): BackoffSettings { return { initialRetryDelayMillis, @@ -527,7 +527,7 @@ export function createMaxRetriesBackoffSettings( initialRpcTimeoutMillis: number, rpcTimeoutMultiplier: number, maxRpcTimeoutMillis: number, - maxRetries: number + maxRetries: number, ): BackoffSettings { return { initialRetryDelayMillis, @@ -607,7 +607,7 @@ function constructRetry( methodConfig: MethodConfig | null, retryCodes: {[index: string]: string[]} | undefined, retryParams: {[index: string]: {}} | undefined, - retryNames: {[index: string]: {}} + retryNames: {[index: string]: {}}, ): RetryOptions | null | undefined { if (!methodConfig) { return null; @@ -633,7 +633,7 @@ function constructRetry( params.initial_rpc_timeout_millis, params.rpc_timeout_multiplier, params.max_rpc_timeout_millis, - params.total_timeout_millis + params.total_timeout_millis, ); } return createRetryOptions(codes!, backoffSettings!); @@ -654,7 +654,7 @@ function constructRetry( */ function mergeRetryOptions( retry: RetryOptions, - overrides: Partial + overrides: Partial, ): RetryOptions | null { if (!overrides) { return null; @@ -686,7 +686,7 @@ function mergeRetryOptions( retryCodes!, backoffSettings!, shouldRetryFn!, - getResumptionRequestFn! + getResumptionRequestFn!, ); } @@ -790,7 +790,7 @@ export function constructSettings( clientConfig: ClientConfig, configOverrides: ClientConfig, retryNames: {}, - otherArgs?: {} + otherArgs?: {}, ) { otherArgs = otherArgs || {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -818,7 +818,7 @@ export function constructSettings( methodConfig, serviceConfig.retry_codes, serviceConfig.retry_params, - retryNames + retryNames, ); let bundlingConfig = methodConfig!.bundling; let timeout = methodConfig!.timeout_millis; @@ -838,8 +838,8 @@ export function constructSettings( overridingMethod, overrides.retry_codes, overrides.retry_params, - retryNames - )! + retryNames, + )!, ); } const apiName = serviceName; @@ -865,7 +865,7 @@ export function createByteLengthFunction(message: typeof Message) { const stringified = JSON.stringify(obj); warn( 'error_encoding_protobufjs_object', - `Cannot encode protobuf.js object: ${stringified}: ${err}` + `Cannot encode protobuf.js object: ${stringified}: ${err}`, ); // We failed to encode the object properly, let's just return an upper boundary of its length. // It's only needed for calculating the size of the batch, so it's safe if it's bigger than needed. diff --git a/gax/src/googleError.ts b/gax/src/googleError.ts index e9070b68f..e7305dbc4 100644 --- a/gax/src/googleError.ts +++ b/gax/src/googleError.ts @@ -38,7 +38,7 @@ export class GoogleError extends Error { if (err.metadata && err.metadata.get('grpc-status-details-bin')) { const statusDetailsObj: GRPCStatusDetailsObject = decoder.decodeGRPCStatusDetails( - err.metadata.get('grpc-status-details-bin') as [] + err.metadata.get('grpc-status-details-bin') as [], ); if ( statusDetailsObj && @@ -88,7 +88,7 @@ export class GoogleError extends Error { const proto3Error = decoder.decodeHTTPError(json['error']); const error = Object.assign( new GoogleError(json['error']['message']), - proto3Error + proto3Error, ); // Get gRPC Status Code if ( @@ -182,7 +182,7 @@ export class GoogleErrorDecoder { const match = anyValue.type_url.match(/^type.googleapis.com\/(.*)/); if (!match) { throw new Error( - `Unknown type encoded in google.protobuf.any: ${anyValue.type_url}` + `Unknown type encoded in google.protobuf.any: ${anyValue.type_url}`, ); } const typeName = match[1]; @@ -239,14 +239,14 @@ export class GoogleErrorDecoder { // Decodes gRPC metadata error details which is an instance of google.rpc.Status. decodeGRPCStatusDetails( - bufferArr: Buffer[] | ArrayBuffer[] + bufferArr: Buffer[] | ArrayBuffer[], ): GRPCStatusDetailsObject { const details: protobuf.Message<{}>[] = []; let errorInfo; bufferArr.forEach(buffer => { const uint8array = new Uint8Array(buffer); const rpcStatus = this.statusType.decode( - uint8array + uint8array, ) as unknown as RpcStatus; for (const detail of rpcStatus.details) { try { @@ -272,7 +272,7 @@ export class GoogleErrorDecoder { const errorMessage = serializer.fromProto3JSON(this.statusType, json); if (!errorMessage) { throw new Error( - `Received error message ${json}, but failed to serialize as proto3 message` + `Received error message ${json}, but failed to serialize as proto3 message`, ); } return this.statusType.toObject(errorMessage, defaultToObjectOptions); @@ -280,7 +280,7 @@ export class GoogleErrorDecoder { // Decodes http error details which is an instance of Array. decodeHttpStatusDetails( - rawDetails: Array + rawDetails: Array, ): GRPCStatusDetailsObject { // eslint-disable-next-line @typescript-eslint/no-unused-vars const details: protobuf.Message<{}>[] = []; diff --git a/gax/src/grpc.ts b/gax/src/grpc.ts index ff8d06f67..37c9a693a 100644 --- a/gax/src/grpc.ts +++ b/gax/src/grpc.ts @@ -24,7 +24,7 @@ import {join} from 'path'; import {OutgoingHttpHeaders} from 'http'; import * as path from 'path'; import * as protobuf from 'protobufjs'; -import * as objectHash from 'object-hash'; +import objectHash from 'object-hash'; import * as gax from './gax'; import {ClientOptions} from '@grpc/grpc-js/build/src/client'; @@ -37,11 +37,11 @@ INCLUDE_DIRS.push(googleProtoFilesDir); // COMMON_PROTO_FILES logic is here for protobufjs loads (see // GoogleProtoFilesRoot below) -import * as commonProtoFiles from './protosList.json'; +import commonProtoFiles from './protosList.json'; import {google} from '../protos/http'; // use the correct path separator for the OS we are running on const COMMON_PROTO_FILES: string[] = commonProtoFiles.map(file => - file.replace(/[/\\]/g, path.sep) + file.replace(/[/\\]/g, path.sep), ); export interface GrpcClientOptions extends GoogleAuthOptions { @@ -131,7 +131,7 @@ export class GrpcClient { */ private static protoCacheKey( filename: string | string[], - options: grpcProtoLoader.Options + options: grpcProtoLoader.Options, ) { if ( !filename || @@ -204,13 +204,13 @@ export class GrpcClient { ? grpc.credentials.createSsl( null, Buffer.from(opts.key), - Buffer.from(opts.cert) + Buffer.from(opts.cert), ) : grpc.credentials.createSsl(); const client = await this.auth.getClient(); const credentials = grpc.credentials.combineChannelCredentials( sslCreds, - grpc.credentials.createFromGoogleCredential(client) + grpc.credentials.createFromGoogleCredential(client), ); return credentials; } @@ -243,7 +243,7 @@ export class GrpcClient { loadFromProto( filename: string | string[], options: grpcProtoLoader.Options, - ignoreCache = false + ignoreCache = false, ) { const cacheKey = GrpcClient.protoCacheKey(filename, options); let grpcPackage = cacheKey @@ -275,7 +275,7 @@ export class GrpcClient { loadProto( protoPath: string, filename?: string | string[], - ignoreCache = false + ignoreCache = false, ) { if (!filename) { filename = path.basename(protoPath); @@ -325,7 +325,7 @@ export class GrpcClient { } return function buildMetadata( abTests?: {}, - moreHeaders?: OutgoingHttpHeaders + moreHeaders?: OutgoingHttpHeaders, ) { // TODO: bring the A/B testing info into the metadata. let copied = false; @@ -365,14 +365,14 @@ export class GrpcClient { serviceName: string, clientConfig: gax.ClientConfig, configOverrides: gax.ClientConfig, - headers: OutgoingHttpHeaders + headers: OutgoingHttpHeaders, ) { return gax.constructSettings( serviceName, clientConfig, configOverrides, this.grpc.status, - {metadataBuilder: this.metadataBuilder(headers)} + {metadataBuilder: this.metadataBuilder(headers)}, ); } @@ -392,7 +392,7 @@ export class GrpcClient { async createStub( CreateStub: typeof ClientStub, options: ClientStubOptions, - customServicePath?: boolean + customServicePath?: boolean, ) { // The following options are understood by grpc-gcp and need a special treatment // (should be passed without a `grpc.` prefix) @@ -403,12 +403,12 @@ export class GrpcClient { ]; const [cert, key] = await this._detectClientCertificate( options, - options.universeDomain + options.universeDomain, ); const servicePath = this._mtlsServicePath( options.servicePath, customServicePath, - cert && key + cert && key, ); const opts = Object.assign({}, options, {cert, key, servicePath}); const serviceAddress = servicePath + ':' + opts.port; @@ -420,7 +420,7 @@ export class GrpcClient { if (universeFromAuth && options.universeDomain !== universeFromAuth) { throw new Error( `The configured universe domain (${options.universeDomain}) does not match the universe domain found in the credentials (${universeFromAuth}). ` + - "If you haven't configured the universe domain explicitly, googleapis.com is the default." + "If you haven't configured the universe domain explicitly, googleapis.com is the default.", ); } } @@ -453,7 +453,7 @@ export class GrpcClient { const stub = new CreateStub( serviceAddress, creds, - grpcOptions as ClientOptions + grpcOptions as ClientOptions, ); return stub; } @@ -467,7 +467,7 @@ export class GrpcClient { */ async _detectClientCertificate( opts?: ClientOptions, - universeDomain?: string + universeDomain?: string, ) { const certRegex = /(?-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----)/s; @@ -480,7 +480,7 @@ export class GrpcClient { ) { if (universeDomain && universeDomain !== 'googleapis.com') { throw new Error( - 'mTLS is not supported outside of googleapis.com universe domain.' + 'mTLS is not supported outside of googleapis.com universe domain.', ); } if (opts?.cert && opts?.key) { @@ -491,7 +491,7 @@ export class GrpcClient { const metadataPath = join( os.homedir(), '.secureConnect', - 'context_aware_metadata.json' + 'context_aware_metadata.json', ); const metadata = JSON.parse(await readFileAsync(metadataPath)); if (!metadata.cert_provider_command) { @@ -499,7 +499,7 @@ export class GrpcClient { } const stdout = await execFileAsync( metadata.cert_provider_command[0], - metadata.cert_provider_command.slice(1) + metadata.cert_provider_command.slice(1), ); const matchCert = stdout.toString().match(certRegex); const matchKey = stdout.toString().match(keyRegex); @@ -526,7 +526,7 @@ export class GrpcClient { _mtlsServicePath( servicePath: string | undefined, customServicePath: boolean | undefined, - hasCertificate: boolean + hasCertificate: boolean, ): string | undefined { // If user provides a custom service path, return the current service // path and do not attempt to add mtls subdomain: diff --git a/gax/src/iamService.ts b/gax/src/iamService.ts index 758536775..1ae5539ae 100644 --- a/gax/src/iamService.ts +++ b/gax/src/iamService.ts @@ -49,7 +49,7 @@ export class IamClient { constructor( gaxGrpc: GrpcClient | FallbackGrpcClient, // eslint-disable-next-line @typescript-eslint/no-explicit-any - options: ClientOptions + options: ClientOptions, ) { this.gaxGrpc = gaxGrpc; // Ensure that options include the service address and port. @@ -61,7 +61,7 @@ export class IamClient { apiEndpoint: options.apiEndpoint, fallback: options.fallback, }, - options + options, ) as ClientOptions & ClientStubOptions; version = opts.fallback ? fallback.version : version; opts.scopes = (this.constructor as typeof IamClient).scopes; @@ -90,7 +90,7 @@ export class IamClient { 'google.iam.v1.IAMPolicy', gapicConfig as gax.ClientConfig, opts!.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} + {'x-goog-api-client': clientHeader.join(' ')}, ); this.innerApiCalls = {}; } @@ -117,7 +117,7 @@ export class IamClient { this._opts.fallback ? this._protos.lookupService('google.iam.v1.IAMPolicy') : this._protos.google.iam.v1.IAMPolicy, - this._opts + this._opts, ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -139,12 +139,12 @@ export class IamClient { }, (err: Error | null | undefined) => () => { throw err; - } + }, ); this.innerApiCalls[methodName] = createApiCall( innerCallPromise, this._defaults[methodName], - this.descriptors.page[methodName] + this.descriptors.page[methodName], ); } return this.iamPolicyStub; @@ -202,7 +202,7 @@ export class IamClient { getIamPolicy( request: protos.google.iam.v1.GetIamPolicyRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Promise<[protos.google.iam.v1.Policy]>; getIamPolicy( request: protos.google.iam.v1.GetIamPolicyRequest, @@ -211,7 +211,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): void; getIamPolicy( request: protos.google.iam.v1.GetIamPolicyRequest, @@ -219,7 +219,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): void; getIamPolicy( request: protos.google.iam.v1.GetIamPolicyRequest, @@ -234,7 +234,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.Policy]> { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -255,13 +255,13 @@ export class IamClient { routingHeader.fromParams({ resource: request.resource, }); - this.initialize(); + this.initialize().catch(console.error); return this.innerApiCalls.getIamPolicy(request, options, callback); } setIamPolicy( request: protos.google.iam.v1.SetIamPolicyRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Promise<[protos.google.iam.v1.Policy]>; setIamPolicy( request: protos.google.iam.v1.SetIamPolicyRequest, @@ -270,7 +270,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): void; setIamPolicy( request: protos.google.iam.v1.SetIamPolicyRequest, @@ -278,7 +278,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): void; setIamPolicy( request: protos.google.iam.v1.SetIamPolicyRequest, @@ -293,7 +293,7 @@ export class IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.Policy]> { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -314,12 +314,12 @@ export class IamClient { routingHeader.fromParams({ resource: request.resource, }); - this.initialize(); + this.initialize().catch(console.error); return this.innerApiCalls.setIamPolicy(request, options, callback); } testIamPermissions( request: protos.google.iam.v1.TestIamPermissionsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Promise<[protos.google.iam.v1.TestIamPermissionsResponse]>; testIamPermissions( request: protos.google.iam.v1.TestIamPermissionsRequest, @@ -327,7 +327,7 @@ export class IamClient { protos.google.iam.v1.TestIamPermissionsResponse, protos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > + >, ): void; testIamPermissions( request: protos.google.iam.v1.TestIamPermissionsRequest, @@ -336,7 +336,7 @@ export class IamClient { protos.google.iam.v1.TestIamPermissionsResponse, protos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > + >, ): void; testIamPermissions( request: protos.google.iam.v1.TestIamPermissionsRequest, @@ -351,7 +351,7 @@ export class IamClient { protos.google.iam.v1.TestIamPermissionsResponse, protos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.TestIamPermissionsResponse]> { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -372,7 +372,7 @@ export class IamClient { routingHeader.fromParams({ resource: request.resource, }); - this.initialize(); + this.initialize().catch(console.error); return this.innerApiCalls.testIamPermissions(request, options, callback); } @@ -382,7 +382,7 @@ export class IamClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { - this.initialize(); + this.initialize().catch(console.error); if (!this._terminated) { return this.iamPolicyStub!.then(stub => { this._terminated = true; @@ -407,7 +407,7 @@ export interface IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.GetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.Policy]>; setIamPolicy(request: protos.google.iam.v1.SetIamPolicyRequest): void; setIamPolicy( @@ -423,10 +423,10 @@ export interface IamClient { protos.google.iam.v1.Policy, protos.google.iam.v1.SetIamPolicyRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.Policy]>; testIamPermissions( - request: protos.google.iam.v1.TestIamPermissionsRequest + request: protos.google.iam.v1.TestIamPermissionsRequest, ): void; testIamPermissions( request: protos.google.iam.v1.TestIamPermissionsRequest, @@ -441,6 +441,6 @@ export interface IamClient { protos.google.iam.v1.TestIamPermissionsResponse, protos.google.iam.v1.TestIamPermissionsRequest | null | undefined, {} | null | undefined - > + >, ): Promise<[protos.google.iam.v1.TestIamPermissionsResponse]>; } diff --git a/gax/src/index.ts b/gax/src/index.ts index 2393ce798..1baf2e566 100644 --- a/gax/src/index.ts +++ b/gax/src/index.ts @@ -76,7 +76,7 @@ export {OperationsClient} from './operationsClient'; export {IamClient} from './iamService'; export {LocationsClient} from './locationService'; -export const createByteLengthFunction = GrpcClient.createByteLengthFunction; +export const createByteLengthFunction = GrpcClient?.createByteLengthFunction; export const version = require('../../package.json').version; import * as protobuf from 'protobufjs'; diff --git a/gax/src/locationService.ts b/gax/src/locationService.ts index bfe49b865..08ed1b0cd 100644 --- a/gax/src/locationService.ts +++ b/gax/src/locationService.ts @@ -100,7 +100,7 @@ export class LocationsClient { constructor( gaxGrpc: GrpcClient | FallbackGrpcClient, // eslint-disable-next-line @typescript-eslint/no-explicit-any - opts: ClientOptions + opts: ClientOptions, ) { // Ensure that options include all the required fields. this.gaxGrpc = gaxGrpc; @@ -158,7 +158,7 @@ export class LocationsClient { listLocations: new PageDescriptor( 'pageToken', 'nextPageToken', - 'locations' + 'locations', ), }; @@ -167,7 +167,7 @@ export class LocationsClient { 'google.cloud.location.Locations', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} + {'x-goog-api-client': clientHeader.join(' ')}, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -201,12 +201,12 @@ export class LocationsClient { this.locationsStub = this.gaxGrpc.createStub( this._opts.fallback ? (this._protos as protobuf.Root).lookupService( - 'google.cloud.location.Locations' + 'google.cloud.location.Locations', ) : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.location.Locations, this._opts, - this._providedCustomServicePath + this._providedCustomServicePath, ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides @@ -224,14 +224,14 @@ export class LocationsClient { }, (err: Error | null | undefined) => () => { throw err; - } + }, ); const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = createApiCall( callPromise, this._defaults[methodName], - descriptor + descriptor, ); this.innerApiCalls[methodName] = apiCall; @@ -281,7 +281,7 @@ export class LocationsClient { getProjectId(): Promise; getProjectId(callback: Callback): void; getProjectId( - callback?: Callback + callback?: Callback, ): Promise | void { if (callback) { this.auth.getProjectId(callback); @@ -295,7 +295,7 @@ export class LocationsClient { // ------------------- getLocation( request?: protos.google.cloud.location.IGetLocationRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Promise; getLocation( request: protos.google.cloud.location.IGetLocationRequest, @@ -304,7 +304,7 @@ export class LocationsClient { protos.google.cloud.location.ILocation, protos.google.cloud.location.IGetLocationRequest | null | undefined, {} | null | undefined - > + >, ): void; getLocation( request: protos.google.cloud.location.IGetLocationRequest, @@ -312,7 +312,7 @@ export class LocationsClient { protos.google.cloud.location.ILocation, protos.google.cloud.location.IGetLocationRequest | null | undefined, {} | null | undefined - > + >, ): void; /** * Gets information about a location. @@ -344,7 +344,7 @@ export class LocationsClient { protos.google.cloud.location.ILocation, protos.google.cloud.location.IGetLocationRequest | null | undefined, {} | null | undefined - > + >, ): Promise { request = request || {}; let options: gax.CallOptions; @@ -361,13 +361,13 @@ export class LocationsClient { routingHeader.fromParams({ name: request.name || '', }); - this.initialize(); + this.initialize().catch(console.error); return this.innerApiCalls.getLocation(request, options, callback); } listLocations( request?: protos.google.cloud.location.IListLocationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Promise< [ protos.google.cloud.location.ILocation[], @@ -382,7 +382,7 @@ export class LocationsClient { protos.google.cloud.location.IListLocationsRequest, protos.google.cloud.location.IListLocationsResponse | null | undefined, protos.google.cloud.location.ILocation - > + >, ): void; listLocations( request: protos.google.cloud.location.IListLocationsRequest, @@ -390,7 +390,7 @@ export class LocationsClient { protos.google.cloud.location.IListLocationsRequest, protos.google.cloud.location.IListLocationsResponse | null | undefined, protos.google.cloud.location.ILocation - > + >, ): void; /** * Lists information about the supported locations for this service. @@ -433,7 +433,7 @@ export class LocationsClient { protos.google.cloud.location.IListLocationsRequest, protos.google.cloud.location.IListLocationsResponse | null | undefined, protos.google.cloud.location.ILocation - > + >, ): Promise< [ protos.google.cloud.location.ILocation[], @@ -456,7 +456,7 @@ export class LocationsClient { routingHeader.fromParams({ name: request.name || '', }); - this.initialize(); + this.initialize().catch(console.error); return this.innerApiCalls.listLocations(request, options, callback); } @@ -492,7 +492,7 @@ export class LocationsClient { */ listLocationsAsync( request: protos.google.cloud.location.IListLocationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): AsyncIterable { request = request || {}; options = options || {}; @@ -504,11 +504,11 @@ export class LocationsClient { }); options = options || {}; const callSettings = new gax.CallSettings(options); - this.initialize(); + this.initialize().catch(console.error); return this.descriptors.page.listLocations.asyncIterate( this.innerApiCalls['listLocations'] as GaxCall, request as unknown as RequestType, - callSettings + callSettings, ) as AsyncIterable; } @@ -519,7 +519,7 @@ export class LocationsClient { * @returns {Promise} A promise that resolves when the client is closed. */ close(): Promise { - this.initialize(); + this.initialize().catch(console.error); if (!this._terminated) { return this.locationsStub!.then(stub => { this._terminated = true; @@ -545,11 +545,11 @@ export interface LocationsClient { protos.google.cloud.location.ILocation, protos.google.cloud.location.IGetLocationRequest | null | undefined, {} | null | undefined - > + >, ): Promise; listLocationsAsync( request: protos.google.cloud.location.IListLocationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): AsyncIterable; } diff --git a/gax/src/longRunningCalls/longRunningApiCaller.ts b/gax/src/longRunningCalls/longRunningApiCaller.ts index 7f4501dcc..c0c17f985 100644 --- a/gax/src/longRunningCalls/longRunningApiCaller.ts +++ b/gax/src/longRunningCalls/longRunningApiCaller.ts @@ -58,7 +58,7 @@ export class LongrunningApiCaller implements APICaller { apiCall: SimpleCallbackFunction, argument: {}, settings: CallOptions, - canceller: OngoingCallPromise + canceller: OngoingCallPromise, ) { canceller.call((argument, callback) => { return this._wrapOperation(apiCall, settings, argument, callback); @@ -69,7 +69,7 @@ export class LongrunningApiCaller implements APICaller { apiCall: SimpleCallbackFunction, settings: CallOptions, argument: {}, - callback: APICallback + callback: APICallback, ) { let backoffSettings: BackoffSettings | undefined = settings.longrunning; if (!backoffSettings) { @@ -89,11 +89,11 @@ export class LongrunningApiCaller implements APICaller { rawResponse as operationProtos.google.longrunning.Operation, longrunningDescriptor, backoffSettings!, - settings + settings, ); callback(null, operation, rawResponse); - } + }, ); } diff --git a/gax/src/longRunningCalls/longRunningDescriptor.ts b/gax/src/longRunningCalls/longRunningDescriptor.ts index 673e167c5..58b823853 100644 --- a/gax/src/longRunningCalls/longRunningDescriptor.ts +++ b/gax/src/longRunningCalls/longRunningDescriptor.ts @@ -37,7 +37,7 @@ export class LongRunningDescriptor implements Descriptor { constructor( operationsClient: OperationsClient, responseDecoder: AnyDecoder, - metadataDecoder: AnyDecoder + metadataDecoder: AnyDecoder, ) { this.operationsClient = operationsClient; this.responseDecoder = responseDecoder; diff --git a/gax/src/longRunningCalls/longrunning.ts b/gax/src/longRunningCalls/longrunning.ts index e061ccf99..492406c08 100644 --- a/gax/src/longRunningCalls/longrunning.ts +++ b/gax/src/longRunningCalls/longrunning.ts @@ -37,7 +37,7 @@ export interface GetOperationCallback { err?: Error | null, result?: {}, metadata?: {}, - rawResponse?: LROOperation + rawResponse?: LROOperation, ): void; } @@ -75,7 +75,7 @@ export class Operation extends EventEmitter { grpcOp: LROOperation, longrunningDescriptor: LongRunningDescriptor, backoffSettings: BackoffSettings, - callOptions?: CallOptions + callOptions?: CallOptions, ) { super(); this.completeListeners = 0; @@ -186,7 +186,7 @@ export class Operation extends EventEmitter { request.name = this.latestResponse.name; this.currentCallPromise_ = operationsClient.getOperationInternal( request, - this._callOptions! + this._callOptions!, ); const noCallbackPromise = this.currentCallPromise_.then( @@ -201,7 +201,7 @@ export class Operation extends EventEmitter { return; } return Promise.reject(err); - } + }, ); if (!callback) { @@ -292,7 +292,7 @@ export class Operation extends EventEmitter { if (now.getTime() >= deadline) { const error = new GoogleError( - 'Total timeout exceeded before any response was received' + 'Total timeout exceeded before any response was received', ); error.code = Status.DEADLINE_EXCEEDED; setImmediate(emit, 'error', error); @@ -312,7 +312,7 @@ export class Operation extends EventEmitter { (rawResponse && !arrayEquals( rawResponse.metadata.value!, - previousMetadataBytes + previousMetadataBytes, ))) ) { setImmediate(emit, 'progress', metadata, rawResponse); @@ -353,7 +353,7 @@ export class Operation extends EventEmitter { 'complete', (result, metadata, rawResponse) => { resolve([result, metadata, rawResponse]); - } + }, ); }); } @@ -376,7 +376,7 @@ export function operation( op: LROOperation, longrunningDescriptor: LongRunningDescriptor, backoffSettings: BackoffSettings, - callOptions?: CallOptions + callOptions?: CallOptions, ) { return new Operation(op, longrunningDescriptor, backoffSettings, callOptions); } diff --git a/gax/src/normalCalls/normalApiCaller.ts b/gax/src/normalCalls/normalApiCaller.ts index 50c424efb..b2da678f9 100644 --- a/gax/src/normalCalls/normalApiCaller.ts +++ b/gax/src/normalCalls/normalApiCaller.ts @@ -38,7 +38,7 @@ export class NormalApiCaller implements APICaller { apiCall: SimpleCallbackFunction, argument: {}, settings: {}, - canceller: OngoingCallPromise + canceller: OngoingCallPromise, ): void { canceller.call(apiCall, argument); } diff --git a/gax/src/normalCalls/retries.ts b/gax/src/normalCalls/retries.ts index ed67a4679..b0dc8c3c7 100644 --- a/gax/src/normalCalls/retries.ts +++ b/gax/src/normalCalls/retries.ts @@ -46,7 +46,7 @@ export function retryable( func: GRPCCall, retry: RetryOptions, otherArgs: GRPCCallOtherArgs, - apiName?: string + apiName?: string, ): SimpleCallbackFunction { const delayMult = retry.backoffSettings.retryDelayMultiplier; const maxDelay = retry.backoffSettings.maxRetryDelayMillis; @@ -86,7 +86,7 @@ export function retryable( retry.backoffSettings.totalTimeoutMillis } milliseconds ${ err ? `retrying error ${err} ` : '' - } before any response was received.` + } before any response was received.`, ); error.code = Status.DEADLINE_EXCEEDED; callback(error); @@ -97,7 +97,7 @@ export function retryable( const error = new GoogleError( 'Exceeded maximum number of retries ' + (err ? `retrying error ${err} ` : '') + - 'before any response was received' + 'before any response was received', ); error.code = Status.DEADLINE_EXCEEDED; callback(error); @@ -149,7 +149,7 @@ export function retryable( if (maxRetries && deadline!) { const error = new GoogleError( 'Cannot set both totalTimeoutMillis and maxRetries ' + - 'in backoffSettings.' + 'in backoffSettings.', ); error.code = Status.INVALID_ARGUMENT; callback(error); diff --git a/gax/src/normalCalls/timeout.ts b/gax/src/normalCalls/timeout.ts index b1790d854..440a89cb5 100644 --- a/gax/src/normalCalls/timeout.ts +++ b/gax/src/normalCalls/timeout.ts @@ -40,7 +40,7 @@ export function addTimeoutArg( func: GRPCCall, timeout: number, otherArgs: GRPCCallOtherArgs, - abTests?: {} + abTests?: {}, ): SimpleCallbackFunction { // TODO: this assumes the other arguments consist of metadata and options, // which is specific to gRPC calls. Remove the hidden dependency on gRPC. diff --git a/gax/src/operationsClient.ts b/gax/src/operationsClient.ts index 2941ff436..8cf71527c 100644 --- a/gax/src/operationsClient.ts +++ b/gax/src/operationsClient.ts @@ -70,7 +70,7 @@ export class OperationsClient { gaxGrpc: GrpcClient | FallbackGrpcClient, // eslint-disable-next-line @typescript-eslint/no-explicit-any operationsProtos: any, - options: ClientOptions + options: ClientOptions, ) { const opts = Object.assign( { @@ -78,7 +78,7 @@ export class OperationsClient { port: DEFAULT_SERVICE_PORT, clientConfig: {}, }, - options + options, ) as ClientOptions & ClientStubOptions; const googleApiClient = ['gl-node/' + process.versions.node]; @@ -96,7 +96,7 @@ export class OperationsClient { 'google.longrunning.Operations', configData, opts.clientConfig || {}, - {'x-goog-api-client': googleApiClient.join(' ')} + {'x-goog-api-client': googleApiClient.join(' ')}, ); this.auth = gaxGrpc.auth; @@ -109,7 +109,7 @@ export class OperationsClient { listOperations: new PageDescriptor( 'pageToken', 'nextPageToken', - 'operations' + 'operations', ), }; // Put together the "service stub" for @@ -118,7 +118,7 @@ export class OperationsClient { opts.fallback ? operationsProtos.lookupService('google.longrunning.Operations') : operationsProtos.google.longrunning.Operations, - opts + opts, ) as Promise<{[method: string]: Function}>; const operationsStubMethods = [ 'getOperation', @@ -136,19 +136,19 @@ export class OperationsClient { }, err => () => { throw err; - } + }, ); this.innerApiCalls[methodName] = createApiCall( innerCallPromise, defaults[methodName], - this.descriptor[methodName] + this.descriptor[methodName], ); } } /** Closes this operations client. */ close() { - this.operationsStub.then(stub => stub.close()); + this.operationsStub.then(stub => stub.close()).catch(console.error); } /** @@ -177,7 +177,7 @@ export class OperationsClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | null | undefined - > + >, ): CancellablePromise { request = request || {}; options = options || {}; @@ -227,7 +227,7 @@ export class OperationsClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | null | undefined - > + >, ): Promise<[protos.google.longrunning.Operation]> { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -335,7 +335,7 @@ export class OperationsClient { protos.google.longrunning.ListOperationsResponse, protos.google.longrunning.ListOperationsRequest, {} | null | undefined - > + >, ): Promise { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -399,13 +399,13 @@ export class OperationsClient { */ listOperationsStream( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): Transform { const callSettings = new gax.CallSettings(options); return this.descriptor.listOperations.createStream( this.innerApiCalls.listOperations as GaxCall, request, - callSettings + callSettings, ); } /** @@ -432,7 +432,7 @@ export class OperationsClient { */ listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + options?: gax.CallOptions, ): AsyncIterable { request = request || {}; options = options || {}; @@ -440,7 +440,7 @@ export class OperationsClient { return this.descriptor.listOperations.asyncIterate( this.innerApiCalls.listOperations as GaxCall, request as unknown as RequestType, - callSettings + callSettings, ) as AsyncIterable; } @@ -487,7 +487,7 @@ export class OperationsClient { protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} | undefined | null - > + >, ): Promise { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -542,7 +542,7 @@ export class OperationsClient { protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | null | undefined - > + >, ): Promise { let options: gax.CallOptions; if (optionsOrCallback instanceof Function && callback === undefined) { @@ -570,7 +570,7 @@ export class OperationsClientBuilder { */ constructor( gaxGrpc: GrpcClient | FallbackGrpcClient, - protoJson?: protobuf.Root + protoJson?: protobuf.Root, ) { if (protoJson && gaxGrpc.httpRules) { // overwrite the http rules if provide in service yaml. diff --git a/gax/src/paginationCalls/pageDescriptor.ts b/gax/src/paginationCalls/pageDescriptor.ts index 80aeb9766..13c3a4636 100644 --- a/gax/src/paginationCalls/pageDescriptor.ts +++ b/gax/src/paginationCalls/pageDescriptor.ts @@ -49,7 +49,7 @@ export class PageDescriptor implements Descriptor { constructor( requestPageTokenField: string, responsePageTokenField: string, - resourceField: string + resourceField: string, ) { this.requestPageTokenField = requestPageTokenField; this.responsePageTokenField = responsePageTokenField; @@ -62,13 +62,13 @@ export class PageDescriptor implements Descriptor { createStream( apiCall: GaxCall, request: {}, - options: CallSettings + options: CallSettings, ): Transform { if (options?.autoPaginate) { warn( 'autoPaginate true', 'Autopaginate will always be set to false in stream paging methods. See more info at https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure paging calls', - 'AutopaginateTrueWarning' + 'AutopaginateTrueWarning', ); } const stream = new PassThrough({objectMode: true}); @@ -80,7 +80,7 @@ export class PageDescriptor implements Descriptor { err: Error | null, resources: Array, next: NextPageRequestType, - apiResp: RawResponseType + apiResp: RawResponseType, ) { if (err) { stream.emit('error', err); @@ -128,10 +128,10 @@ export class PageDescriptor implements Descriptor { setImmediate(apiCall, next, options, callback as APICallback); } } - stream.on('resume', () => { + stream.on('resume', async () => { if (!started) { started = true; - apiCall(request, options, callback as unknown as APICallback); + await apiCall(request, options, callback as unknown as APICallback); } }); return stream; @@ -143,13 +143,13 @@ export class PageDescriptor implements Descriptor { asyncIterate( apiCall: GaxCall, request: RequestType, - options?: CallSettings + options?: CallSettings, ): AsyncIterable<{} | undefined> { if (options?.autoPaginate) { warn( 'autoPaginate true', 'Autopaginate will always be set to false in Async paging methods. See more info at https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure paging calls', - 'AutopaginateTrueWarning' + 'AutopaginateTrueWarning', ); } options = Object.assign({}, options, {autoPaginate: false}); @@ -160,7 +160,7 @@ export class PageDescriptor implements Descriptor { createIterator( apiCall: GaxCall, request: RequestType, - options: CallSettings + options: CallSettings, ): AsyncIterable<{} | undefined> { const asyncIterable = { [Symbol.asyncIterator]() { @@ -179,7 +179,7 @@ export class PageDescriptor implements Descriptor { let result: {} | [ResponseType] | null; [result, nextPageRequest] = (await apiCall( nextPageRequest!, - options + options, )) as ResultTuple; // For pagination response with protobuf map type, use tuple as representation. if (result && !Array.isArray(result)) { diff --git a/gax/src/paginationCalls/pagedApiCaller.ts b/gax/src/paginationCalls/pagedApiCaller.ts index bf92b76cc..e22bcf3f5 100644 --- a/gax/src/paginationCalls/pagedApiCaller.ts +++ b/gax/src/paginationCalls/pagedApiCaller.ts @@ -59,7 +59,7 @@ export class PagedApiCaller implements APICaller { */ private generateParseResponseCallback( request: NextPageRequestType, - callback: APICallback + callback: APICallback, ): APICallback { const resourceFieldName = this.pageDescriptor.resourceField; const responsePageTokenFieldName = @@ -72,13 +72,13 @@ export class PagedApiCaller implements APICaller { } if (!request) { callback( - new GoogleError('Undefined request in pagination method callback.') + new GoogleError('Undefined request in pagination method callback.'), ); return; } if (!response) { callback( - new GoogleError('Undefined response in pagination method callback.') + new GoogleError('Undefined response in pagination method callback.'), ); return; } @@ -109,7 +109,7 @@ export class PagedApiCaller implements APICaller { argument, metadata, options, - self.generateParseResponseCallback(argument, callback) + self.generateParseResponseCallback(argument, callback), ); }; } @@ -144,7 +144,7 @@ export class PagedApiCaller implements APICaller { apiCall: SimpleCallbackFunction, request: RequestType, settings: CallOptions, - ongoingCall: OngoingCall + ongoingCall: OngoingCall, ) { request = Object.assign({}, request); @@ -157,7 +157,7 @@ export class PagedApiCaller implements APICaller { warn( 'autoPaginate true', 'Providing a pageSize without setting autoPaginate to false will still return all results. See https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure manual paging', - 'AutopaginateTrueWarning' + 'AutopaginateTrueWarning', ); } @@ -166,7 +166,7 @@ export class PagedApiCaller implements APICaller { const resourceCollector = new ResourceCollector(apiCall, maxResults); resourceCollector.processAllPages(request).then( resources => ongoingCall.callback(null, resources), - err => ongoingCall.callback(err) + err => ongoingCall.callback(err), ); } diff --git a/gax/src/paginationCalls/resourceCollector.ts b/gax/src/paginationCalls/resourceCollector.ts index 268b5b143..bf64a374b 100644 --- a/gax/src/paginationCalls/resourceCollector.ts +++ b/gax/src/paginationCalls/resourceCollector.ts @@ -45,7 +45,7 @@ export class ResourceCollector { private callback( err: Error | null, resources: Array<{}>, - nextPageRequest: NextPageRequestType + nextPageRequest: NextPageRequestType, ) { if (err) { // Something went wrong with this request - failing everything diff --git a/gax/src/pathTemplate.ts b/gax/src/pathTemplate.ts index ae208448c..636b90db7 100644 --- a/gax/src/pathTemplate.ts +++ b/gax/src/pathTemplate.ts @@ -52,11 +52,11 @@ export class PathTemplate { // if the path contains a wildcard, then the length may differ by 1. if (!this.data.includes('**')) { throw new TypeError( - `This path ${path} does not match path template ${this.data}, the number of parameters is not same.` + `This path ${path} does not match path template ${this.data}, the number of parameters is not same.`, ); } else if (pathSegments.length !== this.segments.length + 1) { throw new TypeError( - `This path ${path} does not match path template ${this.data}, the number of parameters is not same with one wildcard.` + `This path ${path} does not match path template ${this.data}, the number of parameters is not same with one wildcard.`, ); } } @@ -68,18 +68,18 @@ export class PathTemplate { if (this.segments[index] !== pathSegments[0]) { if (!this.segments[index].includes('*')) { throw new TypeError( - `segment does not match, ${this.segments[index]} and ${pathSegments[index]}.` + `segment does not match, ${this.segments[index]} and ${pathSegments[index]}.`, ); } else { let segment = this.segments[index]; const matches = segment.match(/\{[$0-9a-zA-Z_]+=.*?\}/g); if (!matches) { throw new Error( - `Error processing path template segment ${segment}` + `Error processing path template segment ${segment}`, ); } const variables = matches.map(str => - str.replace(/^\{/, '').replace(/=.*/, '') + str.replace(/^\{/, '').replace(/=.*/, ''), ); if (segment.includes('**')) { bindings[variables[0]] = pathSegments[0] + '/' + pathSegments[1]; @@ -96,7 +96,7 @@ export class PathTemplate { const value = pathSegments[0].split(/[-_.~]/); if (value.length !== variables.length) { throw new Error( - `segment ${segment} does not match ${pathSegments[0]}` + `segment ${segment} does not match ${pathSegments[0]}`, ); } for (const v of variables) { @@ -107,7 +107,7 @@ export class PathTemplate { // segment: {blurb_id=*}.{legacy_user=*} matching pathSegments: ['bar~user2'] should fail if (segment !== pathSegments[0]) { throw new TypeError( - `non slash resource pattern ${this.segments[index]} and ${pathSegments[0]} should have same separator` + `non slash resource pattern ${this.segments[index]} and ${pathSegments[0]} should have same separator`, ); } } @@ -136,7 +136,7 @@ export class PathTemplate { Object.keys(bindings).length } does not match the number of needed variables ${ Object.keys(this.bindings).length - }` + }`, ); } let path = this.inspect(); @@ -195,11 +195,11 @@ export class PathTemplate { } else if ((matches = segment.match(/\{[0-9a-zA-Z-.~_]+(?:=.*?)?\}/g))) { for (const subsegment of matches) { const pairMatch = subsegment.match( - /^\{([0-9a-zA-Z-.~_]+)(?:=(.*?))?\}$/ + /^\{([0-9a-zA-Z-.~_]+)(?:=(.*?))?\}$/, ); if (!pairMatch) { throw new Error( - `Cannot process path template segment ${subsegment}` + `Cannot process path template segment ${subsegment}`, ); } const key = pairMatch[1]; diff --git a/gax/src/streamArrayParser.ts b/gax/src/streamArrayParser.ts index 7aa03c1f4..4d001894a 100644 --- a/gax/src/streamArrayParser.ts +++ b/gax/src/streamArrayParser.ts @@ -75,9 +75,9 @@ export class StreamArrayParser extends Transform { 'error', new Error( `Internal Error: API service stream data must start with a '[' and close with the corresponding ']', but it start with ${String.fromCharCode( - chunk[0] - )}` - ) + chunk[0], + )}`, + ), ); } curIndex++; diff --git a/gax/src/streamingCalls/streamDescriptor.ts b/gax/src/streamingCalls/streamDescriptor.ts index fc6090d09..2ac1490fb 100644 --- a/gax/src/streamingCalls/streamDescriptor.ts +++ b/gax/src/streamingCalls/streamDescriptor.ts @@ -31,7 +31,7 @@ export class StreamDescriptor implements Descriptor { constructor( streamType: StreamType, rest?: boolean, - gaxStreamingRetries?: boolean + gaxStreamingRetries?: boolean, ) { this.type = streamType; this.streaming = true; diff --git a/gax/src/streamingCalls/streaming.ts b/gax/src/streamingCalls/streaming.ts index 7e22e2399..81f656604 100644 --- a/gax/src/streamingCalls/streaming.ts +++ b/gax/src/streamingCalls/streaming.ts @@ -55,17 +55,17 @@ export interface DuplexifyConstructor { obj( writable?: Writable | false | null, readable?: Readable | false | null, - options?: DuplexifyOptions + options?: DuplexifyOptions, ): Duplexify; new ( writable?: Writable | false | null, readable?: Readable | false | null, - options?: DuplexifyOptions + options?: DuplexifyOptions, ): Duplexify; ( writable?: Writable | false | null, readable?: Readable | false | null, - options?: DuplexifyOptions + options?: DuplexifyOptions, ): Duplexify; } @@ -117,7 +117,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { type: StreamType, callback: APICallback, rest?: boolean, - gaxServerStreamingRetries?: boolean + gaxServerStreamingRetries?: boolean, ) { super(undefined, undefined, { objectMode: true, @@ -163,7 +163,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { totalTimeoutMillis: number, originalError: GoogleError, originalTimeout: number | undefined, - retries: number + retries: number, ): void { const now = new Date(); @@ -177,7 +177,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { const error = new GoogleError( `Total timeout of API exceeded ${originalTimeout} milliseconds ${ originalError ? `retrying error ${originalError} ` : '' - } before any response was received.` + } before any response was received.`, ); error.code = Status.DEADLINE_EXCEEDED; throw error; @@ -191,7 +191,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { const error = new GoogleError( 'Exceeded maximum number of retries ' + (originalError ? `retrying error ${originalError} ` : '') + - 'before any response was received' + 'before any response was received', ); error.code = Status.DEADLINE_EXCEEDED; throw error; @@ -298,7 +298,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { apiCall: SimpleCallbackFunction, argument: {}, retryRequestOptions: RetryRequestOptions = {}, - retry: RetryOptions + retry: RetryOptions, ) { this.apiCall = apiCall; this.argument = argument; @@ -335,7 +335,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { } const stream = apiCall( argument, - this._callback + this._callback, ) as CancellableStream; this.stream = stream; this.forwardEvents(stream); @@ -378,7 +378,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { * @returns {CancellableStream} - the stream that handles retry logic */ private newStreamingRetryRequest( - opts: streamingRetryRequestOptions + opts: streamingRetryRequestOptions, ): CancellableStream { // at this point, it would be unexpected if retry were undefined // but if it is, provide a logical default so we don't run into trouble @@ -402,7 +402,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { } const transientErrorHelper = ( error: Error, - requestStream: CancellableStream + requestStream: CancellableStream, ) => { const e = GoogleError.parseGRPCStatusDetails(error); e.note = @@ -493,7 +493,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { if (maxRetries && totalTimeout) { const newError = new GoogleError( 'Cannot set both totalTimeoutMillis and maxRetries ' + - 'in backoffSettings.' + 'in backoffSettings.', ); newError.code = Status.INVALID_ARGUMENT; // clean up the request stream and retryStreams, silently destroy it on the request stream @@ -512,11 +512,11 @@ export class StreamProxy extends duplexify implements GRPCCallResult { timeout!, error, totalTimeout, - retries + retries, ); } catch (error: unknown) { const e = GoogleError.parseGRPCStatusDetails( - error as GoogleError + error as GoogleError, ); // clean up the request stream and retryStreams, silently destroy it on the request stream // but do raise it on destruction of the retryStream so the consumer can see it @@ -563,7 +563,7 @@ export class StreamProxy extends duplexify implements GRPCCallResult { } const newStream = this.apiCall!( retryArgument, - this._callback + this._callback, ) as CancellableStream; return newStream; }; diff --git a/gax/src/streamingCalls/streamingApiCaller.ts b/gax/src/streamingCalls/streamingApiCaller.ts index 68ddb9855..66bc77fe7 100644 --- a/gax/src/streamingCalls/streamingApiCaller.ts +++ b/gax/src/streamingCalls/streamingApiCaller.ts @@ -48,7 +48,7 @@ export class StreamingApiCaller implements APICaller { this.descriptor.type, callback, this.descriptor.rest, - this.descriptor.gaxStreamingRetries + this.descriptor.gaxStreamingRetries, ); } @@ -63,7 +63,7 @@ export class StreamingApiCaller implements APICaller { argument: {}, metadata: {}, options: {}, - callback?: APICallback + callback?: APICallback, ) => { return (func as ClientStreamingCall)(metadata, options, callback); }; @@ -74,7 +74,7 @@ export class StreamingApiCaller implements APICaller { default: warn( 'streaming_wrap_unknown_stream_type', - `Unknown stream type: ${this.descriptor.type}` + `Unknown stream type: ${this.descriptor.type}`, ); } return func; @@ -84,13 +84,13 @@ export class StreamingApiCaller implements APICaller { apiCall: SimpleCallbackFunction, argument: {}, settings: CallSettings, - stream: StreamProxy + stream: StreamProxy, ) { stream.setStream( apiCall, argument, settings.retryRequestOptions, - settings.retry! + settings.retry!, ); } diff --git a/gax/src/transcoding.ts b/gax/src/transcoding.ts index d4cdf614b..37b399f50 100644 --- a/gax/src/transcoding.ts +++ b/gax/src/transcoding.ts @@ -50,7 +50,7 @@ export type ParsedOptionsType = Array< export function getField( request: JSONObject, field: string, - allowObjects = false // in most cases, we need leaf fields + allowObjects = false, // in most cases, we need leaf fields ): JSONValue | undefined { const parts = field.split('.'); let value: JSONValue = request; @@ -74,7 +74,7 @@ export function getField( export function deepCopyWithoutMatchedFields( request: JSONObject, fieldsToSkip: Set, - fullNamePrefix = '' + fullNamePrefix = '', ): JSONObject { if (typeof request !== 'object' || request === null) { return request; @@ -89,13 +89,13 @@ export function deepCopyWithoutMatchedFields( if (Array.isArray(copy[key])) { // a field of an array cannot be addressed as "request.field", so we omit the skipping logic for array descendants copy[key] = (copy[key] as JSONObject[]).map(value => - deepCopyWithoutMatchedFields(value, new Set()) + deepCopyWithoutMatchedFields(value, new Set()), ); } else if (typeof copy[key] === 'object' && copy[key] !== null) { copy[key] = deepCopyWithoutMatchedFields( copy[key] as JSONObject, fieldsToSkip, - nextFullNamePrefix + nextFullNamePrefix, ); } } @@ -120,7 +120,7 @@ export function deleteField(request: JSONObject, field: string): void { export function buildQueryStringComponents( request: JSONObject, - prefix = '' + prefix = '', ): string[] { const resultList = []; for (const key in request) { @@ -128,19 +128,19 @@ export function buildQueryStringComponents( for (const value of request[key] as JSONObject[]) { resultList.push( `${prefix}${encodeWithoutSlashes(key)}=${encodeWithoutSlashes( - value.toString() - )}` + value.toString(), + )}`, ); } } else if (typeof request[key] === 'object' && request[key] !== null) { resultList.push( - ...buildQueryStringComponents(request[key] as JSONObject, `${key}.`) + ...buildQueryStringComponents(request[key] as JSONObject, `${key}.`), ); } else { resultList.push( `${prefix}${encodeWithoutSlashes(key)}=${encodeWithoutSlashes( - request[key] === null ? 'null' : request[key]!.toString() - )}` + request[key] === null ? 'null' : request[key]!.toString(), + )}`, ); } } @@ -167,7 +167,7 @@ function escapeRegExp(str: string) { export function applyPattern( pattern: string, - fieldValue: string + fieldValue: string, ): string | undefined { if (!pattern || pattern === '*') { return encodeWithSlashes(fieldValue); @@ -183,7 +183,7 @@ export function applyPattern( escapeRegExp(pattern) .replace(/\\\*\\\*/g, '(.+)') .replace(/\\\*/g, '([^/]+)') + - '$' + '$', ); if (!fieldValue.match(regex)) { @@ -205,7 +205,7 @@ interface MatchResult { export function match( request: JSONObject, - pattern: string + pattern: string, ): MatchResult | undefined { let url = pattern; const matchedFields = []; @@ -223,7 +223,7 @@ export function match( } const appliedPattern = applyPattern( pattern, - fieldValue === null ? 'null' : fieldValue!.toString() + fieldValue === null ? 'null' : fieldValue!.toString(), ); if (appliedPattern === undefined) { return undefined; @@ -268,7 +268,7 @@ export function isProto3OptionalField(field: Field) { export function transcode( request: JSONObject, - parsedOptions: ParsedOptionsType + parsedOptions: ParsedOptionsType, ): TranscodedRequest | undefined { const httpRules = []; for (const option of parsedOptions) { @@ -313,7 +313,7 @@ export function transcode( data = getField( queryStringObject, fieldToCamelCase(httpRule.body), - /*allowObjects:*/ true + /*allowObjects:*/ true, ); deleteField(queryStringObject, fieldToCamelCase(httpRule.body)); } else { @@ -337,7 +337,7 @@ export function transcode( // Override the protobuf json's the http rules. export function overrideHttpRules( httpRules: Array, - protoJson: protobuf.Root + protoJson: protobuf.Root, ) { for (const rule of httpRules) { if (!rule.selector) { diff --git a/gax/src/util.ts b/gax/src/util.ts index 8aab5e316..e52e241ef 100644 --- a/gax/src/util.ts +++ b/gax/src/util.ts @@ -13,7 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {v4 as uuidv4} from 'uuid'; +const randomUUID = () => + globalThis.crypto?.randomUUID() || require('crypto').randomUUID(); function words(str: string, normalize = false) { if (normalize) { @@ -88,7 +89,7 @@ export function toCamelCase(str: string) { return '_' + w; } return capitalize(w); - }) + }), ); return result.join(''); } @@ -110,5 +111,5 @@ export function toLowerCamelCase(str: string) { * in lower case). */ export function makeUUID() { - return uuidv4(); + return randomUUID(); } diff --git a/gax/test/browser-test/karma.conf.js b/gax/test/browser-test/karma.conf.js index 8b79b3868..db543d346 100644 --- a/gax/test/browser-test/karma.conf.js +++ b/gax/test/browser-test/karma.conf.js @@ -30,26 +30,23 @@ module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', - // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'child-process'], + files: ['./test/*.ts'], client: { childProcess: { path: path.relative( process.cwd(), // eslint-disable-next-line n/no-missing-require - require.resolve('showcase-server/build/src/index.js') + require.resolve('showcase-server/build/src/index.js'), ), args: [], options: {}, }, }, - // list of files / patterns to load in the browser - files: ['./test/test.*.ts'], - // list of files / patterns to exclude exclude: [], @@ -60,7 +57,6 @@ module.exports = function (config) { }, webpack: webpackConfig, - // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter @@ -96,14 +92,16 @@ module.exports = function (config) { // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, - + // list of files / patterns to load in the browser // Concurrency level // how many browser should be started simultaneous concurrency: Infinity, - // set correct MIME type when serving .ts files (already compiled to JavaScript): mime: { 'text/javascript': ['ts'], }, + browserDisconnectTimeout: 60000, // Increase to 60 seconds (or more) + browserNoActivityTimeout: 60000, + mode: 'development', }); }; diff --git a/gax/test/browser-test/package.json b/gax/test/browser-test/package.json index 5171769db..e98611d88 100644 --- a/gax/test/browser-test/package.json +++ b/gax/test/browser-test/package.json @@ -8,7 +8,7 @@ "build/test" ], "engines": { - "node": ">=14" + "node": ">=18" }, "license": "Apache-2.0", "keywords": [], @@ -25,23 +25,31 @@ }, "devDependencies": { "@types/mocha": "^9.1.1", - "@types/node": "^14.11.2", + "@types/node": "^20.5.0", "@types/sinon": "^10.0.13", + "assert": "^2.1.0", + "core-js": "^3.40.0", "google-gax": "./google-gax.tgz", + "https-browserify": "^1.0.0", "is-docker": "^2.2.1", - "karma": "^6.0.0", - "karma-child-process": "^1.0.3", - "karma-chrome-launcher": "^3.0.0", - "karma-mocha": "^2.0.0", - "karma-sourcemap-loader": "^0.3.7", - "karma-webpack": "^4.0.0", + "karma": "^6.4.4", + "karma-child-process": "^1.0.14", + "karma-chrome-launcher": "^3.2.0", + "karma-mocha": "^2.0.1", + "karma-sourcemap-loader": "^0.4.0", + "karma-webpack": "^5.0.1", "mocha": "^10.0.0", + "process": "^0.11.10", "puppeteer": "^16.0.0", + "querystring-es3": "^0.2.1", "showcase-echo-client": "./showcase-echo-client.tgz", "showcase-server": "./showcase-server.tgz", "sinon": "^14.0.0", - "typescript": "^4.0.3", - "webpack": "^4.0.0", + "stream-browserify": "^3.0.0", + "stream-http": "^3.2.0", + "typescript": "^5.7.3", + "url": "^0.11.4", + "webpack": "^5.97.1", "webpack-cli": "^4.0.0" } } diff --git a/gax/test/browser-test/test/test.endtoend.ts b/gax/test/browser-test/test/test.endtoend.ts index 1d9556dbc..77cec9f94 100644 --- a/gax/test/browser-test/test/test.endtoend.ts +++ b/gax/test/browser-test/test/test.endtoend.ts @@ -18,6 +18,7 @@ import * as assert from 'assert'; import {describe, it, before} from 'mocha'; import {GoogleAuth} from 'google-gax'; import {EchoClient} from 'showcase-echo-client'; +import 'core-js/stable'; function sleep(timeout: number) { return new Promise(resolve => { @@ -25,7 +26,7 @@ function sleep(timeout: number) { }); } -describe('Run tests against gRPC server', () => { +describe('Run tests against gRPC server', async function () { const authStub = { getClient: async () => { return { @@ -76,6 +77,7 @@ describe('Run tests against gRPC server', () => { }); it('should be able to call simple RPC methods', async () => { + this.timeout(80000); const request = { content: 'test', }; diff --git a/gax/test/browser-test/test/test.grpc-fallback.ts b/gax/test/browser-test/test/test.grpc-fallback.ts index 768242e9b..1b294036d 100644 --- a/gax/test/browser-test/test/test.grpc-fallback.ts +++ b/gax/test/browser-test/test/test.grpc-fallback.ts @@ -21,6 +21,7 @@ import {after, afterEach, before, beforeEach, describe, it} from 'mocha'; import * as sinon from 'sinon'; import {protobuf, GoogleAuth, fallback} from 'google-gax'; import {EchoClient} from 'showcase-echo-client'; +import 'core-js/stable'; import echoProtoJson = require('showcase-echo-client/build/protos/protos.json'); diff --git a/gax/test/browser-test/tsconfig.json b/gax/test/browser-test/tsconfig.json index 696defbe7..21b519c62 100644 --- a/gax/test/browser-test/tsconfig.json +++ b/gax/test/browser-test/tsconfig.json @@ -4,10 +4,11 @@ "rootDir": ".", "outDir": "build", "resolveJsonModule": true, - "lib": ["ES2018", "DOM"] + "lib": ["DOM"] }, "include": [ "src/**/*.ts", - "test/**/*.ts" + "test/**/*.ts", + "src/**/*.json", ] } diff --git a/gax/test/browser-test/webpack.config.js b/gax/test/browser-test/webpack.config.js index b8a8b6a11..448e04819 100644 --- a/gax/test/browser-test/webpack.config.js +++ b/gax/test/browser-test/webpack.config.js @@ -13,12 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable n/no-missing-require */ +const webpack = require('webpack'); module.exports = { entry: './build/src/index.js', resolve: { extensions: ['.ts', '.js', '.json'], + fallback: { + fs: 'empty', + child_process: 'empty', + // eslint-disable-next-line n/no-extraneous-require + assert: require.resolve('assert/'), + util: require.resolve('util'), + stream: require.resolve('stream-browserify'), + http: require.resolve('stream-http'), + https: require.resolve('https-browserify'), + querystring: require.resolve('querystring-es3'), + url: require.resolve('url/'), + }, }, + plugins: [ + new webpack.ProvidePlugin({ + process: 'process/browser', + }), + new webpack.ProvidePlugin({ + Buffer: ['buffer', 'Buffer'], + }), + ], module: { rules: [ { @@ -44,9 +66,6 @@ module.exports = { }, ], }, - node: { - fs: 'empty', - child_process: 'empty', - }, - mode: 'production', + cache: false, + mode: 'development', }; diff --git a/gax/test/showcase-echo-client/package.json b/gax/test/showcase-echo-client/package.json index 3720c326f..e4dc00ed7 100644 --- a/gax/test/showcase-echo-client/package.json +++ b/gax/test/showcase-echo-client/package.json @@ -37,9 +37,9 @@ "devDependencies": { "@types/node": "^20.11.26", "gapic-tools": "./gapic-tools.tgz", - "typescript": "^4.5.5" + "typescript": "^5.7.3" }, "engines": { - "node": ">=v14" + "node": ">=v18" } } diff --git a/gax/test/showcase-echo-client/tsconfig.json b/gax/test/showcase-echo-client/tsconfig.json index 81cb00448..e43e06476 100644 --- a/gax/test/showcase-echo-client/tsconfig.json +++ b/gax/test/showcase-echo-client/tsconfig.json @@ -12,5 +12,7 @@ "include": [ "src/*.ts", "src/**/*.ts", + "src/**/*.json", + "protos/protos.json" ] } diff --git a/gax/test/showcase-server/package.json b/gax/test/showcase-server/package.json index 327552427..54d7cd6bd 100644 --- a/gax/test/showcase-server/package.json +++ b/gax/test/showcase-server/package.json @@ -22,10 +22,10 @@ }, "devDependencies": { "@types/download": "^8.0.1", - "@types/node": "^14.11.2", - "typescript": "^4.0.3" + "@types/node": "^18.11.2", + "typescript": "^5.7.3" }, "engines": { - "node": ">=14" + "node": ">=18" } } diff --git a/gax/test/system-test/test.clientlibs.ts b/gax/test/system-test/test.clientlibs.ts index b236a7b3e..56867dbce 100644 --- a/gax/test/system-test/test.clientlibs.ts +++ b/gax/test/system-test/test.clientlibs.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as execa from 'execa'; +import execa from 'execa'; import * as fs from 'fs'; import * as fsp from 'fs/promises'; import * as path from 'path'; @@ -43,7 +43,7 @@ const toolsTarball = path.join(gaxDir, toolsBasename); async function latestRelease( cwd: string, - inMonorepo: boolean + inMonorepo: boolean, ): Promise { // tags in the monorepo follow the format -major.minor.patch e.g. batch-0.0.1 // or the format -vmajor.minor.patch e.g. batch-v0.0.1 @@ -84,12 +84,12 @@ async function latestRelease( function monoRepoPackageSubdirectory(packageName: string): string { return `${monoRepoDirectory}/packages/google-cloud-${packageName.replace( '-', - '' + '', )}`; } async function preparePackage( packageName: string, - inMonorepo: boolean + inMonorepo: boolean, ): Promise { // clone googleapis/google-cloud node if monorepo, googleapis/nodejs- if not const repoUrl = inMonorepo @@ -101,7 +101,7 @@ async function preparePackage( await execa( 'git', ['clone', repoUrl, inMonorepo ? monoRepoDirectory : packageName], - {stdio: 'inherit'} + {stdio: 'inherit'}, ); clonedRepos.push(repoUrl); } catch (error: unknown) { @@ -118,7 +118,7 @@ async function preparePackage( const packagePath = monoRepoPackageSubdirectory(packageName); // used if in monoRepo const packageJson = path.join( inMonorepo ? packagePath : packageName, - 'package.json' + 'package.json', ); const packageJsonStr = (await readFile(packageJson)).toString(); const packageJsonObj = JSON.parse(packageJsonStr); @@ -140,7 +140,7 @@ enum TestResult { async function runScript( packageName: string, inMonorepo: boolean, - script: string + script: string, ): Promise { try { await execa('npm', ['run', script], { @@ -160,7 +160,7 @@ async function runScript( async function runSystemTest( packageName: string, - inMonorepo: boolean + inMonorepo: boolean, ): Promise { return await runScript(packageName, inMonorepo, 'system-test'); } @@ -183,7 +183,7 @@ describe('Run system tests for some libraries', () => { }); await fs.promises.rename( path.join(gaxDir, '..', 'tools', toolsBasename), - toolsTarball + toolsTarball, ); if (!fs.existsSync(toolsTarball)) { throw new Error(`npm pack tarball ${toolsTarball} does not exist`); diff --git a/gax/test/test-application/package.json b/gax/test/test-application/package.json index dbef3840c..6af31e90d 100644 --- a/gax/test/test-application/package.json +++ b/gax/test/test-application/package.json @@ -32,6 +32,6 @@ "showcase-server": "./showcase-server.tgz" }, "engines": { - "node": ">=14.0.0" + "node": ">=18.0.0" } } diff --git a/gax/test/unit/apiCallable.ts b/gax/test/unit/apiCallable.ts index 4a17d590b..d31e6c64d 100644 --- a/gax/test/unit/apiCallable.ts +++ b/gax/test/unit/apiCallable.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {status} from '@grpc/grpc-js'; import {afterEach, describe, it} from 'mocha'; import * as sinon from 'sinon'; @@ -34,51 +34,49 @@ describe('createApiCall', () => { afterEach(() => { sinon.restore(); }); - it('calls api call', done => { + it('calls api call', async () => { let deadlineArg: {}; function func( argument: {}, metadata: {}, options: {deadline: string}, - callback: Function + callback: Function, ) { deadlineArg = options.deadline; callback(null, argument); } const apiCall = createApiCall(func); - apiCall(42, undefined, (err, resp) => { + await apiCall(42, undefined, (err, resp) => { assert.strictEqual(resp, 42); assert.ok(deadlineArg); - done(); }); }); - it('is customized by call options', done => { + it('is customized by call options', async () => { function func( argument: {}, metadata: {}, options: {deadline: {getTime: Function}}, - callback: Function + callback: Function, ) { callback(null, options.deadline.getTime()); } const apiCall = createApiCall(func, {settings: {timeout: 100}}); - apiCall({}, {timeout: 200}, (err, resp) => { + await apiCall({}, {timeout: 200}, (err, resp) => { const now = new Date(); const originalDeadline = now.getTime() + 100; const expectedDeadline = now.getTime() + 200; assert((resp as unknown as number)! > originalDeadline); assert((resp as unknown as number)! <= expectedDeadline); - done(); }); }); - it('chooses the proper timeout', done => { + it('chooses the proper timeout', async () => { function func( argument: {}, metadata: {}, options: {deadline: {getTime: Function}}, - callback: Function + callback: Function, ) { callback(null, options.deadline.getTime()); } @@ -91,28 +89,27 @@ describe('createApiCall', () => { timeout: 30000, retry: gax.createRetryOptions( [], - gax.createBackoffSettings(100, 1.2, 1000, 2000, 1.5, 30000, 45000) + gax.createBackoffSettings(100, 1.2, 1000, 2000, 1.5, 30000, 45000), ), }, }); const start = new Date().getTime(); - apiCall({}, undefined, (err, resp) => { + await apiCall({}, undefined, (err, resp) => { // The verifying value is slightly bigger than the expected number // 2000 / 30000, because sometimes runtime can consume some time before // the call starts. assert(Number(resp) - start > 2100); assert(Number(resp) - start <= 30100); - done(); }); }); - it('default to `timeout` for idempotent API calls', done => { + it('default to `timeout` for idempotent API calls', async () => { function func( argument: {}, metadata: {}, options: {deadline: {getTime: Function}}, - callback: Function + callback: Function, ) { callback(null, options.deadline.getTime()); } @@ -131,31 +128,25 @@ describe('createApiCall', () => { }); const start = new Date().getTime(); - apiCall({}, undefined, (err, resp) => { + await apiCall({}, undefined, (err, resp) => { // The verifying value is slightly bigger than the expected number // 2000 / 30000, because sometimes runtime can consume some time before // the call starts. assert(Number(resp) - start > 2100); assert(Number(resp) - start <= 30100); - done(); }); }); - it('override just custom retry.retryCodes with retry codes', done => { + it('override just custom retry.retryCodes with retry codes', () => { const initialRetryCodes = [1]; const overrideRetryCodes = [1, 2, 3]; // eslint-disable-next-line @typescript-eslint/no-explicit-any sinon.stub(retries, 'retryable').callsFake((func, retry): any => { - try { - assert.strictEqual(retry.retryCodes, overrideRetryCodes); - return func; - } catch (err) { - done(err); - } + assert.strictEqual(retry.retryCodes, overrideRetryCodes); return func; }); function func() { - done(); + return; } const apiCall = createApiCall(func, { settings: { @@ -176,8 +167,8 @@ describe('createApiCall', () => { retry: { retryCodes: overrideRetryCodes, }, - } - ); + }, + ).catch(console.error); }); it('errors when you override custom retry.shouldRetryFn with a function on a non streaming call', async () => { function neverRetry() { @@ -209,18 +200,18 @@ describe('createApiCall', () => { retry: { shouldRetryFn: overrideRetryCodes, }, - } + }, ); } catch (err) { assert(err instanceof Error); assert.strictEqual( err.message, - 'Using a function to determine retry eligibility is only supported with server streaming calls' + 'Using a function to determine retry eligibility is only supported with server streaming calls', ); } }); - it('override just custom retry.backoffSettings', done => { + it('override just custom retry.backoffSettings', () => { const initialBackoffSettings = gax.createDefaultBackoffSettings(); const overriBackoffSettings = gax.createBackoffSettings( 100, @@ -229,7 +220,7 @@ describe('createApiCall', () => { null, 1.5, 3000, - 4500 + 4500, ); // eslint-disable-next-line @typescript-eslint/no-explicit-any sinon.stub(retries, 'retryable').callsFake((func, retry): any => { @@ -238,7 +229,7 @@ describe('createApiCall', () => { }); function func() { - done(); + return; } const apiCall = createApiCall(func, { @@ -253,8 +244,8 @@ describe('createApiCall', () => { retry: { backoffSettings: overriBackoffSettings, }, - } - ); + }, + ).catch(console.error); }); it('errors when a resumption strategy is passed for a non streaming call', async () => { @@ -266,7 +257,7 @@ describe('createApiCall', () => { null, 1.5, 3000, - 4500 + 4500, ); // "resumption" strategy is to just return the original request const getResumptionRequestFn = (originalRequest: RequestType) => { @@ -274,7 +265,7 @@ describe('createApiCall', () => { }; function func() { - Promise.resolve(); + Promise.resolve().catch(console.error); } const apiCall = createApiCall(func, { settings: { @@ -282,7 +273,7 @@ describe('createApiCall', () => { [1], initialBackoffSettings, undefined, - getResumptionRequestFn + getResumptionRequestFn, ), }, }); @@ -294,13 +285,13 @@ describe('createApiCall', () => { retry: { backoffSettings: overriBackoffSettings, }, - } + }, ); } catch (err) { assert(err instanceof Error); assert.strictEqual( err.message, - 'Resumption strategy can only be used with server streaming retries' + 'Resumption strategy can only be used with server streaming retries', ); } }); @@ -313,7 +304,7 @@ describe('Promise', () => { argument: {}, metadata: {}, options: {deadline: string}, - callback: Function + callback: Function, ) { deadlineArg = options.deadline; callback(null, 42); @@ -418,7 +409,7 @@ describe('Promise', () => { assert.strictEqual(response, 42); done(); }), - undefined + undefined, ); }); }); @@ -429,14 +420,14 @@ describe('retryable', () => { settings: {timeout: 0, retry: retryOptions, apiName: 'TestApi'}, }; - it('retries the API call', done => { + it('retries the API call', async () => { let toAttempt = 3; let deadlineArg: string; function func( argument: {}, metadata: {}, options: {deadline: string}, - callback: Function + callback: Function, ) { deadlineArg = options.deadline; toAttempt--; @@ -447,22 +438,21 @@ describe('retryable', () => { callback(null, 1729); } const apiCall = createApiCall(func, settings); - apiCall({}, undefined, (err, resp) => { + await apiCall({}, undefined, (err, resp) => { assert.strictEqual(resp, 1729); assert.strictEqual(toAttempt, 0); assert(deadlineArg); - done(); }); }); - it('retries the API call with promise', done => { + it('retries the API call with promise', async () => { let toAttempt = 3; let deadlineArg: string; function func( argument: {}, metadata: {}, options: {deadline: string}, - callback: Function + callback: Function, ) { deadlineArg = options.deadline; toAttempt--; @@ -473,15 +463,12 @@ describe('retryable', () => { callback(null, 1729); } const apiCall = createApiCall(func, settings); - apiCall({}, undefined) - .then(resp => { - assert.ok(Array.isArray(resp)); - assert.strictEqual(resp[0], 1729); - assert.strictEqual(toAttempt, 0); - assert.ok(deadlineArg); - done(); - }) - .catch(done); + await apiCall({}, undefined).then(resp => { + assert.ok(Array.isArray(resp)); + assert.strictEqual(resp[0], 1729); + assert.strictEqual(toAttempt, 0); + assert.ok(deadlineArg); + }); }); it('cancels in the middle of retries', done => { @@ -512,29 +499,27 @@ describe('retryable', () => { }); }); - it("doesn't retry if no codes", done => { + it("doesn't retry if no codes", async () => { const retryOptions = gax.createRetryOptions( [], - gax.createBackoffSettings(1, 2, 3, 4, 5, 6, 7) + gax.createBackoffSettings(1, 2, 3, 4, 5, 6, 7), ); const settings = {settings: {timeout: 0, retry: retryOptions}}; const spy = sinon.spy(fail); const apiCall = createApiCall(spy, settings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert.ok(err instanceof Error); assert.strictEqual(err!.code, FAKE_STATUS_CODE_1); assert.strictEqual(err!.note, undefined); assert.strictEqual(spy.callCount, 1); - done(); }); }); - it('aborts retries', done => { + it('aborts retries', async () => { const apiCall = createApiCall(fail, settings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert(err instanceof GoogleError); assert.strictEqual(err!.code, status.DEADLINE_EXCEEDED); - done(); }); }); @@ -548,10 +533,10 @@ describe('retryable', () => { assert(err!.note); assert.strictEqual(spy.callCount, toAttempt); done(); - }); + }).catch(console.error); }); - it('errors on maxRetries and surfaces original error', done => { + it('errors on maxRetries and surfaces original error', async () => { const toAttempt = 5; const backoff = gax.createMaxRetriesBackoffSettings( 0, @@ -560,7 +545,7 @@ describe('retryable', () => { 0, 0, 0, - toAttempt + toAttempt, ); const maxRetriesRetryOptions = utils.createRetryOptions(backoff); @@ -569,35 +554,33 @@ describe('retryable', () => { }; const spy = sinon.spy(fail); const apiCall = createApiCall(spy, maxRetrySettings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert.ok(err instanceof GoogleError); assert.strictEqual(err!.code, status.DEADLINE_EXCEEDED); assert.strictEqual(spy.callCount, toAttempt); assert.match( err.message, - /Exceeded maximum number of retries retrying error Error before any response was received/ + /Exceeded maximum number of retries retrying error Error before any response was received/, ); - done(); }); }); - it('retry fails for exceeding total timeout, surfacing original error', done => { + it('retry fails for exceeding total timeout, surfacing original error', async () => { const spy = sinon.spy(fail); const apiCall = createApiCall(spy, settings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert.ok(err instanceof GoogleError); assert.match( err.message, - /Total timeout of API TestApi exceeded 100 milliseconds retrying error Error {2}before any response was received/ + /Total timeout of API TestApi exceeded 100 milliseconds retrying error Error {2}before any response was received/, ); assert.strictEqual(err!.code, status.DEADLINE_EXCEEDED); - done(); }); }); // maxRetries is unsupported, and intended for internal use only or // use with retry-request backwards compatibility - it('errors when totalTimeoutMillis and maxRetries set', done => { + it('errors when totalTimeoutMillis and maxRetries set', async () => { const maxRetries = 5; const backoff = gax.createMaxRetriesBackoffSettings( 0, @@ -606,7 +589,7 @@ describe('retryable', () => { 0, 0, 0, - maxRetries + maxRetries, ); const maxRetriesRetryOptions = utils.createRetryOptions(backoff); maxRetriesRetryOptions.backoffSettings.totalTimeoutMillis = 100; @@ -615,15 +598,14 @@ describe('retryable', () => { }; const spy = sinon.spy(fail); const apiCall = createApiCall(spy, maxRetrySettings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert(err instanceof GoogleError); assert.strictEqual(err!.code, status.INVALID_ARGUMENT); assert.strictEqual(spy.callCount, 0); - done(); }); }); - it('aborts on unexpected exception', done => { + it('aborts on unexpected exception', async () => { function func(argument: {}, metadata: {}, options: {}, callback: Function) { const error = new GoogleError(); error.code = FAKE_STATUS_CODE_2; @@ -631,24 +613,22 @@ describe('retryable', () => { } const spy = sinon.spy(func); const apiCall = createApiCall(spy, settings); - apiCall({}, undefined, err => { + await apiCall({}, undefined, err => { assert(err instanceof Error); assert.strictEqual(err!.code, FAKE_STATUS_CODE_2); assert(err!.note); assert.strictEqual(spy.callCount, 1); - done(); }); }); - it('does not retry even when no responses', done => { + it('does not retry even when no responses', async () => { function func(argument: {}, metadata: {}, options: {}, callback: Function) { callback(null, null); } const apiCall = createApiCall(func, settings); - apiCall({}, undefined, (err, resp) => { + await apiCall({}, undefined, (err, resp) => { assert.strictEqual(err, null); assert.strictEqual(resp, null); - done(); }); }); @@ -668,7 +648,7 @@ describe('retryable', () => { assert(err!.note); const now = new Date(); assert( - now.getTime() - startTime.getTime() >= backoff.totalTimeoutMillis! + now.getTime() - startTime.getTime() >= backoff.totalTimeoutMillis!, ); const callsLowerBound = backoff.totalTimeoutMillis! / @@ -678,7 +658,7 @@ describe('retryable', () => { assert(spy.callCount > callsLowerBound); assert(spy.callCount < callsUpperBound); done(); - }); + }).catch(console.error); }); it.skip('reports A/B testing', () => { @@ -706,7 +686,7 @@ describe('retryable', () => { 0, 0, 0, - 5 + 5, ); mockBuilder.withExactArgs({retry: '1'}); return apiCall({}, {retry: utils.createRetryOptions(backoff)}); @@ -725,7 +705,7 @@ describe('retryable', () => { }); }); - it('forwards metadata to builder', done => { + it('forwards metadata to builder', async () => { function func(argument: {}, metadata: {}, options: {}, callback: Function) { callback(null, {}); } @@ -744,10 +724,9 @@ describe('retryable', () => { h1: 'val1', h2: 'val2', }; - apiCall({}, {otherArgs: {headers}}).then(() => { + await apiCall({}, {otherArgs: {headers}}).then(() => { assert.strictEqual(gotHeaders.h1, 'val1'); assert.strictEqual(gotHeaders.h2, 'val2'); - done(); }); }); }); diff --git a/gax/test/unit/bundling.ts b/gax/test/unit/bundling.ts index d757d311b..ac16ae0b6 100644 --- a/gax/test/unit/bundling.ts +++ b/gax/test/unit/bundling.ts @@ -17,7 +17,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-prototype-builtins */ -import * as assert from 'assert'; +import assert from 'assert'; import {status} from '@grpc/grpc-js'; import * as sinon from 'sinon'; import {describe, it, beforeEach} from 'mocha'; @@ -107,7 +107,7 @@ describe('computeBundleId', () => { it(t.message, () => { assert.strictEqual( computeBundleId(t.object as unknown as RequestType, t.fields), - t.want + t.want, ); }); }); @@ -215,7 +215,7 @@ describe('Task', () => { task: any, elements: string[] | number[], // eslint-disable-next-line @typescript-eslint/no-explicit-any - callback?: any + callback?: any, ) { if (!callback) { callback = () => {}; @@ -256,7 +256,7 @@ describe('Task', () => { assert.strictEqual( task.getElementCount(), baseCount! + t.want, - t.message + t.message, ); }); }); @@ -271,7 +271,7 @@ describe('Task', () => { extendElements(task, t.data); assert.strictEqual( task.getRequestByteSize(), - baseSize! + t.want * sizePerData + baseSize! + t.want * sizePerData, ); }); }); @@ -511,7 +511,7 @@ describe('Executor', () => { 'field1', ['field2'], 'field1', - byteLength + byteLength, ); return new BundleExecutor(options, descriptor); } @@ -636,9 +636,9 @@ describe('Executor', () => { assert.deepStrictEqual(resp.field1, [3, 4]); assert.strictEqual(spyApi.callCount, 1); done(); - } + }, ); - } + }, ); assert.strictEqual(spyApi.callCount, 0); canceller.cancel(); @@ -750,7 +750,7 @@ describe('Executor', () => { assert(err instanceof GoogleError); assert.strictEqual(err!.code, status.INVALID_ARGUMENT); done(); - } + }, ); }); @@ -787,7 +787,7 @@ describe('Executor', () => { assert(err instanceof GoogleError); assert.strictEqual(err!.code, status.INVALID_ARGUMENT); done(); - } + }, ); }); @@ -862,34 +862,31 @@ describe('bundleable', () => { 'field1', ['field2'], 'field1', - byteLength + byteLength, ); const settings = { settings: {bundleOptions}, descriptor, }; - it('bundles requests', done => { + it('bundles requests', async () => { const spy = sinon.spy(func); const callback = sinon.spy(obj => { assert(Array.isArray(obj)); assert.deepStrictEqual(obj[0].field1, [1, 2, 3]); if (callback.callCount === 2) { assert.strictEqual(spy.callCount, 1); - done(); } }); const apiCall = createApiCall(spy, settings); - apiCall({field1: [1, 2, 3], field2: 'id'}, undefined, (err, obj) => { + await apiCall({field1: [1, 2, 3], field2: 'id'}, undefined, (err, obj) => { if (err) { - done(err); + throw err; } else { callback([obj]); } }); - apiCall({field1: [1, 2, 3], field2: 'id'}, undefined) - .then(callback) - .catch(done); + await apiCall({field1: [1, 2, 3], field2: 'id'}, undefined).then(callback); }); it('does not fail if bundle field is not set', done => { @@ -978,12 +975,12 @@ describe('bundleable', () => { p.cancel(); }); - it('properly processes camel case fields', done => { + it('properly processes camel case fields', async () => { const descriptor = new BundleDescriptor( 'data', ['log_name'], 'data', - byteLength + byteLength, ); const settings = { settings: {bundleOptions}, @@ -993,34 +990,33 @@ describe('bundleable', () => { const callback = sinon.spy(() => { if (callback.callCount === 4) { assert.strictEqual(spy.callCount, 2); // we expect two requests, each has two items - done(); } }); const apiCall = createApiCall(spy, settings); - apiCall({data: ['data1'], logName: 'log1'}, undefined, err => { + await apiCall({data: ['data1'], logName: 'log1'}, undefined, err => { if (err) { - done(err); + throw err; } else { callback(); } }); - apiCall({data: ['data1'], logName: 'log2'}, undefined, err => { + await apiCall({data: ['data1'], logName: 'log2'}, undefined, err => { if (err) { - done(err); + throw err; } else { callback(); } }); - apiCall({data: ['data2'], logName: 'log1'}, undefined, err => { + await apiCall({data: ['data2'], logName: 'log1'}, undefined, err => { if (err) { - done(err); + throw err; } else { callback(); } }); - apiCall({data: ['data2'], logName: 'log2'}, undefined, err => { + await apiCall({data: ['data2'], logName: 'log2'}, undefined, err => { if (err) { - done(err); + throw err; } else { callback(); } diff --git a/gax/test/unit/exports.ts b/gax/test/unit/exports.ts index 032ddc574..8132209b4 100644 --- a/gax/test/unit/exports.ts +++ b/gax/test/unit/exports.ts @@ -16,7 +16,7 @@ import * as index from '../../src/index'; import * as fallback from '../../src/fallback'; -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; const version = require('../../../package.json').version; diff --git a/gax/test/unit/fallbackError.ts b/gax/test/unit/fallbackError.ts index de8ba72b1..ad2479a55 100644 --- a/gax/test/unit/fallbackError.ts +++ b/gax/test/unit/fallbackError.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import * as fs from 'fs'; import * as path from 'path'; @@ -46,7 +46,7 @@ describe('gRPC-fallback error decoding', () => { assert.strictEqual(decodedError.message, expectedError.message); assert.strictEqual( JSON.stringify(decodedError.statusDetails), - JSON.stringify(expectedError.details) + JSON.stringify(expectedError.details), ); }); @@ -56,7 +56,7 @@ describe('gRPC-fallback error decoding', () => { const errorBin = fs.readFileSync(fixtureName); const expectedError = Object.assign( new Error( - '3 INVALID_ARGUMENT: One of content, or gcs_content_uri must be set.' + '3 INVALID_ARGUMENT: One of content, or gcs_content_uri must be set.', ), { code: 3, @@ -70,7 +70,7 @@ describe('gRPC-fallback error decoding', () => { ], }, ], - } + }, ); const decoder = new GoogleErrorDecoder(); const decodedError = decoder.decodeErrorFromBuffer(errorBin); @@ -80,7 +80,7 @@ describe('gRPC-fallback error decoding', () => { assert.strictEqual(decodedError.message, expectedError.message); assert.strictEqual( JSON.stringify(decodedError.statusDetails), - JSON.stringify(expectedError.details) + JSON.stringify(expectedError.details), ); }); @@ -91,7 +91,7 @@ describe('gRPC-fallback error decoding', () => { '..', 'protos', 'google', - 'rpc' + 'rpc', ); const root = protobuf.loadSync([ path.join(protos_path, 'error_details.proto'), @@ -115,7 +115,7 @@ describe('gRPC-fallback error decoding', () => { reason: errorInfo.reason, domain: errorInfo.domain, errorInfoMetadata: errorInfo.metadata, - } + }, ); const status = Object.assign(new Error('mock error.'), { code: 7, @@ -134,7 +134,7 @@ describe('gRPC-fallback error decoding', () => { assert.strictEqual(decodedError.message, expectedError.message); assert.strictEqual( JSON.stringify(decodedError.statusDetails), - JSON.stringify(expectedError.details) + JSON.stringify(expectedError.details), ); }); }); diff --git a/gax/test/unit/gax.ts b/gax/test/unit/gax.ts index 846dd51a0..214b3d07d 100644 --- a/gax/test/unit/gax.ts +++ b/gax/test/unit/gax.ts @@ -22,7 +22,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import * as gax from '../../src/gax'; @@ -76,7 +76,7 @@ function expectRetryOptions(obj: gax.RetryOptions) { assert.ok(obj instanceof Object); ['retryCodes', 'backoffSettings'].forEach(k => // eslint-disable-next-line no-prototype-builtins - assert.ok(obj.hasOwnProperty(k)) + assert.ok(obj.hasOwnProperty(k)), ); assert.ok(Array.isArray(obj.retryCodes)); expectBackoffSettings(obj.backoffSettings); @@ -106,7 +106,7 @@ describe('gax construct settings', () => { A_CONFIG, {}, RETRY_DICT, - otherArgs + otherArgs, ); let settings = defaults.bundlingMethod; assert.strictEqual(settings.timeout, 40000); @@ -137,7 +137,7 @@ describe('gax construct settings', () => { SERVICE_NAME, A_CONFIG, overrides, - RETRY_DICT + RETRY_DICT, ); let settings = defaults.bundlingMethod; assert.strictEqual(settings.timeout, 40000); @@ -179,7 +179,7 @@ describe('gax construct settings', () => { SERVICE_NAME, A_CONFIG, overrides, - RETRY_DICT + RETRY_DICT, ); let settings = defaults.bundlingMethod; diff --git a/gax/test/unit/googleError.ts b/gax/test/unit/googleError.ts index a4bc7bd1d..47b8a8523 100644 --- a/gax/test/unit/googleError.ts +++ b/gax/test/unit/googleError.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import * as fs from 'fs'; import * as util from 'util'; @@ -34,7 +34,7 @@ describe('gRPC-google error decoding', () => { __dirname, '..', 'fixtures', - 'multipleErrors.json' + 'multipleErrors.json', ); const protos_path = path.resolve( __dirname, @@ -42,7 +42,7 @@ describe('gRPC-google error decoding', () => { '..', 'protos', 'google', - 'rpc' + 'rpc', ); const root = protobuf.loadSync([ path.join(protos_path, 'error_details.proto'), @@ -72,17 +72,17 @@ describe('gRPC-google error decoding', () => { const Status = root.lookupType('google.rpc.Status'); const statusBuffer = Status.encode(status).finish() as Buffer; const gRPCStatusDetailsObj = decoder.decodeGRPCStatusDetails( - new Array(statusBuffer) + new Array(statusBuffer), ); assert.strictEqual( JSON.stringify(expectedErrorArr), - JSON.stringify(gRPCStatusDetailsObj.details) + JSON.stringify(gRPCStatusDetailsObj.details), ); assert.deepStrictEqual( JSON.stringify(gRPCStatusDetailsObj.errorInfo), JSON.stringify( - objs.find(item => item.type === 'google.rpc.ErrorInfo')?.value - ) + objs.find(item => item.type === 'google.rpc.ErrorInfo')?.value, + ), ); }); @@ -96,7 +96,7 @@ describe('gRPC-google error decoding', () => { // nested error messages have different types so we can't use deepStrictEqual here assert.strictEqual( JSON.stringify(gRPCStatusDetailsObj.details), - JSON.stringify([]) + JSON.stringify([]), ); assert.strictEqual(gRPCStatusDetailsObj.errorInfo, undefined); }); @@ -112,7 +112,7 @@ describe('gRPC-google error decoding', () => { assert.strictEqual( JSON.stringify(decodedError), - '{"code":3,"message":"test","statusDetails":[]}' + '{"code":3,"message":"test","statusDetails":[]}', ); }); @@ -129,7 +129,7 @@ describe('gRPC-google error decoding', () => { assert.strictEqual( JSON.stringify(gRPCStatusDetailsObj.details), - JSON.stringify([]) + JSON.stringify([]), ); }); @@ -146,7 +146,7 @@ describe('gRPC-google error decoding', () => { 0, err .toString() - .indexOf('Error: Unknown type encoded in google.protobuf.any:') + .indexOf('Error: Unknown type encoded in google.protobuf.any:'), ); } }); @@ -197,7 +197,7 @@ describe('parse grpc status details with ErrorInfo from grpc metadata', () => { { code: 7, metadata: metadata, - } + }, ); const decodedError = GoogleError.parseGRPCStatusDetails(grpcError); assert(decodedError instanceof GoogleError); @@ -205,7 +205,7 @@ describe('parse grpc status details with ErrorInfo from grpc metadata', () => { assert.strictEqual(decodedError.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(decodedError.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); }); @@ -233,19 +233,19 @@ describe('parse grpc status details with ErrorInfo from grpc metadata', () => { { code: 7, metadata: metadata, - } + }, ); const decodedError = GoogleError.parseGRPCStatusDetails(grpcError); assert(decodedError instanceof GoogleError); assert.strictEqual( JSON.stringify(decodedError.statusDetails), - JSON.stringify([errorInfoObj]) + JSON.stringify([errorInfoObj]), ); assert.strictEqual(decodedError.domain, errorInfoObj.domain); assert.strictEqual(decodedError.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(decodedError.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); }); @@ -257,7 +257,7 @@ describe('parse grpc status details with ErrorInfo from grpc metadata', () => { { code: 7, metadata: metadata, - } + }, ); const decodedError = GoogleError.parseGRPCStatusDetails(grpcError); assert(decodedError instanceof GoogleError); @@ -269,7 +269,7 @@ describe('parse grpc status details with ErrorInfo from grpc metadata', () => { new GoogleError('mock error without metadata'), { code: 7, - } + }, ); const decodedError = GoogleError.parseGRPCStatusDetails(grpcError); assert(decodedError instanceof GoogleError); @@ -319,7 +319,7 @@ describe('map http status code to gRPC status code', () => { }, }; const errorAlreadyExists = GoogleError.parseHttpError( - errorJsonAlreadyExistss + errorJsonAlreadyExistss, ); assert.deepStrictEqual(errorAborted.code, Status.ABORTED); assert.deepStrictEqual(errorAlreadyExists.code, Status.ALREADY_EXISTS); @@ -359,14 +359,14 @@ describe('http error decoding', () => { assert.deepStrictEqual(error.code, rpcCodeFromHttpStatusCode(403)); assert.deepStrictEqual( error.statusDetails?.length, - json['error']['details'].length + json['error']['details'].length, ); assert.deepStrictEqual(error.message, json['error']['message']); assert.deepStrictEqual(error.reason, errorInfo.reason); assert.deepStrictEqual(error.domain, errorInfo.domain); assert.deepStrictEqual( JSON.stringify(error.errorInfoMetadata), - JSON.stringify(errorInfo.metadata) + JSON.stringify(errorInfo.metadata), ); }); @@ -375,14 +375,14 @@ describe('http error decoding', () => { assert.deepStrictEqual(error.code, rpcCodeFromHttpStatusCode(403)); assert.deepStrictEqual( error.statusDetails?.length, - json['error']['details'].length + json['error']['details'].length, ); assert.deepStrictEqual(error.message, json['error']['message']); assert.deepStrictEqual(error.reason, errorInfo.reason); assert.deepStrictEqual(error.domain, errorInfo.domain); assert.deepStrictEqual( JSON.stringify(error.errorInfoMetadata), - JSON.stringify(errorInfo.metadata) + JSON.stringify(errorInfo.metadata), ); }); }); diff --git a/gax/test/unit/grpc-fallback.ts b/gax/test/unit/grpc-fallback.ts index 0c3c94952..f12fc3801 100644 --- a/gax/test/unit/grpc-fallback.ts +++ b/gax/test/unit/grpc-fallback.ts @@ -17,15 +17,15 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-undef */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it, beforeEach, afterEach, before, after} from 'mocha'; -import * as nodeFetch from 'node-fetch'; import * as abortController from 'abort-controller'; import * as protobuf from 'protobufjs'; import * as sinon from 'sinon'; import echoProtoJson = require('../fixtures/echo.json'); import {GrpcClient} from '../../src/fallback'; import {GoogleError} from '../../src'; +import proxyquire from 'proxyquire'; // @ts-ignore const hasAbortController = typeof AbortController !== 'undefined'; @@ -138,18 +138,22 @@ describe('createStub', () => { it('validates universe domain if set', async () => { const opts = {...stubOptions, universeDomain: 'example.com'}; - assert.rejects( - gaxGrpc.createStub(echoService, opts), - /configured universe domain/ - ); + assert + .rejects( + gaxGrpc.createStub(echoService, opts), + /configured universe domain/, + ) + .catch(console.error); }); it('validates universe domain if unset', async () => { authClient.universeDomain = 'example.com'; - assert.rejects( - gaxGrpc.createStub(echoService, stubOptions), - /configured universe domain/ - ); + assert + .rejects( + gaxGrpc.createStub(echoService, stubOptions), + /configured universe domain/, + ) + .catch(console.error); // reset to default value authClient.universeDomain = 'googleapis.com'; }); @@ -209,6 +213,7 @@ describe('grpc-fallback', () => { if (hasAbortController) { // @ts-ignore + // eslint-disable-next-line no-global-assign AbortController = FakeAbortController; } else { // @ts-ignore @@ -227,6 +232,7 @@ describe('grpc-fallback', () => { after(() => { if (hasAbortController) { // @ts-ignore + // eslint-disable-next-line no-global-assign AbortController = savedAbortController; } else { // @ts-ignore @@ -268,40 +274,43 @@ describe('grpc-fallback', () => { 'google.showcase.v1beta1.Echo', gapicConfig, {}, - {} + {}, ); const metadataBuilder = settings.echo.otherArgs.metadataBuilder; const headers = metadataBuilder(); assert(headers['x-goog-api-client'][0].match('grpc-web/')); }); - - it('should make a request', done => { + it('should make a request', async () => { const requestObject = {content: 'test-content'}; const responseType = protos.lookupType('EchoResponse'); const response = responseType.create(requestObject); // request === response for EchoService - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(response))); - }, - }) - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { - echoStub.echo(requestObject, {}, {}, (err?: Error, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - requestObject.content, - (result as {content: string}).content - ); - done(); - }); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(response))); + }, + }); + }, }); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(echoService, stubOptions) + .then((echoStub: {echo: any}) => { + echoStub.echo(requestObject, {}, {}, (err?: Error, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + requestObject.content, + (result as {content: string}).content, + ); + }); + }); }); - it('should handle an API error', done => { + it('should handle an API error', async () => { const requestObject = {content: 'test-content'}; // example of an actual google.rpc.Status error message returned by Language API const expectedMessage = @@ -334,63 +343,51 @@ describe('grpc-fallback', () => { }, ], }; - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: false, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(jsonError))); - }, - }) - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(jsonError))); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert(err instanceof GoogleError); assert.strictEqual(err.message, expectedMessage); assert.strictEqual(err.code, expectedError.code); assert.strictEqual( JSON.stringify(err.statusDetails), - JSON.stringify(expectedError.details) + JSON.stringify(expectedError.details), ); - done(); }); }); }); - it('should handle a null response from the API ', done => { + + it('should handle a fetch error', async () => { const requestObject = {content: 'test-content'}; - const expectedMessage = 'Received null response from RPC Echo'; - - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: false, - arrayBuffer: () => { - return Promise.resolve(Buffer.from('')); - }, - }) - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { - echoStub.echo(requestObject, {}, {}, (err?: Error) => { - assert(err instanceof Error); - assert.strictEqual(err.message, expectedMessage); - done(); - }); + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.reject(new Error('fetch error')); + }, }); - }); - it('should handle a fetch error', done => { - const requestObject = {content: 'test-content'}; - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').rejects(new Error('fetch error')); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert.strictEqual(err?.message, 'fetch error'); - done(); }); }); }); - it('should promote ErrorInfo if exist in fallback-rest error', done => { + it('should promote ErrorInfo if exist in fallback-rest error', async () => { const requestObject = {content: 'test-content'}; // example of an actual google.rpc.Status error message returned by Translate API const errorInfo = { @@ -426,23 +423,26 @@ describe('grpc-fallback', () => { auth: authStub, fallback: 'rest', }; - // @ts-ignore incomplete options - gaxGrpc = new GrpcClient(opts); - //@ts-ignore - sinon.stub(nodeFetch, 'Promise').returns( - Promise.resolve({ - ok: false, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(serverError))); - }, - }) - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(serverError))); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(opts); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: Error) => { assert(err instanceof GoogleError); assert.strictEqual( JSON.stringify(err.statusDetails?.length), - JSON.stringify(serverError['error']['details'].length) + JSON.stringify(serverError['error']['details'].length), ); assert.strictEqual(err.code, 7); assert.strictEqual(err.message, serverError['error']['message']); @@ -450,33 +450,56 @@ describe('grpc-fallback', () => { assert.strictEqual(err.domain, errorInfo.domain); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfo.metadata) + JSON.stringify(errorInfo.metadata), ); - done(); }); }); }); it('should be able to cancel an API call using AbortController', async () => { - // @ts-ignore - sinon.stub(nodeFetch, 'Promise').returns(Promise.resolve({})); + const opts = { + auth: authStub, + fallback: 'rest', + }; + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify({}))); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(opts); + const echoStub = await gaxGrpcMock.createStub(echoService, stubOptions); - const echoStub = await gaxGrpc.createStub(echoService, stubOptions); const request = {content: 'content' + new Date().toString()}; const call = echoStub.echo(request, {}, {}, () => {}); call.cancel(); - // @ts-ignore - assert.strictEqual(createdAbortControllers[0].abortCalled, true); + assert.strictEqual((createdAbortControllers[0] as any).abortCalled, true); }); - it('should have close method', done => { - // @ts-ignore - sinon.stub(nodeFetch, 'Promise').returns(Promise.resolve({})); - gaxGrpc.createStub(echoService, stubOptions).then(stub => { + it('should have close method', async () => { + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve({}); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((stub: any) => { stub.close({}, {}, {}, () => {}); - done(); }); }); }); diff --git a/gax/test/unit/grpc.ts b/gax/test/unit/grpc.ts index 084daeb75..6d5de2f7f 100644 --- a/gax/test/unit/grpc.ts +++ b/gax/test/unit/grpc.ts @@ -18,10 +18,10 @@ /* eslint-disable no-prototype-builtins */ /* eslint-disable @typescript-eslint/no-var-requires */ -import * as assert from 'assert'; +import assert from 'assert'; import * as os from 'os'; import * as path from 'path'; -import * as proxyquire from 'proxyquire'; +import proxyquire from 'proxyquire'; import * as sinon from 'sinon'; import {mkdirSync, writeFileSync} from 'fs'; import * as fsp from 'fs/promises'; @@ -123,7 +123,7 @@ describe('grpc', () => { constructor( public address: {}, public creds: {}, - public options: {[index: string]: string | number | Function} + public options: {[index: string]: string | number | Function}, ) {} } @@ -184,22 +184,26 @@ describe('grpc', () => { port: 443, universeDomain: 'example.com', }; - assert.rejects( - // @ts-ignore - grpcClient.createStub(DummyStub, opts), - /configured universe domain/ - ); + assert + .rejects( + // @ts-ignore + grpcClient.createStub(DummyStub, opts), + /configured universe domain/, + ) + .catch(console.error); }); it('validates universe domain if unset', async () => { const opts = {servicePath: 'foo.example.com', port: 443}; stubAuth.getUniverseDomain.reset(); stubAuth.getUniverseDomain.resolves('example.com'); - assert.rejects( - // @ts-ignore - grpcClient.createStub(DummyStub, opts), - /configured universe domain/ - ); + assert + .rejects( + // @ts-ignore + grpcClient.createStub(DummyStub, opts), + /configured universe domain/, + ) + .catch(console.error); }); it('supports optional parameters', () => { @@ -236,15 +240,15 @@ describe('grpc', () => { const dummyStub = stub as unknown as DummyStub; assert.strictEqual( dummyStub.options['grpc.max_send_message_length'], - 10 * 1024 * 1024 + 10 * 1024 * 1024, ); assert.strictEqual( (dummyStub.options['callInvocationTransformer'] as Function)(), - 42 + 42, ); assert.strictEqual( dummyStub.options['grpc-node.max_session_memory'], - 10 + 10, ); ['servicePath', 'port', 'other_dummy_options'].forEach(k => { assert.strictEqual(stub.options.hasOwnProperty(k), false); @@ -290,7 +294,7 @@ describe('grpc', () => { const dummyStub = stub as unknown as DummyStub; assert.strictEqual( dummyStub.options['grpc.max_receive_message_length'], - 10 * 1024 * 1024 + 10 * 1024 * 1024, ); }); }); @@ -323,14 +327,14 @@ describe('grpc', () => { 'example', 'library', 'v1', - 'library.proto' + 'library.proto', ); const TEST_FILE_NO_DEPS = path.join( 'google', 'example', 'library', 'v1', - 'test.proto' + 'test.proto', ); const TEST_PATH = path.resolve(__dirname, '..', '..', 'test', 'fixtures'); const TEST_JSON = path.resolve( @@ -339,7 +343,7 @@ describe('grpc', () => { '..', 'test', 'fixtures', - 'library.json' + 'library.json', ); it('should load the test file', () => { @@ -349,7 +353,7 @@ describe('grpc', () => { const protos = grpcClient.loadProto(TEST_PATH, TEST_FILE) as any; assert.strictEqual( typeof protos.google.example.library.v1.LibraryService, - 'function' + 'function', ); }); @@ -360,7 +364,7 @@ describe('grpc', () => { const protos = grpcClient.loadProtoJSON(require(TEST_JSON)) as any; assert.strictEqual( typeof protos.google.example.library.v1.LibraryService, - 'function' + 'function', ); }); @@ -368,7 +372,7 @@ describe('grpc', () => { // no-any disabled because if the accessed fields are non-existent, this // test will fail anyway. const protos = grpcClient.loadProto( - path.join(TEST_PATH, TEST_FILE_NO_DEPS) + path.join(TEST_PATH, TEST_FILE_NO_DEPS), // eslint-disable-next-line @typescript-eslint/no-explicit-any ) as any; assert(protos.test.TestMessage); @@ -400,7 +404,7 @@ describe('grpc', () => { ]) as any; assert.strictEqual( typeof protos.google.example.library.v1.LibraryService, - 'function' + 'function', ); assert.strictEqual(typeof protos.google.iam.v1.IAMPolicy, 'function'); }); @@ -409,7 +413,7 @@ describe('grpc', () => { const nonExistentDir = path.join(__dirname, 'nonexistent', 'dir'); const nonExistentFile = 'nonexistent.proto'; assert.throws( - grpcClient.loadProto.bind(null, nonExistentDir, nonExistentFile) + grpcClient.loadProto.bind(null, nonExistentDir, nonExistentFile), ); }); @@ -436,12 +440,12 @@ describe('grpc', () => { const proto1 = grpcClient.loadProto( TEST_PATH, TEST_FILE, - /*ignoreCache:*/ true + /*ignoreCache:*/ true, ); const proto2 = grpcClient.loadProto( TEST_PATH, TEST_FILE, - /*ignoreCache:*/ true + /*ignoreCache:*/ true, ); assert.notStrictEqual(proto1, proto2); }); @@ -449,11 +453,11 @@ describe('grpc', () => { it('should ignore cache if asked for JSON protos', () => { const proto1 = grpcClient.loadProtoJSON( require(TEST_JSON), - /*ignoreCache:*/ true + /*ignoreCache:*/ true, ); const proto2 = grpcClient.loadProtoJSON( require(TEST_JSON), - /*ignoreCache:*/ true + /*ignoreCache:*/ true, ); assert.notStrictEqual(proto1, proto2); }); @@ -473,18 +477,18 @@ describe('grpc', () => { 'google', 'example', 'library', - 'v1' + 'v1', ); const TEST_FILE = path.join(FIXTURES_DIR, 'library.proto'); const NON_EXISTENT_FILE = path.join( __dirname, 'does', 'not', - 'exist.proto' + 'exist.proto', ); const MISSING_INCLUDE_FILE = path.join( FIXTURES_DIR, - 'missing_include.proto' + 'missing_include.proto', ); describe('use with protobufjs load', () => { @@ -495,7 +499,7 @@ describe('grpc', () => { }, () => { done(); - } + }, ); }); @@ -506,7 +510,7 @@ describe('grpc', () => { assert(root instanceof protobuf.Root); assert( root.lookup('google.example.library.v1.LibraryService') instanceof - protobuf.Service + protobuf.Service, ); assert(root.lookup('test.TestMessage') instanceof protobuf.Type); done(); @@ -549,7 +553,7 @@ describe('grpc', () => { assert(root instanceof protobuf.Root); assert( root.lookup('google.example.library.v1.LibraryService') instanceof - protobuf.Service + protobuf.Service, ); assert(root.lookup('test.TestMessage') instanceof protobuf.Type); }); @@ -559,8 +563,8 @@ describe('grpc', () => { protobuf.loadSync.bind( null, NON_EXISTENT_FILE, - new GoogleProtoFilesRoot() - ) + new GoogleProtoFilesRoot(), + ), ); }); @@ -569,8 +573,8 @@ describe('grpc', () => { protobuf.loadSync.bind( null, MISSING_INCLUDE_FILE, - new GoogleProtoFilesRoot() - ) + new GoogleProtoFilesRoot(), + ), ); }); }); @@ -601,7 +605,7 @@ describe('grpc', () => { }).GoogleProtoFilesRoot._findIncludePath; assert.strictEqual( findIncludePath(originPath, includePath), - correctPath + correctPath, ); }); }); @@ -630,7 +634,7 @@ describe('grpc', () => { const servicePath = client._mtlsServicePath( 'https://foo.googleapis.com', false, - true + true, ); assert.strictEqual(servicePath, expected); }); @@ -641,7 +645,7 @@ describe('grpc', () => { const servicePath = client._mtlsServicePath( 'https://foo.googleapis.com', false, - false + false, ); assert.strictEqual(servicePath, expected); }); @@ -676,11 +680,17 @@ dvorak mkdirSync(tmpdir, {recursive: true}); const metadataFile = path.join(tmpdir, 'context_aware_metadata.json'); writeFileSync(metadataFile, JSON.stringify(metadataFileContents), 'utf8'); - sandbox.stub(os, 'homedir').returns(tmpFolder); // Create a client and test the certificate detection flow: process.env.GOOGLE_API_USE_CLIENT_CERTIFICATE = 'true'; - const client = gaxGrpc(); - const [cert, key] = await client._detectClientCertificate(); + const {GrpcClient} = await proxyquire('../../src/grpc.js', { + os: { + homedir: () => { + return tmpFolder; + }, + }, + }); + const clientMock = new GrpcClient(); + const [cert, key] = await clientMock._detectClientCertificate(); assert.ok(cert.includes('qwerty')); assert.ok(key.includes('dvorak')); await fsp.rm(tmpFolder, {recursive: true, force: true}); // Cleanup. @@ -693,15 +703,24 @@ dvorak mkdirSync(tmpdir, {recursive: true}); const metadataFile = path.join(tmpdir, 'context_aware_metadata.json'); writeFileSync(metadataFile, JSON.stringify(metadataFileContents), 'utf8'); - sandbox.stub(os, 'homedir').returns(tmpFolder); + + process.env.GOOGLE_API_USE_CLIENT_CERTIFICATE = 'true'; + const {GrpcClient} = await proxyquire('../../src/grpc.js', { + os: { + homedir: () => { + return tmpFolder; + }, + }, + }); // Create a client and test the certificate detection flow: process.env.GOOGLE_API_USE_CLIENT_CERTIFICATE = 'true'; - const client = gaxGrpc(); - assert.rejects( - // @ts-ignore - client.createStub(DummyStub, {universeDomain: 'example.com'}), - /configured universe domain/ - ); + const clientMock = new GrpcClient(); + assert + .rejects( + clientMock.createStub(DummyStub, {universeDomain: 'example.com'}), + /configured universe domain/, + ) + .catch(console.error); await fsp.rm(tmpFolder, {recursive: true, force: true}); // Cleanup. }); }); diff --git a/gax/test/unit/iamService.ts b/gax/test/unit/iamService.ts index bfeec0abc..56c88ddb4 100644 --- a/gax/test/unit/iamService.ts +++ b/gax/test/unit/iamService.ts @@ -15,8 +15,9 @@ // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + import * as protos from '../../protos/iam_service'; -import * as assert from 'assert'; +import assert from 'assert'; import * as sinon from 'sinon'; import {SinonStub} from 'sinon'; import {describe, it} from 'mocha'; @@ -29,7 +30,7 @@ function generateSampleMessage(instance: T) { instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( - filledObject + filledObject, ) as T; } @@ -41,7 +42,7 @@ function stubSimpleCall(response?: ResponseType, error?: Error) { function stubSimpleCallWithCallback( response?: ResponseType, - error?: Error + error?: Error, ) { return error ? sinon.stub().callsArgWith(2, error) @@ -56,9 +57,9 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() + new protos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -70,7 +71,7 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() + new protos.google.iam.v1.Policy(), ); client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); const response = await client.getIamPolicy(request, expectedOptions); @@ -78,7 +79,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes getIamPolicy without error using callback', async () => { @@ -87,9 +88,9 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() + new protos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -101,29 +102,34 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() + new protos.google.iam.v1.Policy(), ); client.innerApiCalls.getIamPolicy = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.getIamPolicy( - request, - expectedOptions, - (err?: Error | null, result?: protos.google.iam.v1.Policy | null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); + client + .getIamPolicy( + request, + expectedOptions, + ( + err?: Error | null, + result?: protos.google.iam.v1.Policy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions /* callback function above */) + .calledWith(request, expectedOptions /* callback function above */), ); }); it('invokes getIamPolicy with error', async () => { @@ -132,9 +138,9 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.iam.v1.GetIamPolicyRequest() + new protos.google.iam.v1.GetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -148,7 +154,7 @@ describe('IAM service', () => { const expectedError = new Error('expected'); client.innerApiCalls.getIamPolicy = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.getIamPolicy(request, expectedOptions); @@ -156,7 +162,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.getIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -167,9 +173,9 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() + new protos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -181,7 +187,7 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() + new protos.google.iam.v1.Policy(), ); client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse); const response = await client.setIamPolicy(request, expectedOptions); @@ -189,7 +195,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes setIamPolicy without error using callback', async () => { @@ -198,9 +204,9 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() + new protos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -212,29 +218,34 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.Policy() + new protos.google.iam.v1.Policy(), ); client.innerApiCalls.setIamPolicy = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.setIamPolicy( - request, - expectedOptions, - (err?: Error | null, result?: protos.google.iam.v1.Policy | null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); + client + .setIamPolicy( + request, + expectedOptions, + ( + err?: Error | null, + result?: protos.google.iam.v1.Policy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions /* callback function above */) + .calledWith(request, expectedOptions /* callback function above */), ); }); it('invokes setIamPolicy with error', async () => { @@ -243,9 +254,9 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.iam.v1.SetIamPolicyRequest() + new protos.google.iam.v1.SetIamPolicyRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -259,7 +270,7 @@ describe('IAM service', () => { const expectedError = new Error('expected'); client.innerApiCalls.setIamPolicy = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.setIamPolicy(request, expectedOptions); @@ -267,7 +278,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.setIamPolicy as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -278,9 +289,9 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() + new protos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -292,19 +303,19 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsResponse() + new protos.google.iam.v1.TestIamPermissionsResponse(), ); client.innerApiCalls.testIamPermissions = stubSimpleCall(expectedResponse); const response = await client.testIamPermissions( request, - expectedOptions + expectedOptions, ); assert.deepStrictEqual(response, [expectedResponse]); assert( (client.innerApiCalls.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); it('invokes testIamPermissions without error using callback', async () => { @@ -313,9 +324,9 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() + new protos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -327,32 +338,34 @@ describe('IAM service', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsResponse() + new protos.google.iam.v1.TestIamPermissionsResponse(), ); client.innerApiCalls.testIamPermissions = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.testIamPermissions( - request, - expectedOptions, - ( - err?: Error | null, - result?: protos.google.iam.v1.TestIamPermissionsResponse | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); + client + .testIamPermissions( + request, + expectedOptions, + ( + err?: Error | null, + result?: protos.google.iam.v1.TestIamPermissionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions /* callback function above */) + .calledWith(request, expectedOptions /* callback function above */), ); }); it('invokes testIamPermissions with error', async () => { @@ -361,9 +374,9 @@ describe('IAM service', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.iam.v1.TestIamPermissionsRequest() + new protos.google.iam.v1.TestIamPermissionsRequest(), ); request.resource = ''; const expectedHeaderRequestParams = 'resource='; @@ -377,7 +390,7 @@ describe('IAM service', () => { const expectedError = new Error('expected'); client.innerApiCalls.testIamPermissions = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.testIamPermissions(request, expectedOptions); @@ -385,7 +398,7 @@ describe('IAM service', () => { assert( (client.innerApiCalls.testIamPermissions as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); diff --git a/gax/test/unit/locationService.ts b/gax/test/unit/locationService.ts index 8d957cb41..cb2119cb5 100644 --- a/gax/test/unit/locationService.ts +++ b/gax/test/unit/locationService.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as protos from '../../protos/locations'; -import * as assert from 'assert'; +import assert from 'assert'; import * as sinon from 'sinon'; import {SinonStub} from 'sinon'; import {describe, it} from 'mocha'; @@ -27,7 +27,7 @@ function generateSampleMessage(instance: T) { instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( - filledObject + filledObject, ) as T; } @@ -39,7 +39,7 @@ function stubSimpleCall(response?: ResponseType, error?: Error) { function stubSimpleCallWithCallback( response?: ResponseType, - error?: Error + error?: Error, ) { return error ? sinon.stub().callsArgWith(2, error) @@ -48,7 +48,7 @@ function stubSimpleCallWithCallback( function stubAsyncIterationCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { let counter = 0; const asyncIterable = { @@ -77,9 +77,9 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.cloud.location.GetLocationRequest() + new protos.google.cloud.location.GetLocationRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -91,7 +91,7 @@ describe('LocationsClient', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.cloud.location.Location() + new protos.google.cloud.location.Location(), ); client.innerApiCalls.getLocation = stubSimpleCall(expectedResponse); const response = await client.getLocation(request, expectedOptions); @@ -99,7 +99,7 @@ describe('LocationsClient', () => { assert( (client.innerApiCalls.getLocation as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); @@ -109,9 +109,9 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.cloud.location.GetLocationRequest() + new protos.google.cloud.location.GetLocationRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -123,31 +123,33 @@ describe('LocationsClient', () => { }, }; const expectedResponse = generateSampleMessage( - new protos.google.cloud.location.Location() + new protos.google.cloud.location.Location(), ); client.innerApiCalls.getLocation = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.getLocation( - request, - ( - err?: Error | null, - result?: protos.google.cloud.location.ILocation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); + client + .getLocation( + request, + ( + err?: Error | null, + result?: protos.google.cloud.location.ILocation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.getLocation as SinonStub) .getCall(0) - .calledWith(request, expectedOptions /*, callback defined above */) + .calledWith(request, expectedOptions /*, callback defined above */), ); }); @@ -156,9 +158,9 @@ describe('LocationsClient', () => { const client = new LocationsClient(grpcClient, { projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.cloud.location.GetLocationRequest() + new protos.google.cloud.location.GetLocationRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -172,16 +174,16 @@ describe('LocationsClient', () => { const expectedError = new Error('expected'); client.innerApiCalls.getLocation = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects( client.getLocation(request, expectedOptions), - expectedError + expectedError, ); assert( (client.innerApiCalls.getLocation as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); }); @@ -193,9 +195,9 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() + new protos.google.cloud.location.ListLocationsRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -217,7 +219,7 @@ describe('LocationsClient', () => { assert( (client.innerApiCalls.listLocations as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); @@ -227,9 +229,9 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() + new protos.google.cloud.location.ListLocationsRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -252,14 +254,14 @@ describe('LocationsClient', () => { request, ( err?: Error | null, - result?: protos.google.cloud.location.ILocation[] | null + result?: protos.google.cloud.location.ILocation[] | null, ) => { if (err) { reject(err); } else { resolve(result); } - } + }, ); }); const response = await promise; @@ -267,7 +269,7 @@ describe('LocationsClient', () => { assert( (client.innerApiCalls.listLocations as SinonStub) .getCall(0) - .calledWith(request, expectedOptions /*, callback defined above */) + .calledWith(request, expectedOptions /*, callback defined above */), ); }); @@ -277,9 +279,9 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() + new protos.google.cloud.location.ListLocationsRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -293,16 +295,16 @@ describe('LocationsClient', () => { const expectedError = new Error('expected'); client.innerApiCalls.listLocations = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects( client.listLocations(request, expectedOptions), - expectedError + expectedError, ); assert( (client.innerApiCalls.listLocations as SinonStub) .getCall(0) - .calledWith(request, expectedOptions, undefined) + .calledWith(request, expectedOptions, undefined), ); }); @@ -312,9 +314,9 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() + new protos.google.cloud.location.ListLocationsRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -335,13 +337,13 @@ describe('LocationsClient', () => { ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert.strictEqual( ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], - expectedHeaderRequestParams + expectedHeaderRequestParams, ); }); @@ -351,9 +353,9 @@ describe('LocationsClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); - client.initialize(); + client.initialize().catch(console.error); const request = generateSampleMessage( - new protos.google.cloud.location.ListLocationsRequest() + new protos.google.cloud.location.ListLocationsRequest(), ); request.name = ''; const expectedHeaderRequestParams = 'name='; @@ -371,13 +373,13 @@ describe('LocationsClient', () => { ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[1], - request + request, ); assert.strictEqual( ( client.descriptors.page.listLocations.asyncIterate as SinonStub ).getCall(0).args[2].otherArgs.headers['x-goog-request-params'], - expectedHeaderRequestParams + expectedHeaderRequestParams, ); }); }); diff --git a/gax/test/unit/longrunning.ts b/gax/test/unit/longrunning.ts index 0ec804a3c..ce48e7854 100644 --- a/gax/test/unit/longrunning.ts +++ b/gax/test/unit/longrunning.ts @@ -16,7 +16,7 @@ /* eslint-disable no-prototype-builtins */ -import * as assert from 'assert'; +import assert from 'assert'; import {status} from '@grpc/grpc-js'; import * as sinon from 'sinon'; import {describe, it} from 'mocha'; @@ -85,7 +85,7 @@ function createApiCall(func: Function, client?: OperationsClient) { const descriptor = new LongrunningDescriptor( client!, mockDecoder as unknown as AnyDecoder, - mockDecoder as unknown as AnyDecoder + mockDecoder as unknown as AnyDecoder, ); return utils.createApiCall(func, {descriptor}) as GaxCallPromise; } @@ -140,7 +140,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -157,19 +157,19 @@ describe('longrunning', () => { assert(operation.hasOwnProperty('backoffSettings')); assert.strictEqual( operation.backoffSettings.initialRetryDelayMillis, - defaultInitialRetryDelayMillis + defaultInitialRetryDelayMillis, ); assert.strictEqual( operation.backoffSettings.retryDelayMultiplier, - defaultRetryDelayMultiplier + defaultRetryDelayMultiplier, ); assert.strictEqual( operation.backoffSettings.maxRetryDelayMillis, - defaultMaxRetryDelayMillis + defaultMaxRetryDelayMillis, ); assert.strictEqual( operation.backoffSettings.totalTimeoutMillis, - defaultTotalTimeoutMillis + defaultTotalTimeoutMillis, ); assert(operation.hasOwnProperty('longrunningDescriptor')); assert.strictEqual(operation.name, OPERATION_NAME); @@ -190,7 +190,7 @@ describe('longrunning', () => { const desc = new LongrunningDescriptor( client as OperationsClient, mockDecoder as unknown as AnyDecoder, - mockDecoder as unknown as AnyDecoder + mockDecoder as unknown as AnyDecoder, ); const initialRetryDelayMillis = 1; const retryDelayMultiplier = 2; @@ -204,30 +204,30 @@ describe('longrunning', () => { unusedRpcValue, unusedRpcValue, unusedRpcValue, - totalTimeoutMillis + totalTimeoutMillis, ); const operation = longrunning.operation( SUCCESSFUL_OP as {} as operationProtos.google.longrunning.Operation, desc, - backoff + backoff, ); assert(operation instanceof Object); assert(operation.hasOwnProperty('backoffSettings')); assert.strictEqual( operation.backoffSettings.initialRetryDelayMillis, - initialRetryDelayMillis + initialRetryDelayMillis, ); assert.strictEqual( operation.backoffSettings.retryDelayMultiplier, - retryDelayMultiplier + retryDelayMultiplier, ); assert.strictEqual( operation.backoffSettings.maxRetryDelayMillis, - maxRetryDelayMillis + maxRetryDelayMillis, ); assert.strictEqual( operation.backoffSettings.totalTimeoutMillis, - totalTimeoutMillis + totalTimeoutMillis, ); assert(operation.hasOwnProperty('longrunningDescriptor')); assert.strictEqual(operation.name, OPERATION_NAME); @@ -247,7 +247,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, SUCCESSFUL_OP); }; @@ -275,7 +275,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -305,7 +305,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -325,7 +325,7 @@ describe('longrunning', () => { assert.strictEqual(client.getOperation.callCount, 1); done(); }), - undefined + undefined, ); }) .catch(error => { @@ -338,7 +338,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -370,7 +370,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, ERROR_OP); }; @@ -397,7 +397,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -428,7 +428,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, SUCCESSFUL_OP); }; @@ -449,7 +449,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -481,7 +481,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -509,7 +509,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -522,11 +522,14 @@ describe('longrunning', () => { .then(responses => { const operation = responses[0] as longrunning.Operation; const p = operation.promise(); - operation.cancel().then(() => { - assert.strictEqual(client.cancelOperation.called, true); - assert.strictEqual(client.cancelGetOperationSpy.called, true); - done(); - }); + operation + .cancel() + .then(() => { + assert.strictEqual(client.cancelOperation.called, true); + assert.strictEqual(client.cancelGetOperationSpy.called, true); + done(); + }) + .catch(console.error); return p; }) .then(() => { @@ -544,7 +547,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -577,7 +580,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -610,7 +613,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -646,7 +649,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -699,7 +702,7 @@ describe('longrunning', () => { argument: {}, metadata: {}, options: {}, - callback: Function + callback: Function, ) => { callback(null, PENDING_OP); }; @@ -713,7 +716,7 @@ describe('longrunning', () => { {}, { longrunning: gax.createBackoffSettings(1, 1, 1, 0, 0, 0, 1), - } + }, ) .then(responses => { const operation = responses[0] as longrunning.Operation; @@ -725,7 +728,7 @@ describe('longrunning', () => { assert.strictEqual(err!.code, status.DEADLINE_EXCEEDED); assert.strictEqual( err!.message, - 'Total timeout exceeded before ' + 'any response was received' + 'Total timeout exceeded before ' + 'any response was received', ); done(); }); diff --git a/gax/test/unit/operationClient.ts b/gax/test/unit/operationClient.ts index 0d910b8cb..f3d7a6f7e 100644 --- a/gax/test/unit/operationClient.ts +++ b/gax/test/unit/operationClient.ts @@ -15,8 +15,9 @@ // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + import * as protos from '../../protos/operations'; -import * as assert from 'assert'; +import assert from 'assert'; import * as sinon from 'sinon'; import {SinonStub} from 'sinon'; import {describe, it} from 'mocha'; @@ -31,7 +32,7 @@ function generateSampleMessage(instance: T) { instance.constructor as typeof protobuf.Message ).toObject(instance as protobuf.Message, {defaults: true}); return (instance.constructor as typeof protobuf.Message).fromObject( - filledObject + filledObject, ) as T; } @@ -43,7 +44,7 @@ function stubSimpleCall(response?: ResponseType, error?: Error) { function stubSimpleCallWithCallback( response?: ResponseType, - error?: Error + error?: Error, ) { return error ? sinon.stub().callsArgWith(2, error) @@ -51,7 +52,7 @@ function stubSimpleCallWithCallback( } function stubPageStreamingCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { const pagingStub = sinon.stub(); if (responses) { @@ -89,7 +90,7 @@ function stubPageStreamingCall( function stubAsyncIterationCall( responses?: ResponseType[], - error?: Error + error?: Error, ) { let counter = 0; const asyncIterable = { @@ -119,14 +120,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() + new protos.google.longrunning.Operation(), ); client.innerApiCalls.getOperation = stubSimpleCall(expectedResponse); const response = await client.getOperation(request); @@ -134,7 +135,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -145,39 +146,41 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() + new protos.google.longrunning.Operation(), ); client.innerApiCalls.getOperation = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.getOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.longrunning.Operation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); + client + .getOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.longrunning.Operation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request /* callback function above */) + .calledWith(request /* callback function above */), ); }); @@ -188,15 +191,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedError = new Error('expected'); client.innerApiCalls.getOperation = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.getOperation(request); @@ -204,7 +207,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); }); @@ -216,11 +219,11 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedResponse: ResultTuple = [ new protos.google.longrunning.Operation(), @@ -233,7 +236,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -244,11 +247,11 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedResponse: ResultTuple = [ new protos.google.longrunning.Operation(), @@ -258,27 +261,29 @@ describe('operation client', () => { client.innerApiCalls.getOperation = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.getOperationInternal( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.longrunning.Operation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); + client + .getOperationInternal( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.longrunning.Operation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request /* callback function above */) + .calledWith(request /* callback function above */), ); }); @@ -289,15 +294,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.GetOperationRequest() + new protos.google.longrunning.GetOperationRequest(), ); const expectedError = new Error('expected'); client.innerApiCalls.getOperation = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.getOperationInternal(request); @@ -305,7 +310,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.getOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); }); @@ -317,14 +322,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.longrunning.ListOperationsResponse() + new protos.google.longrunning.ListOperationsResponse(), ); client.innerApiCalls.listOperations = stubSimpleCall(expectedResponse); const response = await client.listOperations(request); @@ -332,7 +337,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.listOperations as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -343,39 +348,41 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.longrunning.ListOperationsResponse() + new protos.google.longrunning.ListOperationsResponse(), ); client.innerApiCalls.listOperations = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.listOperations( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.longrunning.ListOperationsResponse | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); + client + .listOperations( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.longrunning.ListOperationsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.listOperations as SinonStub) .getCall(0) - .calledWith(request /* callback function above */) + .calledWith(request /* callback function above */), ); }); @@ -386,15 +393,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedError = new Error('expected'); client.innerApiCalls.listOperations = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.listOperations(request); @@ -402,7 +409,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.listOperations as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -413,11 +420,11 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedResponse = [ generateSampleMessage(new protos.google.longrunning.Operation()), @@ -444,7 +451,7 @@ describe('operation client', () => { assert( (client.descriptor.listOperations.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listOperations, request) + .calledWith(client.innerApiCalls.listOperations, request), ); }); @@ -455,16 +462,16 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedError = new Error('expected'); client.descriptor.listOperations.createStream = stubPageStreamingCall( undefined, - expectedError + expectedError, ); const stream = client.listOperationsStream(request); const promise = new Promise((resolve, reject) => { @@ -485,7 +492,7 @@ describe('operation client', () => { assert( (client.descriptor.listOperations.createStream as SinonStub) .getCall(0) - .calledWith(client.innerApiCalls.listOperations, request) + .calledWith(client.innerApiCalls.listOperations, request), ); }); @@ -496,21 +503,21 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedResponse = [ generateSampleMessage( - new protos.google.longrunning.ListOperationsResponse() + new protos.google.longrunning.ListOperationsResponse(), ), generateSampleMessage( - new protos.google.longrunning.ListOperationsResponse() + new protos.google.longrunning.ListOperationsResponse(), ), generateSampleMessage( - new protos.google.longrunning.ListOperationsResponse() + new protos.google.longrunning.ListOperationsResponse(), ), ]; client.descriptor.listOperations.asyncIterate = @@ -524,7 +531,7 @@ describe('operation client', () => { assert.deepStrictEqual( (client.descriptor.listOperations.asyncIterate as SinonStub).getCall(0) .args[1], - request + request, ); }); @@ -535,15 +542,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.ListOperationsRequest() + new protos.google.longrunning.ListOperationsRequest(), ); const expectedError = new Error('expected'); client.descriptor.listOperations.asyncIterate = stubAsyncIterationCall( undefined, - expectedError + expectedError, ); const iterable = client.listOperationsAsync(request); await assert.rejects(async () => { @@ -555,7 +562,7 @@ describe('operation client', () => { }); assert.deepStrictEqual( (client.descriptor.listOperations.asyncIterate as SinonStub).args[0][1], - request + request, ); }); }); @@ -567,14 +574,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.CancelOperationRequest() + new protos.google.longrunning.CancelOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.cancelOperation = stubSimpleCall(expectedResponse); const response = await client.cancelOperation(request); @@ -582,7 +589,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.cancelOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -593,39 +600,41 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.CancelOperationRequest() + new protos.google.longrunning.CancelOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.cancelOperation = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.cancelOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); + client + .cancelOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.cancelOperation as SinonStub) .getCall(0) - .calledWith(request /* callback function above */) + .calledWith(request /* callback function above */), ); }); @@ -636,15 +645,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.CancelOperationRequest() + new protos.google.longrunning.CancelOperationRequest(), ); const expectedError = new Error('expected'); client.innerApiCalls.cancelOperation = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.cancelOperation(request); @@ -652,7 +661,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.cancelOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); }); @@ -664,14 +673,14 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.DeleteOperationRequest() + new protos.google.longrunning.DeleteOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteOperation = stubSimpleCall(expectedResponse); const response = await client.deleteOperation(request); @@ -679,7 +688,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.deleteOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); @@ -690,39 +699,41 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.DeleteOperationRequest() + new protos.google.longrunning.DeleteOperationRequest(), ); const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() + new protos.google.protobuf.Empty(), ); client.innerApiCalls.deleteOperation = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.deleteOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); + client + .deleteOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(console.error); }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); assert( (client.innerApiCalls.deleteOperation as SinonStub) .getCall(0) - .calledWith(request /* callback function above */) + .calledWith(request /* callback function above */), ); }); @@ -733,15 +744,15 @@ describe('operation client', () => { projectId: 'bogus', }; const client = new OperationsClientBuilder(grpcClient).operationsClient( - clientOptions + clientOptions, ); const request = generateSampleMessage( - new protos.google.longrunning.DeleteOperationRequest() + new protos.google.longrunning.DeleteOperationRequest(), ); const expectedError = new Error('expected'); client.innerApiCalls.deleteOperation = stubSimpleCall( undefined, - expectedError + expectedError, ); await assert.rejects(async () => { await client.deleteOperation(request); @@ -749,7 +760,7 @@ describe('operation client', () => { assert( (client.innerApiCalls.deleteOperation as SinonStub) .getCall(0) - .calledWith(request) + .calledWith(request), ); }); }); diff --git a/gax/test/unit/pagedIteration.ts b/gax/test/unit/pagedIteration.ts index 8399711d2..b0556d82c 100644 --- a/gax/test/unit/pagedIteration.ts +++ b/gax/test/unit/pagedIteration.ts @@ -17,11 +17,11 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable no-prototype-builtins */ -import * as assert from 'assert'; +import assert from 'assert'; import * as pumpify from 'pumpify'; import * as sinon from 'sinon'; import {PassThrough} from 'stream'; -import * as streamEvents from 'stream-events'; +import streamEvents from 'stream-events'; import {PageDescriptor} from '../../src/paginationCalls/pageDescriptor'; import {APICallback, GaxCall, RequestType} from '../../src/apitypes'; import {describe, it, beforeEach} from 'mocha'; @@ -45,7 +45,7 @@ describe('paged iteration', () => { request: {pageToken?: number}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) { const pageToken = request.pageToken || 0; if (pageToken >= pageSize * pagesToStream) { @@ -76,8 +76,8 @@ describe('paged iteration', () => { warnStub.calledWith( 'autoPaginate true', 'Providing a pageSize without setting autoPaginate to false will still return all results. See https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure manual paging', - 'AutopaginateTrueWarning' - ) + 'AutopaginateTrueWarning', + ), ); warnStub.restore(); done(); @@ -99,16 +99,15 @@ describe('paged iteration', () => { .catch(done); }); - it('calls callback with an Array', done => { + it('calls callback with an Array', async () => { const apiCall = util.createApiCall(func, createOptions); const expected: Array<{}> = []; for (let i = 0; i < pageSize * pagesToStream; ++i) { expected.push(i); } - apiCall({}, undefined, (err, results) => { + await apiCall({}, undefined, (err, results) => { assert.strictEqual(err, null); assert.deepStrictEqual(results, expected); - done(); }); }); @@ -147,17 +146,16 @@ describe('paged iteration', () => { .catch(done); }); - it('sets additional arguments to the callback', done => { + it('sets additional arguments to the callback', async () => { let counter = 0; const apiCall = util.createApiCall(func, createOptions); - function callback( + async function callback( err: {}, resources: {}, next: {}, - rawResponse: {nums: {}} + rawResponse: {nums: {}}, ) { if (err) { - done(err); return; } counter++; @@ -167,26 +165,29 @@ describe('paged iteration', () => { assert(rawResponse.hasOwnProperty('nums')); assert.strictEqual(rawResponse.nums, resources); if (next) { - apiCall( + await apiCall( next, {autoPaginate: false}, - callback as unknown as APICallback + callback as unknown as APICallback, ); } else { assert.strictEqual(counter, pagesToStream + 1); - done(); } } - apiCall({}, {autoPaginate: false}, callback as unknown as APICallback); + await apiCall( + {}, + {autoPaginate: false}, + callback as unknown as APICallback, + ); }); - it('retries on failure', done => { + it('retries on failure', async () => { let callCount = 0; function failingFunc( request: {}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) { callCount++; if (callCount % 2 === 0) { @@ -196,14 +197,11 @@ describe('paged iteration', () => { } } const apiCall = util.createApiCall(failingFunc, createOptions); - apiCall({}, undefined) - .then(resources => { - assert(Array.isArray(resources)); - // @ts-ignore response type - assert.strictEqual(resources[0].length, pageSize * pagesToStream); - done(); - }) - .catch(done); + await apiCall({}, undefined).then(resources => { + assert(Array.isArray(resources)); + // @ts-ignore response type + assert.strictEqual(resources[0].length, pageSize * pagesToStream); + }); }); it('caps the results by maxResults', () => { @@ -244,10 +242,10 @@ describe('paged iteration', () => { } const settings = new gax.CallSettings( - (createOptions && createOptions.settings) || {} + (createOptions && createOptions.settings) || {}, ); const resources = await iterableChecker( - descriptor.asyncIterate(apiCall, {}, settings) + descriptor.asyncIterate(apiCall, {}, settings), ); assert.strictEqual(resources.length, 10); }); @@ -271,11 +269,11 @@ describe('paged iteration', () => { } const settings = new gax.CallSettings( - (createOptions && createOptions.settings) || {} + (createOptions && createOptions.settings) || {}, ); settings.autoPaginate = true; const resources = await iterableChecker( - descriptor.asyncIterate(apiCall, {}, settings) + descriptor.asyncIterate(apiCall, {}, settings), ); assert.strictEqual(resources.length, 10); assert.strictEqual(warnStub.callCount, 1); @@ -283,8 +281,8 @@ describe('paged iteration', () => { warnStub.calledWith( 'autoPaginate true', 'Autopaginate will always be set to false in Async paging methods. See more info at https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure paging calls', - 'AutopaginateTrueWarning' - ) + 'AutopaginateTrueWarning', + ), ); warnStub.restore(); }); @@ -293,7 +291,7 @@ describe('paged iteration', () => { request: {pageToken?: number}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) { const responsePages = [ [1, 2, 3], @@ -318,7 +316,7 @@ describe('paged iteration', () => { } const apiCall = util.createApiCall(func, createOptions); const settings = new gax.CallSettings( - (createOptions && createOptions.settings) || {} + (createOptions && createOptions.settings) || {}, ); const iterable = descriptor.asyncIterate(apiCall, {}, settings); const results = []; @@ -342,7 +340,7 @@ describe('paged iteration', () => { stream: Stream, onEnd: Function, done: (...args: string[]) => void, - start: number + start: number, ) { let counter = start; stream @@ -365,7 +363,7 @@ describe('paged iteration', () => { assert.strictEqual(spy.callCount, pagesToStream + 1); }, done, - 0 + 0, ); }); @@ -378,7 +376,7 @@ describe('paged iteration', () => { stream, () => assert.strictEqual(onResponse.callCount, pagesToStream + 1), done, - 0 + 0, ); }); @@ -396,7 +394,7 @@ describe('paged iteration', () => { assert.strictEqual(spy.callCount, 2); }, done, - 0 + 0, ); }); it('ignores autoPaginate options and warns, but respects others', done => { @@ -415,13 +413,13 @@ describe('paged iteration', () => { warnStub.calledWith( 'autoPaginate true', 'Autopaginate will always be set to false in stream paging methods. See more info at https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination for more information on how to configure paging calls', - 'AutopaginateTrueWarning' - ) + 'AutopaginateTrueWarning', + ), ); warnStub.restore(); }, done, - 0 + 0, ); }); it('ignores autoPaginate options but respects others', done => { @@ -435,7 +433,7 @@ describe('paged iteration', () => { assert.strictEqual(spy.callCount, 1); }, done, - 0 + 0, ); }); @@ -454,7 +452,7 @@ describe('paged iteration', () => { assert.strictEqual(onResponse.callCount, spy.callCount); }, done, - 0 + 0, ); }); @@ -469,7 +467,7 @@ describe('paged iteration', () => { assert.strictEqual(spy.callCount, pagesToStream + 1); }, done, - 0 + 0, ); }, 50); }); @@ -520,7 +518,7 @@ describe('paged iteration', () => { request: {pageToken?: number}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) { const pageToken = request.pageToken || 0; if (pageToken >= pageSize * pagesToStream) { @@ -552,7 +550,7 @@ describe('paged iteration', () => { assert.strictEqual(onResponseSpy.callCount, spy.callCount); }, done, - 0 + 0, ); }); }); @@ -596,7 +594,7 @@ describe('REGAPIC Pagination', () => { request: {pageToken?: number}, metadata: {}, options: {}, - callback: APICallback + callback: APICallback, ) { const pageToken = request.pageToken || 0; if (pageToken >= pageSize * pagesToStream) { @@ -628,10 +626,10 @@ describe('REGAPIC Pagination', () => { it('return an tuple iterable, count to 10', async () => { const settings = new gax.CallSettings( - (createOptions && createOptions.settings) || {} + (createOptions && createOptions.settings) || {}, ); const resources = await iterableChecker( - descriptor.asyncIterate(apiCall, {}, settings) + descriptor.asyncIterate(apiCall, {}, settings), ); assert.strictEqual(resources.length, 10); for await (const [key, value] of resources as [string, ResponseType]) { diff --git a/gax/test/unit/pathTemplate.ts b/gax/test/unit/pathTemplate.ts index 8669dada6..d06092ec6 100644 --- a/gax/test/unit/pathTemplate.ts +++ b/gax/test/unit/pathTemplate.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import {PathTemplate} from '../../src/pathTemplate'; @@ -102,7 +102,7 @@ describe('PathTemplate', () => { const want = {$0: 'hello%2F%2Bworld'}; assert.deepStrictEqual( template.match('buckets/hello%2F%2Bworld/objects'), - want + want, ); }); @@ -111,7 +111,7 @@ describe('PathTemplate', () => { const want = {$0: 'foo', $1: 'bar/baz'}; assert.deepStrictEqual( template.match('buckets/foo/objects/bar/baz'), - want + want, ); }); @@ -123,7 +123,7 @@ describe('PathTemplate', () => { it('should match template with non-slash resource patterns', () => { const template = new PathTemplate( - 'user/{user_id}/blurbs/legacy/{blurb_a}-{blurb_b}~{legacy_user}' + 'user/{user_id}/blurbs/legacy/{blurb_a}-{blurb_b}~{legacy_user}', ); const want = { user_id: 'foo', @@ -133,13 +133,13 @@ describe('PathTemplate', () => { }; assert.deepStrictEqual( template.match('user/foo/blurbs/legacy/bara-barb~user'), - want + want, ); }); it('should not match template with malformed non-slash resource patterns', () => { const template = new PathTemplate( - 'user/{user_id}/blurbs/legacy/{blurb_id}.{legacy_user}' + 'user/{user_id}/blurbs/legacy/{blurb_id}.{legacy_user}', ); assert.throws(() => { template.match('user/foo/blurbs/legacy/bar~user2'); @@ -161,7 +161,7 @@ describe('PathTemplate', () => { }); it('should render atomic resource', () => { const template = new PathTemplate( - 'projects/{project}/metricDescriptors/{metric_descriptor=**}' + 'projects/{project}/metricDescriptors/{metric_descriptor=**}', ); const params = { project: 'project-name', @@ -203,7 +203,7 @@ describe('PathTemplate', () => { it('should accept both strings and numbers as values', () => { const template = new PathTemplate( - 'projects/{project}/sessions/{session}' + 'projects/{project}/sessions/{session}', ); const params = { project: 'testProject', @@ -215,7 +215,7 @@ describe('PathTemplate', () => { it('should render non-slash resource', () => { const template = new PathTemplate( - 'user/{user_id}/blurbs/legacy/{blurb_id}.{legacy_user}/project/{project}' + 'user/{user_id}/blurbs/legacy/{blurb_id}.{legacy_user}/project/{project}', ); const params = { user_id: 'foo', diff --git a/gax/test/unit/regapic.ts b/gax/test/unit/regapic.ts index 6c85e75dd..0616d7cb7 100644 --- a/gax/test/unit/regapic.ts +++ b/gax/test/unit/regapic.ts @@ -14,9 +14,8 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it, afterEach, before} from 'mocha'; -import * as nodeFetch from 'node-fetch'; import * as protobuf from 'protobufjs'; import * as path from 'path'; import * as sinon from 'sinon'; @@ -27,6 +26,7 @@ import * as transcoding from '../../src/transcoding'; import {OAuth2Client} from 'google-auth-library'; import {GrpcClientOptions} from '../../src'; import {StreamArrayParser} from '../../src/streamArrayParser'; +import proxyquire from 'proxyquire'; const authClient = { async getRequestHeaders() { @@ -80,7 +80,7 @@ describe('REGAPIC', () => { '..', 'test', 'fixtures', - 'library.json' + 'library.json', ); // eslint-disable-next-line @typescript-eslint/no-var-requires libProtos = gaxGrpc.loadProtoJSON(require(TEST_JSON)); @@ -90,33 +90,36 @@ describe('REGAPIC', () => { afterEach(() => { sinon.restore(); }); - - it('should make a request', done => { + it('should make a request', async () => { const requestObject = {content: 'test-content'}; - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(requestObject))); - }, - }) - ); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { - echoStub.echo(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - requestObject.content, - (result as {content: string}).content - ); - done(); - }); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(requestObject))); + }, + }); + }, }); + + const gaxGrpcMock = new GrpcClient(); + + (await gaxGrpcMock) + .createStub(echoService, stubOptions) + .then((echoStub: any) => { + echoStub.echo(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + requestObject.content, + (result as {content: string}).content, + ); + }); + }); }); - it('should make a streaming request', done => { + it('should make a streaming request', async () => { const requestObject = {content: 'test content'}; const responseObject = [{content: 'test'}, {content: 'content'}]; const responseObjectJson = JSON.stringify(responseObject, null, ' '); @@ -126,236 +129,275 @@ describe('REGAPIC', () => { responseStream.push(null); // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - body: responseStream, - }) - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + body: responseStream, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { const stream = echoStub.expand( requestObject, {}, {}, - () => {} + () => {}, ) as StreamArrayParser; const results: {}[] = []; - stream.on('data', data => { + stream.on('data', (data: {}) => { results.push(data); }); - stream.on('error', done); + stream.on('error', () => { + return; + }); stream.on('end', () => { assert.deepStrictEqual(results, responseObject); - done(); }); }); }); - it('should handle fetch failure', done => { + it('should handle fetch failure', async () => { const requestObject = {content: 'test-content'}; - sinon - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .stub(nodeFetch, 'Promise' as any) - .returns(Promise.reject(new Error('Fetch error'))); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.reject(new Error('Fetch error')); + }, + }); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock.createStub(echoService, stubOptions).then((echoStub: any) => { echoStub.echo(requestObject, {}, {}, (err?: {}) => { assert.strictEqual((err as Error).message, 'Fetch error'); - done(); }); }); }); - it('should handle streaming request failure', done => { + it('should handle streaming request failure', async () => { const requestObject = {content: 'test content'}; - sinon - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .stub(nodeFetch, 'Promise' as any) - .returns(Promise.reject(new Error('Fetch error'))); - gaxGrpc.createStub(echoService, stubOptions).then(echoStub => { - const stream = echoStub.expand(requestObject) as StreamArrayParser; - stream.on('error', err => { - assert.strictEqual((err as Error).message, 'Fetch error'); - done(); - }); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.reject(new Error('Fetch error')); + }, }); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpc + .createStub(echoService, stubOptions) + .then((echoStub: any) => { + const stream = echoStub.expand(requestObject) as StreamArrayParser; + stream.on('error', (err: Error) => { + assert.strictEqual((err as Error).message, 'Fetch error'); + }); + }) + .catch(console.error); }); describe('should support enum conversion in proto message', () => { - it('should support enum conversion in proto message response', done => { + it('should support enum conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name'}; const responseObject = { name: 'shelf-name', theme: 'shelf-theme', type: 1, }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); - }, - }) - ); + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)), + ); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - assert.strictEqual( - 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name - ); - assert.strictEqual( - 'TYPEONE', - (result as {name: {}; theme: {}; type: {}}).type - ); - done(); + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + assert.strictEqual( + 'shelf-name', + (result as {name: {}; theme: {}; type: {}}).name, + ); + assert.strictEqual( + 'TYPEONE', + (result as {name: {}; theme: {}; type: {}}).type, + ); + }); }); - }, /* catch: */ done); }); - it('should support enum conversion in proto message request using symbolic name', done => { + it('should support enum conversion in proto message request using symbolic name', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 'TYPEONE', }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }) - ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.createShelf(requestObject, {}, {}, (err?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - done(); + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); + + const gaxGrpcMock = new GrpcClient(); + + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.createShelf(requestObject, {}, {}, (err?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + }); }); - }, /* catch: */ done); }); - it('should support enum conversion in proto message request using type value', done => { + it('should support enum conversion in proto message request using type value', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 1, }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }) - ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.createShelf(requestObject, {}, {}, (err?: {}) => { - assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); - assert.strictEqual(err, null); - done(); + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.createShelf(requestObject, {}, {}, (err?: {}) => { + assert.strictEqual(spy.getCall(0).returnValue?.queryString, ''); + assert.strictEqual(err, null); + }); }); - }, /* catch: */ done); }); }); describe('should support enum conversion in proto message with numeric enums enabled', () => { - it('should support enum conversion in proto message response', done => { + it('should support enum conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name'}; const responseObject = { name: 'shelf-name', theme: 'shelf-theme', type: 100, // unknown enum value }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); - }, - }) - ); + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)), + ); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); + + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); - gaxGrpcNumericEnums + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - '$alt=json%3Benum-encoding=int' + '$alt=json%3Benum-encoding=int', ); assert.strictEqual(err, null); assert.strictEqual( 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name + (result as {name: {}; theme: {}; type: {}}).name, ); assert.strictEqual( 100, - (result as {name: {}; theme: {}; type: {}}).type + (result as {name: {}; theme: {}; type: {}}).type, ); - done(); }); - }, /* catch: */ done); + }); }); - it('should request numeric enums if passed as symbolic name', done => { + it('should request numeric enums if passed as symbolic name', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 'TYPEONE', }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }) - ); - gaxGrpcNumericEnums + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); + + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( - 'string', - typeof spy.getCall(0).returnValue?.queryString - ); - assert.match( - spy.getCall(0).returnValue?.queryString, - /\$alt=json%3Benum-encoding=int(&.*)?$/ + spy.getCall(0).returnValue?.queryString, + '$alt=json%3Benum-encoding=int', ); assert.strictEqual(err, null); - done(); }); - }, /* catch: */ done); + }); }); - it('should preserve query string when appending numeric enums parameter', done => { + it('should preserve query string when appending numeric enums parameter', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', @@ -365,66 +407,78 @@ describe('REGAPIC', () => { shelf: shelf, queryStringParameter: 'must-be-preserved', }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }) - ); - gaxGrpcNumericEnums + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); + + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - 'queryStringParameter=must-be-preserved&$alt=json%3Benum-encoding=int' + 'queryStringParameter=must-be-preserved&$alt=json%3Benum-encoding=int', ); assert.strictEqual(err, null); - done(); }); - }, /* catch: */ done); + }); }); - it('should request numeric enums if passed as an unknown number', done => { + it('should request numeric enums if passed as an unknown number', async () => { const shelf = { name: 'shelf-name', theme: 'shelf-theme', type: 100, }; const requestObject = {shelf: shelf}; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(shelf))); - }, - }) - ); - gaxGrpcNumericEnums + const spy = sinon.spy(); + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve(Buffer.from(JSON.stringify(shelf))); + }, + }); + }, + '../src/transcoding.js': {transcode: spy}, + }); + + const gaxGrpcNumericEnumsMock = new GrpcClient({ + ...opts, + numericEnums: true, + }); + gaxGrpcNumericEnumsMock .createStub(libraryService, stubOptions) - .then(libStub => { + .then((libStub: any) => { libStub.createShelf(requestObject, {}, {}, (err?: {}) => { assert.strictEqual( spy.getCall(0).returnValue?.queryString, - '$alt=json%3Benum-encoding=int' + '$alt=json%3Benum-encoding=int', ); assert.strictEqual(err, null); - done(); }); - }, /* catch: */ done); + }); }); }); describe('should support long data type conversion in proto message', () => { - it('large number long data type conversion in proto message response', done => { + it('large number long data type conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name/books/book-name'}; const responseObject = { name: 'book-name', @@ -433,49 +487,55 @@ describe('REGAPIC', () => { read: true, bookId: 9007199254740992, }; - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); - }, - }) - ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name - ); - assert.strictEqual( - '9007199254740992', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId - ); - done(); + + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)), + ); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name, + ); + assert.strictEqual( + '9007199254740992', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId, + ); + }); }); - }, /* catch: */ done); }); - it('small number long data type conversion in proto message response', done => { + it('small number long data type conversion in proto message response', async () => { const requestObject = {name: 'shelves/shelf-name/books/book-name'}; const responseObject = { name: 'book-name', @@ -485,48 +545,54 @@ describe('REGAPIC', () => { bookId: 42, }; // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); - }, - }) - ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name - ); - assert.strictEqual( - '42', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId - ); - done(); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)), + ); + }, + }); + }, + }); + + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock + .createStub(libraryService, stubOptions) + .then((libStub: any) => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { + assert.strictEqual(err, null); + assert.strictEqual( + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name, + ); + assert.strictEqual( + '42', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId, + ); + }); }); - }, /* catch: */ done); }); - it('long data type conversion in proto message request', done => { + it('long data type conversion in proto message request', async () => { const bookId = 9007199254740992; const requestObject = {name: `shelves/shelf-name/book_id/${bookId}`}; const responseObject = { @@ -538,134 +604,51 @@ describe('REGAPIC', () => { }; // incomplete types for nodeFetch, so... // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); - }, - }) - ); - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual(err, null); - assert.strictEqual( - 'book-name', - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).name - ); - assert.strictEqual( - bookId.toString(), - ( - result as { - name: {}; - author: {}; - title: {}; - read: false; - bookId: {}; - } - ).bookId - ); - done(); - }); - }, /* catch: */ done); - }); - }); - - describe('should support json minification', () => { - it('should send prettyPrint=0 when json minification is requested', done => { - const requestObject = {name: 'shelves/shelf-name'}; - const responseObject = { - name: 'shelf-name', - theme: 'shelf-theme', - type: 100, // unknown enum value - }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); - }, - }) - ); + const {GrpcClient} = await proxyquire('../../src/fallback.js', { + 'node-fetch': () => { + return Promise.resolve({ + ok: true, + arrayBuffer: () => { + return Promise.resolve( + Buffer.from(JSON.stringify(responseObject)), + ); + }, + }); + }, + }); - gaxGrpcMinifyJson + const gaxGrpcMock = new GrpcClient(); + gaxGrpcMock .createStub(libraryService, stubOptions) - .then(libStub => { - libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual( - 'string', - typeof spy.getCall(0).returnValue?.queryString - ); - assert.match( - spy.getCall(0).returnValue?.queryString, - /\$prettyPrint=0(&.*)?$/ - ); + .then((libStub: any) => { + libStub.getBook(requestObject, {}, {}, (err?: {}, result?: {}) => { assert.strictEqual(err, null); assert.strictEqual( - 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name + 'book-name', + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).name, ); assert.strictEqual( - 100, - (result as {name: {}; theme: {}; type: {}}).type + bookId.toString(), + ( + result as { + name: {}; + author: {}; + title: {}; + read: false; + bookId: {}; + } + ).bookId, ); - done(); }); - }, /* catch: */ done); - }); - - it('should not send prettyPrint setting when json minification is not requested', done => { - const requestObject = {name: 'shelves/shelf-name'}; - const responseObject = { - name: 'shelf-name', - theme: 'shelf-theme', - type: 100, // unknown enum value - }; - const spy = sinon.spy(transcoding, 'transcode'); - // incomplete types for nodeFetch, so... - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sinon.stub(nodeFetch, 'Promise' as any).returns( - Promise.resolve({ - ok: true, - arrayBuffer: () => { - return Promise.resolve(Buffer.from(JSON.stringify(responseObject))); - }, - }) - ); - - gaxGrpc.createStub(libraryService, stubOptions).then(libStub => { - libStub.getShelf(requestObject, {}, {}, (err?: {}, result?: {}) => { - assert.strictEqual( - 'string', - typeof spy.getCall(0).returnValue?.queryString - ); - assert.doesNotMatch( - spy.getCall(0).returnValue?.queryString, - /prettyPrint/ - ); - assert.strictEqual(err, null); - assert.strictEqual( - 'shelf-name', - (result as {name: {}; theme: {}; type: {}}).name - ); - assert.strictEqual( - 100, - (result as {name: {}; theme: {}; type: {}}).type - ); - done(); }); - }, /* catch: */ done); }); }); }); diff --git a/gax/test/unit/routingHeader.ts b/gax/test/unit/routingHeader.ts index a1e318830..1e7c77f83 100644 --- a/gax/test/unit/routingHeader.ts +++ b/gax/test/unit/routingHeader.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {fromParams} from '../../src/routingHeader'; import {describe, it} from 'mocha'; @@ -28,7 +28,7 @@ describe('fromParams', () => { const routingHeader = fromParams({screaming: '😱', cyrillic: 'тест'}); assert.strictEqual( routingHeader, - 'screaming=%F0%9F%98%B1&cyrillic=%D1%82%D0%B5%D1%81%D1%82' + 'screaming=%F0%9F%98%B1&cyrillic=%D1%82%D0%B5%D1%81%D1%82', ); }); }); diff --git a/gax/test/unit/status.ts b/gax/test/unit/status.ts index 3007be4dc..1302e2c28 100644 --- a/gax/test/unit/status.ts +++ b/gax/test/unit/status.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import {rpcCodeFromHttpStatusCode, Status} from '../../src/status'; @@ -26,40 +26,40 @@ describe('status.ts', () => { assert.deepStrictEqual(rpcCodeFromHttpStatusCode(307), Status.UNKNOWN); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(400), - Status.INVALID_ARGUMENT + Status.INVALID_ARGUMENT, ); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(401), - Status.UNAUTHENTICATED + Status.UNAUTHENTICATED, ); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(403), - Status.PERMISSION_DENIED + Status.PERMISSION_DENIED, ); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(404), Status.NOT_FOUND); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(409), Status.ABORTED); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(416), Status.OUT_OF_RANGE); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(429), - Status.RESOURCE_EXHAUSTED + Status.RESOURCE_EXHAUSTED, ); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(499), Status.CANCELLED); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(451), - Status.FAILED_PRECONDITION + Status.FAILED_PRECONDITION, ); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(411), - Status.FAILED_PRECONDITION + Status.FAILED_PRECONDITION, ); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(501), - Status.UNIMPLEMENTED + Status.UNIMPLEMENTED, ); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(503), Status.UNAVAILABLE); assert.deepStrictEqual( rpcCodeFromHttpStatusCode(504), - Status.DEADLINE_EXCEEDED + Status.DEADLINE_EXCEEDED, ); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(505), Status.INTERNAL); assert.deepStrictEqual(rpcCodeFromHttpStatusCode(510), Status.INTERNAL); diff --git a/gax/test/unit/streamArrayParser.ts b/gax/test/unit/streamArrayParser.ts index 61325031b..ca9da211b 100644 --- a/gax/test/unit/streamArrayParser.ts +++ b/gax/test/unit/streamArrayParser.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {StreamArrayParser} from '../../src/streamArrayParser'; import {before, describe, it} from 'mocha'; import {pipeline} from 'stream'; @@ -102,7 +102,7 @@ describe('Parse REST stream array', () => { }, ]; const inStream = createRandomChunkReadableStream( - JSON.stringify(expectedResults) + JSON.stringify(expectedResults), ); inStream.on('data', d => { assert.notEqual(d, undefined); @@ -125,7 +125,7 @@ describe('Parse REST stream array', () => { const expect = toProtobufJSON(User, expectedResults[key]); assert.strictEqual( JSON.stringify(results[key]), - JSON.stringify(expect) + JSON.stringify(expect), ); } done(); @@ -143,7 +143,7 @@ describe('Parse REST stream array', () => { }, ]; const inStream = createRandomChunkReadableStream( - JSON.stringify(expectedResults) + JSON.stringify(expectedResults), ); const streamArrayParser = new StreamArrayParser(streamMethod); pipeline(inStream, streamArrayParser, err => { @@ -165,7 +165,7 @@ describe('Parse REST stream array', () => { it("should listen on error if input stream is not start '['", done => { const expectedResults = {}; const inStream = createRandomChunkReadableStream( - JSON.stringify(expectedResults) + JSON.stringify(expectedResults), ); const streamArrayParser = new StreamArrayParser(streamMethod); pipeline(inStream, streamArrayParser, err => { diff --git a/gax/test/unit/streaming.ts b/gax/test/unit/streaming.ts index 4c291abe9..5aa3512a1 100644 --- a/gax/test/unit/streaming.ts +++ b/gax/test/unit/streaming.ts @@ -16,7 +16,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ -import * as assert from 'assert'; +import assert from 'assert'; import * as sinon from 'sinon'; import {afterEach, describe, it} from 'mocha'; import {PassThrough, Transform, pipeline} from 'stream'; @@ -47,14 +47,14 @@ function createApiCallStreaming( | sinon.SinonSpy, internal.Transform | StreamArrayParser>, type: streaming.StreamType, rest?: boolean, - gaxStreamingRetries?: boolean + gaxStreamingRetries?: boolean, ) { const settings = new gax.CallSettings(); return createApiCall( //@ts-ignore Promise.resolve(func), settings, - new StreamDescriptor(type, rest, gaxStreamingRetries) + new StreamDescriptor(type, rest, gaxStreamingRetries), ) as GaxCallStream; } @@ -80,7 +80,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( spy, - streaming.StreamType.SERVER_STREAMING + streaming.StreamType.SERVER_STREAMING, ); const s = apiCall({}, undefined); const callback = sinon.spy(data => { @@ -119,7 +119,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( //@ts-ignore func, - streaming.StreamType.CLIENT_STREAMING + streaming.StreamType.CLIENT_STREAMING, ); const s = apiCall({}, undefined, (err, response) => { assert.strictEqual(err, null); @@ -148,7 +148,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( //@ts-ignore func, - streaming.StreamType.BIDI_STREAMING + streaming.StreamType.BIDI_STREAMING, ); const s = apiCall({}, undefined); const arg = {foo: 'bar'}; @@ -191,7 +191,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( //@ts-ignore func, - streaming.StreamType.BIDI_STREAMING + streaming.StreamType.BIDI_STREAMING, ); const s = apiCall({}, undefined); let receivedMetadata: {}; @@ -266,7 +266,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( //@ts-ignore func, - streaming.StreamType.SERVER_STREAMING + streaming.StreamType.SERVER_STREAMING, ); const s = apiCall( {}, @@ -279,7 +279,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 0, }), - } + }, ); let counter = 0; const expectedCount = 5; @@ -331,7 +331,7 @@ describe('streaming', () => { func, streaming.StreamType.SERVER_STREAMING, false, - true // gax native retries + true, // gax native retries ); const s = apiCall( {}, @@ -344,7 +344,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 0, }), - } + }, ); let counter = 0; const expectedCount = 5; @@ -393,7 +393,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( spy, - streaming.StreamType.SERVER_STREAMING + streaming.StreamType.SERVER_STREAMING, ); const s = apiCall({}, undefined); let receivedMetadata: {}; @@ -473,7 +473,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new gax retries + true, // new gax retries ); const s = apiCall({}, undefined); let receivedMetadata: {}; @@ -547,7 +547,7 @@ describe('streaming', () => { const apiCall = createApiCallStreaming( spy, - streaming.StreamType.SERVER_STREAMING + streaming.StreamType.SERVER_STREAMING, ); const s = apiCall({}, undefined); let receivedStatus: {}; @@ -615,7 +615,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new gax retries + true, // new gax retries ); const s = apiCall({}, undefined); let receivedStatus: {}; @@ -702,7 +702,7 @@ describe('streaming', () => { }); const apiCall = createApiCallStreaming( spy, - streaming.StreamType.SERVER_STREAMING + streaming.StreamType.SERVER_STREAMING, ); const s = apiCall( @@ -716,7 +716,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 0, }), - } + }, ); s.on('error', err => { @@ -728,7 +728,7 @@ describe('streaming', () => { assert.strictEqual(err.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); done(); }); @@ -783,7 +783,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s = apiCall( @@ -797,7 +797,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 0, }), - } + }, ); s.on('error', err => { @@ -809,7 +809,7 @@ describe('streaming', () => { assert.strictEqual(err.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); done(); }); @@ -865,7 +865,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s = apiCall( @@ -879,7 +879,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 1, // max retries or timeout must be > 0 in order to reach the code we want to test }), - } + }, ); s.on('error', err => { @@ -890,13 +890,13 @@ describe('streaming', () => { assert.deepStrictEqual(err.message, 'test error'); assert.deepStrictEqual( err.note, - 'Exception occurred in retry method that was not classified as transient' + 'Exception occurred in retry method that was not classified as transient', ); assert.strictEqual(err.domain, errorInfoObj.domain); assert.strictEqual(err.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); done(); }); @@ -950,7 +950,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s = apiCall( @@ -964,7 +964,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, // neither maxRetries nor totalTimeoutMillis is defined }), - } + }, ); s.on('error', err => { @@ -975,13 +975,13 @@ describe('streaming', () => { assert.deepStrictEqual(err.message, 'test error'); assert.deepStrictEqual( err.note, - 'Exception occurred in retry method that was not classified as transient' + 'Exception occurred in retry method that was not classified as transient', ); assert.strictEqual(err.domain, errorInfoObj.domain); assert.strictEqual(err.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); done(); }); @@ -1074,7 +1074,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s = apiCall( {}, @@ -1087,7 +1087,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 2, // max retries or timeout must be > 0 in order to reach the code we want to test }), - } + }, ); s.on('error', err => { @@ -1097,13 +1097,13 @@ describe('streaming', () => { assert.deepStrictEqual(err.message, 'test error 2'); assert.deepStrictEqual( err.note, - 'Exception occurred in retry method that was not classified as transient' + 'Exception occurred in retry method that was not classified as transient', ); assert.strictEqual(err.domain, errorInfoObj.domain); assert.strictEqual(err.reason, errorInfoObj.reason); assert.strictEqual( JSON.stringify(err.errorInfoMetadata), - JSON.stringify(errorInfoObj.metadata) + JSON.stringify(errorInfoObj.metadata), ); done(); }); @@ -1138,7 +1138,7 @@ describe('streaming', () => { counter++; assert.deepStrictEqual( receivedData.join(' '), - 'Hello World testing retries' + 'Hello World testing retries', ); done(); break; @@ -1153,7 +1153,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // streaming retries + true, // streaming retries ); const s = apiCall( @@ -1167,7 +1167,7 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 1, }), - } + }, ); s.on('data', data => { receivedData.push(data); @@ -1230,7 +1230,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retries + true, // new retries ); function shouldRetryFn(error: GoogleError) { @@ -1249,9 +1249,9 @@ describe('streaming', () => { maxRpcTimeoutMillis: 3000, maxRetries: 2, // maxRetries must be > 1 to ensure we hit both checks for a shouldRetry function }, - shouldRetryFn + shouldRetryFn, ), - } + }, ); const finalData: string[] = []; s.on('data', data => { @@ -1334,7 +1334,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); // resumption strategy is to pass a different arg to the function const getResumptionRequestFn = sinon.spy((originalRequest: RequestType) => { @@ -1355,9 +1355,9 @@ describe('streaming', () => { maxRetries: 2, // max retries or timeout must be > 0 in order to reach the code we want to test }, undefined, - getResumptionRequestFn + getResumptionRequestFn, ), - } + }, ); s.on('data', data => { receivedData.push(data); @@ -1372,7 +1372,7 @@ describe('streaming', () => { assert.strictEqual(receivedData.length, 4); assert.deepStrictEqual( receivedData.join(' '), - 'Hello World testing retries' + 'Hello World testing retries', ); assert.strictEqual(getResumptionRequestFn.callCount, 1); done(); @@ -1438,7 +1438,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - false // new retry behavior disabled + false, // new retry behavior disabled ); // resumption strategy is to pass a different arg to the function const getResumptionRequestFn = (originalRequest: RequestType) => { @@ -1459,9 +1459,9 @@ describe('streaming', () => { maxRetries: 2, // max retries or timeout must be > 0 in order to reach the code we want to test }, undefined, - getResumptionRequestFn + getResumptionRequestFn, ), - } + }, ); s.on('error', err => { @@ -1469,7 +1469,7 @@ describe('streaming', () => { // stream will continue after retry assert.deepStrictEqual( err.message, - 'getResumptionRequestFn can only be used when gaxStreamingRetries is set to true.' + 'getResumptionRequestFn can only be used when gaxStreamingRetries is set to true.', ); done(); }); @@ -1498,7 +1498,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s1 = apiCall({}, undefined); @@ -1508,7 +1508,7 @@ describe('streaming', () => { transform: (data, _encoding, callback) => { callback( null, - data.resources.map((element: number) => element + 1) + data.resources.map((element: number) => element + 1), ); }, }); @@ -1526,7 +1526,7 @@ describe('streaming', () => { s2.on('end', () => { assert.strictEqual( JSON.stringify(finalResults), - JSON.stringify([[2, 3]]) + JSON.stringify([[2, 3]]), ); done(); }); @@ -1534,7 +1534,7 @@ describe('streaming', () => { pipeline(s1, transform, s2, err => { if (err) { throw new Error( - 'pipeline in properly emits the end event at the end of a pipeline transformation test failed' + 'pipeline in properly emits the end event at the end of a pipeline transformation test failed', ); } }); @@ -1563,7 +1563,7 @@ describe('streaming', () => { spy, streaming.StreamType.SERVER_STREAMING, false, - true // new retry behavior enabled + true, // new retry behavior enabled ); const s1 = apiCall({}, undefined); @@ -1574,7 +1574,7 @@ describe('streaming', () => { setTimeout(() => { callback( null, - data.resources.map((element: number) => element + 1) + data.resources.map((element: number) => element + 1), ); }, 10); }, @@ -1593,7 +1593,7 @@ describe('streaming', () => { s2.on('end', () => { assert.strictEqual( JSON.stringify(finalResults), - JSON.stringify([[2, 3]]) + JSON.stringify([[2, 3]]), ); done(); }); @@ -1601,7 +1601,7 @@ describe('streaming', () => { pipeline(s1, transform, s2, err => { if (err) { throw new Error( - 'pipeline in properly emits the end event at the end of a pipeline transformation test failed' + 'pipeline in properly emits the end event at the end of a pipeline transformation test failed', ); } }); @@ -1615,7 +1615,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en it('server streaming call retries until exceeding timeout and surfaces underlying error', done => { const retrySpy = sinon.spy( streaming.StreamProxy.prototype, - 'throwIfMaxRetriesOrTotalTimeoutExceeded' + 'throwIfMaxRetriesOrTotalTimeoutExceeded', ); const firstError = Object.assign(new GoogleError('UNAVAILABLE'), { code: 14, @@ -1641,7 +1641,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true + true, ); const call = apiCall( @@ -1655,7 +1655,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, totalTimeoutMillis: 200, // timeout that ensures it should retry at least once }), - } + }, ); call.on('error', err => { @@ -1667,7 +1667,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert.notStrictEqual(retrySpy.callCount, 0); // it MUST retry at least once assert.strictEqual( err.message, - 'Total timeout of API exceeded 200 milliseconds retrying error Error: UNAVAILABLE before any response was received.' + 'Total timeout of API exceeded 200 milliseconds retrying error Error: UNAVAILABLE before any response was received.', ); done(); } @@ -1680,7 +1680,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en it('server streaming call retries until exceeding max retries and surfaces underlying error in note', done => { const retrySpy = sinon.spy( streaming.StreamProxy.prototype, - 'throwIfMaxRetriesOrTotalTimeoutExceeded' + 'throwIfMaxRetriesOrTotalTimeoutExceeded', ); const firstError = Object.assign(new GoogleError('UNAVAILABLE'), { code: 14, @@ -1706,7 +1706,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true + true, ); const call = apiCall( @@ -1720,7 +1720,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, maxRetries: 2, }), - } + }, ); call.on('error', err => { @@ -1732,7 +1732,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert.strictEqual(retrySpy.callCount, 3); // we pass the first two times assert.strictEqual( err.message, - 'Exceeded maximum number of retries retrying error Error: UNAVAILABLE before any response was received' + 'Exceeded maximum number of retries retrying error Error: UNAVAILABLE before any response was received', ); done(); } @@ -1746,7 +1746,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en // we don't call the timeout/max retry check on non retryable error codes const retrySpy = sinon.spy( streaming.StreamProxy.prototype, - 'throwIfMaxRetriesOrTotalTimeoutExceeded' + 'throwIfMaxRetriesOrTotalTimeoutExceeded', ); const firstError = Object.assign(new GoogleError('UNAVAILABLE'), { code: 14, @@ -1773,7 +1773,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true + true, ); const call = apiCall( @@ -1788,7 +1788,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, maxRetries: 2, }), - } + }, ); call.on('error', err => { @@ -1827,7 +1827,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true + true, ); const call = apiCall( @@ -1841,7 +1841,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, totalTimeoutMillis: 10, }), - } + }, ); call.on('error', err => { @@ -1851,7 +1851,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert.strictEqual(err.code, 4); assert.strictEqual( err.message, - 'Total timeout of API exceeded 10 milliseconds retrying error Error: UNAVAILABLE before any response was received.' + 'Total timeout of API exceeded 10 milliseconds retrying error Error: UNAVAILABLE before any response was received.', ); done(); } @@ -1877,7 +1877,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true //gaxStreamingRetries + true, //gaxStreamingRetries ); // anonymous function is a shouldRetryFn @@ -1896,9 +1896,9 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en }, () => { return true; - } + }, ), - } + }, ); }); @@ -1921,7 +1921,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true //gaxStreamingRetries + true, //gaxStreamingRetries ); apiCall( @@ -1935,7 +1935,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, totalTimeoutMillis: 4500, }), - } + }, ); }); @@ -1967,7 +1967,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true //gaxStreamingRetries + true, //gaxStreamingRetries ); // "resumption" strategy is to just return the original request @@ -1989,9 +1989,9 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en totalTimeoutMillis: 4500, }, undefined, - getResumptionRequestFn + getResumptionRequestFn, ), - } + }, ); }); @@ -2025,7 +2025,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // ensure we're doing the new retries + true, // ensure we're doing the new retries ); // make the call with both options passed at call time @@ -2041,7 +2041,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en totalTimeoutMillis: 4000, maxRetries: 5, }), - } + }, ); call.on('error', err => { assert(err instanceof GoogleError); @@ -2049,7 +2049,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert.strictEqual(err.code, 3); assert.strictEqual( err.message, - 'Cannot set both totalTimeoutMillis and maxRetries in backoffSettings.' + 'Cannot set both totalTimeoutMillis and maxRetries in backoffSettings.', ); done(); } @@ -2074,7 +2074,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // ensure we're doing the new retries + true, // ensure we're doing the new retries ); const passedRetryRequestOptions = { @@ -2103,13 +2103,13 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en maxRpcTimeoutMillis: 3000, totalTimeoutMillis: 4500, }), - } + }, ); } catch (err) { assert(err instanceof Error); assert.strictEqual( err.toString(), - 'Error: Only one of retry or retryRequestOptions may be set' + 'Error: Only one of retry or retryRequestOptions may be set', ); done(); } @@ -2128,16 +2128,16 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert(typeof settings.retryRequestOptions === 'undefined'); assert.strictEqual( settings.retry?.backoffSettings.maxRetryDelayMillis, - 70000 + 70000, ); assert.strictEqual( settings.retry?.backoffSettings.retryDelayMultiplier, - 3 + 3, ); // totalTimeout is undefined because maxRetries is passed assert( typeof settings.retry?.backoffSettings.totalTimeoutMillis === - 'undefined' + 'undefined', ); assert.strictEqual(settings.retry?.backoffSettings.maxRetries, 1); @@ -2162,7 +2162,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // gaxStreamingRetries + true, // gaxStreamingRetries ); const passedRetryRequestOptions = { objectMode: false, @@ -2180,7 +2180,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en {}, { retryRequestOptions: passedRetryRequestOptions, - } + }, ); assert.strictEqual(warnStub.callCount, 4); @@ -2188,29 +2188,29 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en warnStub.calledWith( 'retry_request_options', 'retryRequestOptions will be deprecated in a future release. Please use retryOptions to pass retry options at call time', - 'DeprecationWarning' - ) + 'DeprecationWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'noResponseRetries override is not supported. Please specify retry codes or a function to determine retry eligibility.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'currentRetryAttempt override is not supported. Retry attempts are tracked internally.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'objectMode override is not supported. It is set to true internally by default in gax.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); }); @@ -2227,16 +2227,16 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert(typeof settings.retryRequestOptions === 'undefined'); assert.strictEqual( settings.retry?.backoffSettings.maxRetryDelayMillis, - 0 + 0, ); assert.strictEqual( settings.retry?.backoffSettings.retryDelayMultiplier, - 0 + 0, ); // totalTimeout is undefined because maxRetries is passed assert( typeof settings.retry?.backoffSettings.totalTimeoutMillis === - 'undefined' + 'undefined', ); assert.strictEqual(settings.retry?.backoffSettings.maxRetries, 0); @@ -2261,7 +2261,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // gaxStreamingRetries + true, // gaxStreamingRetries ); const passedRetryRequestOptions = { objectMode: false, @@ -2279,7 +2279,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en {}, { retryRequestOptions: passedRetryRequestOptions, - } + }, ); assert.strictEqual(warnStub.callCount, 4); @@ -2287,29 +2287,29 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en warnStub.calledWith( 'retry_request_options', 'retryRequestOptions will be deprecated in a future release. Please use retryOptions to pass retry options at call time', - 'DeprecationWarning' - ) + 'DeprecationWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'noResponseRetries override is not supported. Please specify retry codes or a function to determine retry eligibility.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'currentRetryAttempt override is not supported. Retry attempts are tracked internally.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'objectMode override is not supported. It is set to true internally by default in gax.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); }); @@ -2326,18 +2326,18 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert(typeof settings.retryRequestOptions === 'undefined'); assert.strictEqual( settings.retry?.backoffSettings.maxRetryDelayMillis, - 70000 + 70000, ); assert.strictEqual( settings.retry?.backoffSettings.retryDelayMultiplier, - 3 + 3, ); assert.strictEqual( settings.retry?.backoffSettings.totalTimeoutMillis, - 650000 + 650000, ); assert( - typeof settings.retry?.backoffSettings.maxRetries === 'undefined' + typeof settings.retry?.backoffSettings.maxRetries === 'undefined', ); assert(settings.retry.shouldRetryFn); assert(settings.retry.retryCodes.length === 0); @@ -2360,7 +2360,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // gaxStreamingRetries + true, // gaxStreamingRetries ); const passedRetryRequestOptions = { objectMode: false, @@ -2377,7 +2377,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en {}, { retryRequestOptions: passedRetryRequestOptions, - } + }, ); assert.strictEqual(warnStub.callCount, 4); @@ -2385,29 +2385,29 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en warnStub.calledWith( 'retry_request_options', 'retryRequestOptions will be deprecated in a future release. Please use retryOptions to pass retry options at call time', - 'DeprecationWarning' - ) + 'DeprecationWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'objectMode override is not supported. It is set to true internally by default in gax.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'noResponseRetries override is not supported. Please specify retry codes or a function to determine retry eligibility.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'currentRetryAttempt override is not supported. Retry attempts are tracked internally.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); }); @@ -2424,18 +2424,18 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en assert(typeof settings.retryRequestOptions === 'undefined'); assert.strictEqual( settings.retry?.backoffSettings.maxRetryDelayMillis, - 0 + 0, ); assert.strictEqual( settings.retry?.backoffSettings.retryDelayMultiplier, - 0 + 0, ); assert.strictEqual( settings.retry?.backoffSettings.totalTimeoutMillis, - 0 + 0, ); assert( - typeof settings.retry?.backoffSettings.maxRetries === 'undefined' + typeof settings.retry?.backoffSettings.maxRetries === 'undefined', ); assert(settings.retry.shouldRetryFn); assert(settings.retry.retryCodes.length === 0); @@ -2458,7 +2458,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en spy, streaming.StreamType.SERVER_STREAMING, false, - true // gaxStreamingRetries + true, // gaxStreamingRetries ); const passedRetryRequestOptions = { objectMode: false, @@ -2475,7 +2475,7 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en {}, { retryRequestOptions: passedRetryRequestOptions, - } + }, ); assert.strictEqual(warnStub.callCount, 4); @@ -2483,29 +2483,29 @@ describe('handles server streaming retries in gax when gaxStreamingRetries is en warnStub.calledWith( 'retry_request_options', 'retryRequestOptions will be deprecated in a future release. Please use retryOptions to pass retry options at call time', - 'DeprecationWarning' - ) + 'DeprecationWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'objectMode override is not supported. It is set to true internally by default in gax.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'noResponseRetries override is not supported. Please specify retry codes or a function to determine retry eligibility.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); assert( warnStub.calledWith( 'retry_request_options', 'currentRetryAttempt override is not supported. Retry attempts are tracked internally.', - 'UnsupportedParameterWarning' - ) + 'UnsupportedParameterWarning', + ), ); }); }); @@ -2535,7 +2535,7 @@ describe('warns/errors about server streaming retry behavior when gaxStreamingRe spy, streaming.StreamType.SERVER_STREAMING, false, - false // ensure we are NOT opted into the new retry behavior + false, // ensure we are NOT opted into the new retry behavior ); // make the call with neither retry option passed at call time @@ -2563,7 +2563,7 @@ describe('REST streaming apiCall return StreamArrayParser', () => { const apiCall = createApiCallStreaming( spy, streaming.StreamType.SERVER_STREAMING, - true + true, ); const s = apiCall({}, undefined); assert.strictEqual(s.readable, true); @@ -2575,7 +2575,7 @@ describe('REST streaming apiCall return StreamArrayParser', () => { s.on('end', () => { assert.strictEqual( JSON.stringify(actualResults), - JSON.stringify([{resources: [1, 2]}, {resources: [3, 4, 5]}]) + JSON.stringify([{resources: [1, 2]}, {resources: [3, 4, 5]}]), ); done(); }); @@ -2593,7 +2593,7 @@ describe('REST streaming apiCall return StreamArrayParser', () => { const apiCall = createApiCallStreaming( spy, streaming.StreamType.SERVER_STREAMING, - true + true, ); const s = apiCall({}, undefined); assert.strictEqual(s.readable, true); diff --git a/gax/test/unit/transcoding.ts b/gax/test/unit/transcoding.ts index 1293ce2ef..f6c6669c6 100644 --- a/gax/test/unit/transcoding.ts +++ b/gax/test/unit/transcoding.ts @@ -32,7 +32,7 @@ import { buildQueryStringComponents, overrideHttpRules, } from '../../src/transcoding'; -import * as assert from 'assert'; +import assert from 'assert'; import * as protobuf from 'protobufjs'; import echoProtoJson = require('../fixtures/echo.json'); import {google} from '../../protos/http'; @@ -85,7 +85,7 @@ describe('gRPC to HTTP transcoding', () => { url: '/v3/projects/project/supportedLanguages', queryString: '', data: '', - } + }, ); assert.deepStrictEqual( @@ -95,46 +95,46 @@ describe('gRPC to HTTP transcoding', () => { url: '/v3/projects/project/supportedLanguages', queryString: 'field=value', data: '', - } + }, ); assert.deepStrictEqual( transcode( {parent: 'projects/project', field: 'value', a: 42}, - parsedOptions + parsedOptions, ), { httpMethod: 'get', url: '/v3/projects/project/supportedLanguages', queryString: 'field=value&a=42', data: '', - } + }, ); assert.deepStrictEqual( transcode( {parent: 'post1/project', field: 'value', a: 42}, - parsedOptions + parsedOptions, ), { httpMethod: 'post', url: '/v3/post1/project/supportedLanguages', queryString: '', data: {field: 'value', a: 42}, - } + }, ); assert.deepStrictEqual( transcode( {parent: 'post2/project', field: 'value', a: 42}, - parsedOptions + parsedOptions, ), { httpMethod: 'post', url: '/v3/post2/project/supportedLanguages', queryString: 'a=42', data: 'value', - } + }, ); assert.deepStrictEqual( @@ -144,7 +144,7 @@ describe('gRPC to HTTP transcoding', () => { url: '/v3/get/project/value/supportedLanguages', queryString: 'a=42', data: '', - } + }, ); // Checking camel-snake-case conversions @@ -155,14 +155,14 @@ describe('gRPC to HTTP transcoding', () => { snakeCaseBody: {snakeCaseField: 42}, fieldName: 'value', }, - parsedOptions + parsedOptions, ), { httpMethod: 'post', url: '/v3/a/first', queryString: 'fieldName=value', data: {snakeCaseField: 42}, - } + }, ); assert.deepStrictEqual( @@ -172,19 +172,19 @@ describe('gRPC to HTTP transcoding', () => { snakeCaseBody: {snakeCaseField: 42}, fieldName: 'value', }, - parsedOptions + parsedOptions, ), { httpMethod: 'post', url: '/v3/b/second', queryString: '', data: {snakeCaseBody: {snakeCaseField: 42}, fieldName: 'value'}, - } + }, ); assert.strictEqual( transcode({unknownField: 'project'}, parsedOptions), - undefined + undefined, ); }); @@ -217,7 +217,7 @@ describe('gRPC to HTTP transcoding', () => { parent: 'post1/project', IPProtocol: 'tcp', }, - parsedOptions + parsedOptions, ), { httpMethod: 'post', @@ -226,7 +226,7 @@ describe('gRPC to HTTP transcoding', () => { data: { IPProtocol: 'tcp', }, - } + }, ); assert.deepStrictEqual( transcode( @@ -235,14 +235,14 @@ describe('gRPC to HTTP transcoding', () => { IPProtocol: 'tcp', field: 'value', }, - parsedOptions + parsedOptions, ), { httpMethod: 'post', queryString: 'IPProtocol=tcp', url: '/v3/post2/project/supportedLanguages', data: 'value', - } + }, ); assert.deepStrictEqual( transcode( @@ -250,7 +250,7 @@ describe('gRPC to HTTP transcoding', () => { parent: 'post1/project', iPProtocol: 'tcp', }, - parsedOptions + parsedOptions, ), { httpMethod: 'post', @@ -259,7 +259,7 @@ describe('gRPC to HTTP transcoding', () => { data: { iPProtocol: 'tcp', }, - } + }, ); }); @@ -290,38 +290,38 @@ describe('gRPC to HTTP transcoding', () => { it('getField', () => { assert.strictEqual( getField({field: 'stringValue'}, 'field'), - 'stringValue' + 'stringValue', ); assert.strictEqual( getField({field: 'stringValue'}, 'nosuchfield'), - undefined + undefined, ); assert.strictEqual( getField({field: 'stringValue'}, 'field.subfield'), - undefined + undefined, ); assert.strictEqual( getField({field: {subfield: 'stringValue'}}, 'field.subfield'), - 'stringValue' + 'stringValue', ); assert.deepStrictEqual( getField({field: {subfield: [1, 2, 3]}}, 'field.subfield'), - [1, 2, 3] + [1, 2, 3], ); assert.strictEqual( getField({field: {subfield: 'stringValue'}}, 'field'), - undefined + undefined, ); assert.strictEqual( getField({field: {subfield: 'stringValue'}}, 'field.nosuchfield'), - undefined + undefined, ); assert.strictEqual( getField( {field: {subfield: {subsubfield: 'stringValue'}}}, - 'field.subfield.subsubfield' + 'field.subfield.subsubfield', ), - 'stringValue' + 'stringValue', ); }); @@ -364,9 +364,9 @@ describe('gRPC to HTTP transcoding', () => { assert.strictEqual(encodeWithSlashes('тест'), '%D1%82%D0%B5%D1%81%D1%82'); assert.strictEqual( encodeWithSlashes( - '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ ' + '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ ', ), - '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%2F%20' + '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%2F%20', ); }); @@ -374,13 +374,13 @@ describe('gRPC to HTTP transcoding', () => { assert.strictEqual(encodeWithoutSlashes('abcd'), 'abcd'); assert.strictEqual( encodeWithoutSlashes('тест'), - '%D1%82%D0%B5%D1%81%D1%82' + '%D1%82%D0%B5%D1%81%D1%82', ); assert.strictEqual( encodeWithoutSlashes( - '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ ' + '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/ ', ), - '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/%20' + '_.~0-9abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/%20', ); }); @@ -390,24 +390,24 @@ describe('gRPC to HTTP transcoding', () => { assert.strictEqual(applyPattern('fail', 'test'), undefined); assert.strictEqual( applyPattern('projects/*', 'projects/test'), - 'projects/test' + 'projects/test', ); assert.strictEqual( applyPattern('projects/*/locations/*', 'projects/test'), - undefined + undefined, ); assert.strictEqual(applyPattern('locations/*', 'projects/test'), undefined); assert.strictEqual( applyPattern('projects/*/locations/*', 'projects/test/locations/us'), - 'projects/test/locations/us' + 'projects/test/locations/us', ); assert.strictEqual( applyPattern('projects/*/locations/*', 'projects/test/locations/us/q/z'), - undefined + undefined, ); assert.strictEqual( applyPattern('projects/*/locations/**', 'projects/test/locations/us/q/z'), - 'projects/test/locations/us/q/z' + 'projects/test/locations/us/q/z', ); }); @@ -416,7 +416,7 @@ describe('gRPC to HTTP transcoding', () => { assert.deepStrictEqual(flattenObject({field: 'value'}), {field: 'value'}); assert.deepStrictEqual( flattenObject({field: 'value', nested: {subfield: 'subvalue'}}), - {field: 'value', 'nested.subfield': 'subvalue'} + {field: 'value', 'nested.subfield': 'subvalue'}, ); }); @@ -424,46 +424,46 @@ describe('gRPC to HTTP transcoding', () => { assert.deepStrictEqual( match( {parent: 'projects/te st', test: 'value'}, - '/v3/{parent=projects/*}/supportedLanguages' + '/v3/{parent=projects/*}/supportedLanguages', ), { matchedFields: ['parent'], url: '/v3/projects/te%20st/supportedLanguages', - } + }, ); assert.deepStrictEqual( match( {parent: 'projects/te st/locations/location', test: 'value'}, - '/v3/{parent=projects/*}/supportedLanguages' + '/v3/{parent=projects/*}/supportedLanguages', ), - undefined + undefined, ); assert.deepStrictEqual( match( {parent: 'projects/te st/locations/location', test: 'value'}, - '/v3/{parent=projects/*/locations/*}/supportedLanguages' + '/v3/{parent=projects/*/locations/*}/supportedLanguages', ), { matchedFields: ['parent'], url: '/v3/projects/te%20st/locations/location/supportedLanguages', - } + }, ); assert.deepStrictEqual( match( {parent: 'projects/te st', test: 'value'}, - '/v3/{parent=projects/*}/{field=*}/supportedLanguages' + '/v3/{parent=projects/*}/{field=*}/supportedLanguages', ), - undefined + undefined, ); assert.deepStrictEqual( match( {parent: 'projects/te st', test: 'value', field: 42}, - '/v3/{parent=projects/*}/{field=*}/supportedLanguages' + '/v3/{parent=projects/*}/{field=*}/supportedLanguages', ), { matchedFields: ['field', 'parent'], url: '/v3/projects/te%20st/42/supportedLanguages', - } + }, ); assert.deepStrictEqual( match( @@ -473,23 +473,23 @@ describe('gRPC to HTTP transcoding', () => { field: 'fields/field42', path: 'a/b,c/d', }, - '/v3/{parent=projects/*}/{field=fields/*}/{path=**}/supportedLanguages' + '/v3/{parent=projects/*}/{field=fields/*}/{path=**}/supportedLanguages', ), { matchedFields: ['path', 'field', 'parent'], url: '/v3/projects/te%20st/fields/field42/a/b%2Cc/d/supportedLanguages', - } + }, ); assert.deepStrictEqual( match({}, '/v3/{field.subfield}/supportedLanguages'), - undefined + undefined, ); assert.deepStrictEqual( match({field: {subfield: 42}}, '/v3/{field.subfield}/supportedLanguages'), { matchedFields: ['field.subfield'], url: '/v3/42/supportedLanguages', - } + }, ); }); @@ -503,7 +503,7 @@ describe('gRPC to HTTP transcoding', () => { }; const copy = deepCopyWithoutMatchedFields( request as RequestType, - new Set() + new Set(), ); assert.deepStrictEqual(copy, request); request.field.subfield = 43; @@ -532,7 +532,7 @@ describe('gRPC to HTTP transcoding', () => { }; const copy = deepCopyWithoutMatchedFields( request as RequestType, - new Set(['field.subfield']) + new Set(['field.subfield']), ); assert.deepStrictEqual(copy, expected); }); @@ -543,7 +543,7 @@ describe('gRPC to HTTP transcoding', () => { ]); assert.deepStrictEqual( buildQueryStringComponents({field: 'value', a: 42}), - ['field=value', 'a=42'] + ['field=value', 'a=42'], ); assert.deepStrictEqual( buildQueryStringComponents({ @@ -558,7 +558,7 @@ describe('gRPC to HTTP transcoding', () => { 'repeated=z%20z%20z', 'obj.subfield=string', 'obj.y=z', - ] + ], ); }); }); @@ -615,7 +615,7 @@ describe('override the HTTP rules in protoJson', () => { assert.deepStrictEqual(httpOptions.get, rule.get); assert.deepStrictEqual( httpOptions.additional_bindings, - rule.additional_bindings + rule.additional_bindings, ); } } @@ -645,7 +645,7 @@ describe('override the HTTP rules in protoJson', () => { }; assert(originAdditionalBindings()); const expectedAditionalBindings = originAdditionalBindings()!.concat( - httpRules[0].additional_bindings + httpRules[0].additional_bindings, ); overrideHttpRules(httpRules, root); for (const rule of httpRules) { @@ -660,7 +660,7 @@ describe('override the HTTP rules in protoJson', () => { assert.deepStrictEqual(httpOptions.get, rule.get); assert.deepStrictEqual( httpOptions.additional_bindings, - expectedAditionalBindings + expectedAditionalBindings, ); } } diff --git a/gax/test/unit/util.ts b/gax/test/unit/util.ts index 614e1c06f..e9e882a36 100644 --- a/gax/test/unit/util.ts +++ b/gax/test/unit/util.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import {describe, it} from 'mocha'; import { toCamelCase as snakeToCamelCase, @@ -37,7 +37,7 @@ describe('util.ts', () => { assert.strictEqual(camelToSnakeCase('a.1B'), 'a.1_b'); assert.strictEqual( camelToSnakeCase('somethingABCDEValue`'), - 'something_a_b_c_d_e_value' + 'something_a_b_c_d_e_value', ); }); @@ -53,7 +53,7 @@ describe('util.ts', () => { assert.strictEqual(snakeToCamelCase('a.1_b'), 'a.1B'); assert.strictEqual( snakeToCamelCase('something_abcde_value'), - 'somethingAbcdeValue' + 'somethingAbcdeValue', ); }); @@ -69,15 +69,15 @@ describe('util.ts', () => { assert.strictEqual(toLowerCamelCase('a.1_b'), 'a.1B'); assert.strictEqual( toLowerCamelCase('something_abcde_value'), - 'somethingAbcdeValue' + 'somethingAbcdeValue', ); assert.strictEqual( toLowerCamelCase('PascalCaseString'), - 'pascalCaseString' + 'pascalCaseString', ); assert.strictEqual( toLowerCamelCase('PascalCASEString'), - 'pascalCaseString' + 'pascalCaseString', ); }); diff --git a/gax/test/unit/utils.ts b/gax/test/unit/utils.ts index 24f53d89f..664ec45f9 100644 --- a/gax/test/unit/utils.ts +++ b/gax/test/unit/utils.ts @@ -28,7 +28,7 @@ export function fail( argument: {}, metadata: {}, options: Options, - callback: Function + callback: Function, ) { const error = new GoogleError(); error.code = FAKE_STATUS_CODE_1; @@ -76,7 +76,7 @@ export function createApiCall(func: Function, opts?: Options) { }; }), settings, - descriptor + descriptor, ) as GaxCallPromise; } @@ -87,7 +87,7 @@ export function createRetryOptions( initialRpcTimeoutMillis?: number, rpcTimeoutMultiplier?: number, maxRpcTimeoutMillis?: number, - totalTimeoutMillis?: number + totalTimeoutMillis?: number, ) { const backoff = typeof backoffSettingsOrInitialRetryDelayMillis === 'number' @@ -98,7 +98,7 @@ export function createRetryOptions( initialRpcTimeoutMillis!, rpcTimeoutMultiplier!, maxRpcTimeoutMillis!, - totalTimeoutMillis! + totalTimeoutMillis!, ) : backoffSettingsOrInitialRetryDelayMillis; return gax.createRetryOptions([FAKE_STATUS_CODE_1], backoff); @@ -108,7 +108,7 @@ export function toProtobufJSON(protobufType: protobuf.Type, json: {}) { const message = serializer.fromProto3JSON(protobufType, json); if (!message) { throw new Error( - `Internal Error: fail to convert JSON to protobuf specific JSON, protobuf type: ${protobufType}` + `Internal Error: fail to convert JSON to protobuf specific JSON, protobuf type: ${protobufType}`, ); } return protobufType.toObject(message, defaultToObjectOptions); diff --git a/gax/test/unit/warning.ts b/gax/test/unit/warning.ts index 8453e8105..240523321 100644 --- a/gax/test/unit/warning.ts +++ b/gax/test/unit/warning.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import assert from 'assert'; import * as sinon from 'sinon'; import {describe, it} from 'mocha'; @@ -48,7 +48,7 @@ describe('warnings', () => { assert( stub.calledWith('messageD-1', { type: 'WarningType1', - }) + }), ); stub.restore(); done(); diff --git a/gax/tsconfig.json b/gax/tsconfig.json index 0921b23c8..d5cda5d87 100644 --- a/gax/tsconfig.json +++ b/gax/tsconfig.json @@ -5,7 +5,11 @@ "rootDir": ".", "outDir": "build", "noImplicitAny": true, - "resolveJsonModule": true + "resolveJsonModule": true, + "moduleResolution": "node16", + "esModuleInterop": true, + "module": "node16", + "skipLibCheck": true }, "include": [ "src/*.ts", @@ -15,5 +19,8 @@ "src/*/*.ts", "test/system-test/*.ts", "test/unit/*.ts", + "protos/**/*.json", + "src/*.json", + "test/fixtures/*.json" ] } diff --git a/gax/webpack.config.js b/gax/webpack.config.js index 03705217e..83bf18ce5 100644 --- a/gax/webpack.config.js +++ b/gax/webpack.config.js @@ -28,12 +28,12 @@ module.exports = { '../../package.json': path.resolve(__dirname, 'package.json'), '../../protos/operations.json': path.resolve( __dirname, - 'protos/operations.json' + 'protos/operations.json', ), '../../protos/status.json': path.resolve(__dirname, 'protos/status.json'), '../../protos/iam_service.json': path.resolve( __dirname, - 'protos/iam_service.json' + 'protos/iam_service.json', ), }, }, diff --git a/package-lock.json b/package-lock.json index e12807202..dcbf3b673 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,7 +7,7 @@ "name": "gax-nodejs", "license": "Apache-2.0", "engines": { - "node": ">=14" + "node": ">=18" } } } diff --git a/package.json b/package.json index e0003f91f..4717726b2 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "url": "https://github.com/googleapis/gax-nodejs/issues" }, "engines": { - "node": ">=14" + "node": ">=18" }, "homepage": "https://github.com/googleapis/gax-nodejs#readme" } diff --git a/tools/package.json b/tools/package.json index 2e175337e..ebc784307 100644 --- a/tools/package.json +++ b/tools/package.json @@ -28,14 +28,14 @@ "author": "Google API Authors", "license": "Apache-2.0", "dependencies": { - "@babel/core": "^7.22.5", - "@babel/traverse": "^7.22.5", - "google-gax": "^4.3.2", + "@babel/core": "^7.26.8", + "@babel/traverse": "^7.26.8", + "google-gax": "^4.4.1", "google-proto-files": "^4.2.0", - "protobufjs-cli": "1.1.3", - "uglify-js": "^3.17.0", - "walk-up-path": "^3.0.1", - "walkdir": "^0.4.0" + "protobufjs-cli": "^1.1.3", + "uglify-js": "^3.19.3", + "walk-up-path": "^3.0.0", + "walkdir": "^0.4.1" }, "repository": { "type": "git", @@ -43,21 +43,21 @@ "directory": "gapic-tools" }, "devDependencies": { - "@babel/cli": "^7.22.5", - "@babel/types": "^7.22.5", - "@types/babel__core": "^7.20.1", - "@types/babel__traverse": "^7.20.1", - "@types/mocha": "^9.0.0", - "@types/ncp": "^2.0.1", - "@types/uglify-js": "^3.17.0", - "c8": "^9.0.0", - "gts": "^5.0.0", - "mocha": "^9.0.0", + "@babel/cli": "^7.26.4", + "@babel/types": "^7.26.8", + "@types/babel__core": "^7.20.5", + "@types/babel__traverse": "^7.20.6", + "@types/mocha": "^10.0.10", + "@types/ncp": "^2.0.8", + "@types/uglify-js": "^3.17.5", + "c8": "^10.1.3", + "gts": "^6.0.2", + "mocha": "^11.1.0", "ncp": "^2.0.0", - "protobufjs": "7.4.0", - "typescript": "^5.1.6" + "protobufjs": "^7.4.0", + "typescript": "^5.7.3" }, "engines": { - "node": ">=14" + "node": ">=18" } } diff --git a/tools/src/compileProtos.ts b/tools/src/compileProtos.ts index 81c9981be..06e92890f 100644 --- a/tools/src/compileProtos.ts +++ b/tools/src/compileProtos.ts @@ -28,7 +28,7 @@ export const gaxProtos = path.join( require.resolve('google-gax'), '..', '..', - 'protos' + 'protos', ); const readdir = util.promisify(fs.readdir); const readFile = util.promisify(fs.readFile); @@ -95,7 +95,7 @@ function getAllEnums(dts: string): Set { let currentEnum = undefined; for (const line of lines) { const match = line.match( - /^\s*(?:export )?(namespace|class|interface|enum) (\w+) .*{/ + /^\s*(?:export )?(namespace|class|interface|enum) (\w+) .*{/, ); if (match) { const [, keyword, id] = match; @@ -144,7 +144,7 @@ function updateDtsTypes(dts: string, enums: Set): string { // enum: E => E|keyof typeof E to allow all string values replaced = replaced.replace( typeName, - `${typeName}|keyof typeof ${typeName}` + `${typeName}|keyof typeof ${typeName}`, ); } else if (typeName === 'Uint8Array') { // bytes: Uint8Array => Uint8Array|Buffer|string to allow base64-encoded strings @@ -170,14 +170,14 @@ function fixJsFile(js: string): string { // depend on protobufjs, so we re-export it from google-gax js = js.replace( 'import * as $protobuf from "protobufjs/minimal"', - 'import {protobufMinimal as $protobuf} from "google-gax/build/src/protobuf.js"' + 'import {protobufMinimal as $protobuf} from "google-gax/build/src/protobuf.js"', ); // 1. fix protobufjs require: we don't want the libraries to // depend on protobufjs, so we re-export it from google-gax js = js.replace( 'require("protobufjs/minimal")', - 'require("google-gax/build/src/protobuf").protobufMinimal' + 'require("google-gax/build/src/protobuf").protobufMinimal', ); // 2. add Apache license to the generated .js file @@ -192,7 +192,7 @@ function fixDtsFile(dts: string): string { // 1. fix for pbts output to make sure we import Long properly dts = dts.replace( 'import * as Long from "long";', - 'import Long = require("long");' + 'import Long = require("long");', ); if (!dts.match(/import Long = require/)) { dts = 'import Long = require("long");\n' + dts; @@ -202,7 +202,7 @@ function fixDtsFile(dts: string): string { // depend on protobufjs, so we re-export it from google-gax dts = dts.replace( 'import * as $protobuf from "protobufjs"', - 'import type {protobuf as $protobuf} from "google-gax"' + 'import type {protobuf as $protobuf} from "google-gax"', ); // 3. add Apache license to the generated .d.ts file @@ -223,7 +223,7 @@ function fixDtsFile(dts: string): string { */ async function buildListOfProtos( protoJsonFiles: string[], - esm?: boolean + esm?: boolean, ): Promise { const result: string[] = []; for (const file of protoJsonFiles) { @@ -233,7 +233,7 @@ async function buildListOfProtos( // If we're in ESM, we're going to be in a directory level below normal esm ? path.join(directory, '..', normalizePath(filePath)) - : path.join(directory, normalizePath(filePath)) + : path.join(directory, normalizePath(filePath)), ); result.push(...list); } @@ -259,7 +259,7 @@ interface CompileProtosOptions { async function compileProtos( rootName: string, protos: string[], - options: CompileProtosOptions + options: CompileProtosOptions, ): Promise { const extraArgs = []; if (options.keepCase) { @@ -439,16 +439,16 @@ export async function main(parameters: string[]): Promise { */ function usage() { console.log( - `Usage: node ${process.argv[1]} [--skip-json] [--esm] directory ...` + `Usage: node ${process.argv[1]} [--skip-json] [--esm] directory ...`, ); console.log( - `Finds all files matching ${PROTO_LIST_REGEX} in the given directories.` + `Finds all files matching ${PROTO_LIST_REGEX} in the given directories.`, ); console.log( - 'Each of those files should contain a JSON array of proto files used by the' + 'Each of those files should contain a JSON array of proto files used by the', ); console.log( - 'client library. Those proto files will be compiled to JSON using pbjs tool' + 'client library. Those proto files will be compiled to JSON using pbjs tool', ); console.log('from protobufjs.'); } @@ -460,5 +460,6 @@ if (require.main === module) { process.exit(1); } // argv[0] is node.js binary, argv[1] is script path + // eslint-disable-next-line @typescript-eslint/no-floating-promises main(process.argv.slice(2)); } diff --git a/tools/src/listProtos.ts b/tools/src/listProtos.ts index ae797919f..85d79fd8b 100644 --- a/tools/src/listProtos.ts +++ b/tools/src/listProtos.ts @@ -32,7 +32,7 @@ async function main(directory: string) { fs.writeFileSync( outputFile, - JSON.stringify(commonProtoFiles, null, 2) + '\n' + JSON.stringify(commonProtoFiles, null, 2) + '\n', ); } /** @@ -46,5 +46,6 @@ if (require.main === module) { if (process.argv.length < 3 || process.argv[2] === '--help') { usage(); } + // eslint-disable-next-line @typescript-eslint/no-floating-promises main(process.argv[2]); } diff --git a/tools/src/minify.ts b/tools/src/minify.ts index d12931314..08c71f51c 100644 --- a/tools/src/minify.ts +++ b/tools/src/minify.ts @@ -60,10 +60,10 @@ export async function main(directory?: string) { function usage() { console.log(`Usage: node ${process.argv[1]} [directory]`); console.log( - 'Minifies all JSON files in-place in the given directory (non-recursively).' + 'Minifies all JSON files in-place in the given directory (non-recursively).', ); console.log( - 'If no directory is given, minifies JSON files in ./build/protos.' + 'If no directory is given, minifies JSON files in ./build/protos.', ); } @@ -76,5 +76,6 @@ if (require.main === module) { process.exit(1); } + // eslint-disable-next-line @typescript-eslint/no-floating-promises main(process.argv[2]); } diff --git a/tools/src/prepublish.ts b/tools/src/prepublish.ts index 371a9b77e..4f1d750c8 100755 --- a/tools/src/prepublish.ts +++ b/tools/src/prepublish.ts @@ -70,6 +70,6 @@ if (require.main === module) { // eslint-disable-next-line n/no-process-exit process.exit(1); } - + // eslint-disable-next-line @typescript-eslint/no-floating-promises main(process.argv[2]); } diff --git a/tools/test/compileProtos.ts b/tools/test/compileProtos.ts index e5704e8c7..a30ccdcd5 100644 --- a/tools/test/compileProtos.ts +++ b/tools/test/compileProtos.ts @@ -93,12 +93,12 @@ describe('compileProtos tool', () => { assert(js.toString().includes('TestMessage')); assert(js.toString().includes('LibraryService')); assert( - js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( js .toString() - .includes('require("google-gax/build/src/protobuf").protobufMinimal') + .includes('require("google-gax/build/src/protobuf").protobufMinimal'), ); assert(!js.toString().includes('require("protobufjs/minimal")')); @@ -111,12 +111,12 @@ describe('compileProtos tool', () => { assert(ts.toString().includes('import Long = require')); assert(!ts.toString().includes('import * as Long')); assert( - ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( ts .toString() - .includes('import type {protobuf as $protobuf} from "google-gax"') + .includes('import type {protobuf as $protobuf} from "google-gax"'), ); assert(!ts.toString().includes('import * as $protobuf from "protobufjs"')); }); @@ -138,12 +138,12 @@ describe('compileProtos tool', () => { assert(cjs.toString().includes('TestMessage')); assert(cjs.toString().includes('LibraryService')); assert( - cjs.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + cjs.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( cjs .toString() - .includes('require("google-gax/build/src/protobuf").protobufMinimal') + .includes('require("google-gax/build/src/protobuf").protobufMinimal'), ); assert(!cjs.toString().includes('require("protobufjs/minimal")')); @@ -154,18 +154,20 @@ describe('compileProtos tool', () => { assert(js.toString().includes('TestMessage')); assert(js.toString().includes('LibraryService')); assert( - js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( js .toString() .includes( - 'import {protobufMinimal as $protobuf} from "google-gax/build/src/protobuf.js"' - ) + 'import {protobufMinimal as $protobuf} from "google-gax/build/src/protobuf.js"', + ), ); assert(!js.toString().includes('require("protobufjs/minimal")')); assert( - !js.toString().includes('import * as $protobuf from "protobufjs/minimal"') + !js + .toString() + .includes('import * as $protobuf from "protobufjs/minimal"'), ); // check that it uses proper root object; it's taken from fixtures/package.json @@ -177,12 +179,12 @@ describe('compileProtos tool', () => { assert(ts.toString().includes('import Long = require')); assert(!ts.toString().includes('import * as Long')); assert( - ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( ts .toString() - .includes('import type {protobuf as $protobuf} from "google-gax"') + .includes('import type {protobuf as $protobuf} from "google-gax"'), ); assert(!ts.toString().includes('import * as $protobuf from "protobufjs"')); }); @@ -198,12 +200,12 @@ describe('compileProtos tool', () => { assert(js.toString().includes('TestMessage')); assert(js.toString().includes('LibraryService')); assert( - js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + js.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( js .toString() - .includes('require("google-gax/build/src/protobuf").protobufMinimal') + .includes('require("google-gax/build/src/protobuf").protobufMinimal'), ); assert(!js.toString().includes('require("protobufjs/minimal")')); @@ -216,12 +218,12 @@ describe('compileProtos tool', () => { assert(ts.toString().includes('import Long = require')); assert(!ts.toString().includes('import * as Long')); assert( - ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert( ts .toString() - .includes('import type {protobuf as $protobuf} from "google-gax"') + .includes('import type {protobuf as $protobuf} from "google-gax"'), ); assert(!ts.toString().includes('import * as $protobuf from "protobufjs"')); }); @@ -239,43 +241,43 @@ describe('compileProtos tool', () => { assert(ts.toString().includes('import Long = require')); assert(!ts.toString().includes('import * as Long')); assert( - ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0') + ts.toString().includes('http://www.apache.org/licenses/LICENSE-2.0'), ); assert(ts.toString().includes('longField?: (number|Long|string|null);')); assert( - ts.toString().includes('bytesField?: (Uint8Array|Buffer|string|null);') + ts.toString().includes('bytesField?: (Uint8Array|Buffer|string|null);'), ); assert( ts .toString() .includes( - 'enumField?: (google.TestEnum|keyof typeof google.TestEnum|null);' - ) + 'enumField?: (google.TestEnum|keyof typeof google.TestEnum|null);', + ), ); assert( ts .toString() .includes( - '"case"?: (google.TestEnum|keyof typeof google.TestEnum|null);' - ) + '"case"?: (google.TestEnum|keyof typeof google.TestEnum|null);', + ), ); assert(ts.toString().includes('public longField: (number|Long|string);')); assert( - ts.toString().includes('public bytesField: (Uint8Array|Buffer|string);') + ts.toString().includes('public bytesField: (Uint8Array|Buffer|string);'), ); assert( ts .toString() .includes( - 'public enumField: (google.TestEnum|keyof typeof google.TestEnum);' - ) + 'public enumField: (google.TestEnum|keyof typeof google.TestEnum);', + ), ); assert( ts .toString() .includes( - 'public case: (google.TestEnum|keyof typeof google.TestEnum);' - ) + 'public case: (google.TestEnum|keyof typeof google.TestEnum);', + ), ); }); diff --git a/tools/test/replaceESMMockingLib.ts b/tools/test/replaceESMMockingLib.ts index 51aa7d565..cd41a46ec 100644 --- a/tools/test/replaceESMMockingLib.ts +++ b/tools/test/replaceESMMockingLib.ts @@ -101,7 +101,7 @@ describe('replace ESM mocking lib', () => { assert.strictEqual( result?.code?.replace(/(\r\n|\n|\r)/gm, '').replace(' ', ''), - expected + expected, ); });