diff --git a/packages/google-cloud-shell/.gitignore b/packages/google-cloud-shell/.gitignore index f73bce1a797..5d32b23782f 100644 --- a/packages/google-cloud-shell/.gitignore +++ b/packages/google-cloud-shell/.gitignore @@ -12,4 +12,3 @@ system-test/*key.json .DS_Store package-lock.json __pycache__ -owl-bot-staging \ No newline at end of file diff --git a/packages/google-cloud-shell/.jsdoc.js b/packages/google-cloud-shell/.jsdoc.js index 4db91f5d595..42d047c4975 100644 --- a/packages/google-cloud-shell/.jsdoc.js +++ b/packages/google-cloud-shell/.jsdoc.js @@ -1,4 +1,4 @@ -// Copyright 2021 Google LLC +// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ module.exports = { includePattern: '\\.js$' }, templates: { - copyright: 'Copyright 2021 Google LLC', + copyright: 'Copyright 2022 Google LLC', includeDate: false, sourceFiles: false, systemName: '@google-cloud/shell', @@ -52,4 +52,4 @@ module.exports = { markdown: { idInHeadings: true } -}; \ No newline at end of file +}; diff --git a/packages/google-cloud-shell/README.md b/packages/google-cloud-shell/README.md index 4a0eedffc5d..94722960de3 100644 --- a/packages/google-cloud-shell/README.md +++ b/packages/google-cloud-shell/README.md @@ -87,6 +87,11 @@ Samples are in the [`samples/`](https://github.com/googleapis/google-cloud-node/ | Sample | Source Code | Try it | | --------------------------- | --------------------------------- | ------ | +| Cloud_shell_service.add_public_key | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.add_public_key.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.add_public_key.js,samples/README.md) | +| Cloud_shell_service.authorize_environment | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.authorize_environment.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.authorize_environment.js,samples/README.md) | +| Cloud_shell_service.get_environment | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.get_environment.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.get_environment.js,samples/README.md) | +| Cloud_shell_service.remove_public_key | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.remove_public_key.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.remove_public_key.js,samples/README.md) | +| Cloud_shell_service.start_environment | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.start_environment.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.start_environment.js,samples/README.md) | | Quickstart | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/quickstart.js,samples/README.md) | | Quickstart | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/test/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/test/quickstart.js,samples/README.md) | diff --git a/packages/google-cloud-shell/linkinator.config.json b/packages/google-cloud-shell/linkinator.config.json index 4e8e9438f7a..befd23c8633 100644 --- a/packages/google-cloud-shell/linkinator.config.json +++ b/packages/google-cloud-shell/linkinator.config.json @@ -1,11 +1,16 @@ { "recurse": true, "skip": [ - "https://github.com/googleapis/nodejs-cloud-shell/blob/master/CHANGELOG.md", "https://codecov.io/gh/googleapis/", "www.googleapis.com", - "img.shields.io" + "img.shields.io", + "https://console.cloud.google.com/cloudshell", + "https://support.google.com" ], "silent": true, - "concurrency": 10 + "concurrency": 5, + "retry": true, + "retryErrors": true, + "retryErrorsCount": 5, + "retryErrorsJitter": 3000 } diff --git a/packages/google-cloud-shell/protos/google/cloud/shell/v1/cloudshell.proto b/packages/google-cloud-shell/protos/google/cloud/shell/v1/cloudshell.proto index f4b35b171cd..cee2cb1887d 100644 --- a/packages/google-cloud-shell/protos/google/cloud/shell/v1/cloudshell.proto +++ b/packages/google-cloud-shell/protos/google/cloud/shell/v1/cloudshell.proto @@ -1,4 +1,4 @@ -// Copyright 2021 Google LLC +// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ import "google/api/client.proto"; import "google/api/field_behavior.proto"; import "google/api/resource.proto"; import "google/longrunning/operations.proto"; -import "google/protobuf/field_mask.proto"; import "google/protobuf/timestamp.proto"; option go_package = "google.golang.org/genproto/googleapis/cloud/shell/v1;shell"; @@ -381,6 +380,10 @@ message CloudShellErrorDetails { // The user has exhausted their weekly Cloud Shell quota, and Cloud Shell // will be disabled until the quota resets. QUOTA_EXCEEDED = 5; + + // The Cloud Shell environment is unavailable and cannot be connected to at + // the moment. + ENVIRONMENT_UNAVAILABLE = 6; } // Code indicating the specific error the occurred. diff --git a/packages/google-cloud-shell/protos/protos.d.ts b/packages/google-cloud-shell/protos/protos.d.ts index 86906343e5e..8c0dd862c38 100644 --- a/packages/google-cloud-shell/protos/protos.d.ts +++ b/packages/google-cloud-shell/protos/protos.d.ts @@ -1884,7 +1884,8 @@ export namespace google { IMAGE_UNAVAILABLE = 1, CLOUD_SHELL_DISABLED = 2, TOS_VIOLATION = 4, - QUOTA_EXCEEDED = 5 + QUOTA_EXCEEDED = 5, + ENVIRONMENT_UNAVAILABLE = 6 } } } @@ -6165,103 +6166,6 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a FieldMask. */ - interface IFieldMask { - - /** FieldMask paths */ - paths?: (string[]|null); - } - - /** Represents a FieldMask. */ - class FieldMask implements IFieldMask { - - /** - * Constructs a new FieldMask. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFieldMask); - - /** FieldMask paths. */ - public paths: string[]; - - /** - * Creates a new FieldMask instance using the specified properties. - * @param [properties] Properties to set - * @returns FieldMask instance - */ - public static create(properties?: google.protobuf.IFieldMask): google.protobuf.FieldMask; - - /** - * Encodes the specified FieldMask message. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. - * @param message FieldMask message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IFieldMask, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified FieldMask message, length delimited. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. - * @param message FieldMask message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IFieldMask, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FieldMask message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns FieldMask - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldMask; - - /** - * Decodes a FieldMask message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns FieldMask - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldMask; - - /** - * Verifies a FieldMask message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldMask - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; - - /** - * Creates a plain object from a FieldMask message. Also converts values to other types if specified. - * @param message FieldMask - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FieldMask to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for FieldMask - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - /** Properties of a Timestamp. */ interface ITimestamp { diff --git a/packages/google-cloud-shell/protos/protos.js b/packages/google-cloud-shell/protos/protos.js index 82cac9e04c4..28d38a81fbd 100644 --- a/packages/google-cloud-shell/protos/protos.js +++ b/packages/google-cloud-shell/protos/protos.js @@ -3960,6 +3960,7 @@ case 2: case 4: case 5: + case 6: break; } return null; @@ -4004,6 +4005,10 @@ case 5: message.code = 5; break; + case "ENVIRONMENT_UNAVAILABLE": + case 6: + message.code = 6; + break; } return message; }; @@ -4063,6 +4068,7 @@ * @property {number} CLOUD_SHELL_DISABLED=2 CLOUD_SHELL_DISABLED value * @property {number} TOS_VIOLATION=4 TOS_VIOLATION value * @property {number} QUOTA_EXCEEDED=5 QUOTA_EXCEEDED value + * @property {number} ENVIRONMENT_UNAVAILABLE=6 ENVIRONMENT_UNAVAILABLE value */ CloudShellErrorDetails.CloudShellErrorCode = (function() { var valuesById = {}, values = Object.create(valuesById); @@ -4071,6 +4077,7 @@ values[valuesById[2] = "CLOUD_SHELL_DISABLED"] = 2; values[valuesById[4] = "TOS_VIOLATION"] = 4; values[valuesById[5] = "QUOTA_EXCEEDED"] = 5; + values[valuesById[6] = "ENVIRONMENT_UNAVAILABLE"] = 6; return values; })(); @@ -15832,225 +15839,6 @@ return Empty; })(); - protobuf.FieldMask = (function() { - - /** - * Properties of a FieldMask. - * @memberof google.protobuf - * @interface IFieldMask - * @property {Array.|null} [paths] FieldMask paths - */ - - /** - * Constructs a new FieldMask. - * @memberof google.protobuf - * @classdesc Represents a FieldMask. - * @implements IFieldMask - * @constructor - * @param {google.protobuf.IFieldMask=} [properties] Properties to set - */ - function FieldMask(properties) { - this.paths = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FieldMask paths. - * @member {Array.} paths - * @memberof google.protobuf.FieldMask - * @instance - */ - FieldMask.prototype.paths = $util.emptyArray; - - /** - * Creates a new FieldMask instance using the specified properties. - * @function create - * @memberof google.protobuf.FieldMask - * @static - * @param {google.protobuf.IFieldMask=} [properties] Properties to set - * @returns {google.protobuf.FieldMask} FieldMask instance - */ - FieldMask.create = function create(properties) { - return new FieldMask(properties); - }; - - /** - * Encodes the specified FieldMask message. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. - * @function encode - * @memberof google.protobuf.FieldMask - * @static - * @param {google.protobuf.IFieldMask} message FieldMask message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldMask.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.paths != null && message.paths.length) - for (var i = 0; i < message.paths.length; ++i) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.paths[i]); - return writer; - }; - - /** - * Encodes the specified FieldMask message, length delimited. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.FieldMask - * @static - * @param {google.protobuf.IFieldMask} message FieldMask message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldMask.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a FieldMask message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.FieldMask - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.FieldMask} FieldMask - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldMask.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldMask(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - if (!(message.paths && message.paths.length)) - message.paths = []; - message.paths.push(reader.string()); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a FieldMask message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.FieldMask - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.FieldMask} FieldMask - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldMask.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a FieldMask message. - * @function verify - * @memberof google.protobuf.FieldMask - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - FieldMask.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.paths != null && message.hasOwnProperty("paths")) { - if (!Array.isArray(message.paths)) - return "paths: array expected"; - for (var i = 0; i < message.paths.length; ++i) - if (!$util.isString(message.paths[i])) - return "paths: string[] expected"; - } - return null; - }; - - /** - * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FieldMask - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FieldMask} FieldMask - */ - FieldMask.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FieldMask) - return object; - var message = new $root.google.protobuf.FieldMask(); - if (object.paths) { - if (!Array.isArray(object.paths)) - throw TypeError(".google.protobuf.FieldMask.paths: array expected"); - message.paths = []; - for (var i = 0; i < object.paths.length; ++i) - message.paths[i] = String(object.paths[i]); - } - return message; - }; - - /** - * Creates a plain object from a FieldMask message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FieldMask - * @static - * @param {google.protobuf.FieldMask} message FieldMask - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldMask.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.paths = []; - if (message.paths && message.paths.length) { - object.paths = []; - for (var j = 0; j < message.paths.length; ++j) - object.paths[j] = message.paths[j]; - } - return object; - }; - - /** - * Converts this FieldMask to JSON. - * @function toJSON - * @memberof google.protobuf.FieldMask - * @instance - * @returns {Object.} JSON object - */ - FieldMask.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for FieldMask - * @function getTypeUrl - * @memberof google.protobuf.FieldMask - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FieldMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.FieldMask"; - }; - - return FieldMask; - })(); - protobuf.Timestamp = (function() { /** diff --git a/packages/google-cloud-shell/protos/protos.json b/packages/google-cloud-shell/protos/protos.json index e614cad6cc9..87a7043854b 100644 --- a/packages/google-cloud-shell/protos/protos.json +++ b/packages/google-cloud-shell/protos/protos.json @@ -362,7 +362,8 @@ "IMAGE_UNAVAILABLE": 1, "CLOUD_SHELL_DISABLED": 2, "TOS_VIOLATION": 4, - "QUOTA_EXCEEDED": 5 + "QUOTA_EXCEEDED": 5, + "ENVIRONMENT_UNAVAILABLE": 6 } } } @@ -1541,15 +1542,6 @@ "Empty": { "fields": {} }, - "FieldMask": { - "fields": { - "paths": { - "rule": "repeated", - "type": "string", - "id": 1 - } - } - }, "Timestamp": { "fields": { "seconds": { diff --git a/packages/google-cloud-shell/samples/README.md b/packages/google-cloud-shell/samples/README.md index 6faeb3cff52..c352e90f9f6 100644 --- a/packages/google-cloud-shell/samples/README.md +++ b/packages/google-cloud-shell/samples/README.md @@ -12,6 +12,11 @@ * [Before you begin](#before-you-begin) * [Samples](#samples) + * [Cloud_shell_service.add_public_key](#cloud_shell_service.add_public_key) + * [Cloud_shell_service.authorize_environment](#cloud_shell_service.authorize_environment) + * [Cloud_shell_service.get_environment](#cloud_shell_service.get_environment) + * [Cloud_shell_service.remove_public_key](#cloud_shell_service.remove_public_key) + * [Cloud_shell_service.start_environment](#cloud_shell_service.start_environment) * [Quickstart](#quickstart) * [Quickstart](#quickstart) @@ -30,6 +35,91 @@ Before running the samples, make sure you've followed the steps outlined in +### Cloud_shell_service.add_public_key + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.add_public_key.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.add_public_key.js,samples/README.md) + +__Usage:__ + + +`node packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.add_public_key.js` + + +----- + + + + +### Cloud_shell_service.authorize_environment + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.authorize_environment.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.authorize_environment.js,samples/README.md) + +__Usage:__ + + +`node packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.authorize_environment.js` + + +----- + + + + +### Cloud_shell_service.get_environment + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.get_environment.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.get_environment.js,samples/README.md) + +__Usage:__ + + +`node packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.get_environment.js` + + +----- + + + + +### Cloud_shell_service.remove_public_key + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.remove_public_key.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.remove_public_key.js,samples/README.md) + +__Usage:__ + + +`node packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.remove_public_key.js` + + +----- + + + + +### Cloud_shell_service.start_environment + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.start_environment.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.start_environment.js,samples/README.md) + +__Usage:__ + + +`node packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.start_environment.js` + + +----- + + + + ### Quickstart View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-shell/samples/quickstart.js). diff --git a/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.add_public_key.js b/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.add_public_key.js new file mode 100644 index 00000000000..4e60a338568 --- /dev/null +++ b/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.add_public_key.js @@ -0,0 +1,71 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main() { + // [START cloudshell_v1_generated_CloudShellService_AddPublicKey_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Environment this key should be added to, e.g. + * `users/me/environments/default`. + */ + // const environment = 'abc123' + /** + * Key that should be added to the environment. Supported formats are + * `ssh-dss` (see RFC4253), `ssh-rsa` (see RFC4253), `ecdsa-sha2-nistp256` + * (see RFC5656), `ecdsa-sha2-nistp384` (see RFC5656) and + * `ecdsa-sha2-nistp521` (see RFC5656). It should be structured as + * <format> <content>, where <content> part is encoded with + * Base64. + */ + // const key = 'abc123' + + // Imports the Shell library + const {CloudShellServiceClient} = require('@google-cloud/shell').v1; + + // Instantiates a client + const shellClient = new CloudShellServiceClient(); + + async function callAddPublicKey() { + // Construct request + const request = { + }; + + // Run request + const [operation] = await shellClient.addPublicKey(request); + const [response] = await operation.promise(); + console.log(response); + } + + callAddPublicKey(); + // [END cloudshell_v1_generated_CloudShellService_AddPublicKey_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.authorize_environment.js b/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.authorize_environment.js new file mode 100644 index 00000000000..8bd72e92cfe --- /dev/null +++ b/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.authorize_environment.js @@ -0,0 +1,76 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main() { + // [START cloudshell_v1_generated_CloudShellService_AuthorizeEnvironment_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Name of the resource that should receive the credentials, for example + * `users/me/environments/default` or + * `users/someone@example.com/environments/default`. + */ + // const name = 'abc123' + /** + * The OAuth access token that should be sent to the environment. + */ + // const accessToken = 'abc123' + /** + * The OAuth ID token that should be sent to the environment. + */ + // const idToken = 'abc123' + /** + * The time when the credentials expire. If not set, defaults to one hour from + * when the server received the request. + */ + // const expireTime = {} + + // Imports the Shell library + const {CloudShellServiceClient} = require('@google-cloud/shell').v1; + + // Instantiates a client + const shellClient = new CloudShellServiceClient(); + + async function callAuthorizeEnvironment() { + // Construct request + const request = { + }; + + // Run request + const [operation] = await shellClient.authorizeEnvironment(request); + const [response] = await operation.promise(); + console.log(response); + } + + callAuthorizeEnvironment(); + // [END cloudshell_v1_generated_CloudShellService_AuthorizeEnvironment_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.get_environment.js b/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.get_environment.js new file mode 100644 index 00000000000..c730a1020a0 --- /dev/null +++ b/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.get_environment.js @@ -0,0 +1,62 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(name) { + // [START cloudshell_v1_generated_CloudShellService_GetEnvironment_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. Name of the requested resource, for example `users/me/environments/default` + * or `users/someone@example.com/environments/default`. + */ + // const name = 'abc123' + + // Imports the Shell library + const {CloudShellServiceClient} = require('@google-cloud/shell').v1; + + // Instantiates a client + const shellClient = new CloudShellServiceClient(); + + async function callGetEnvironment() { + // Construct request + const request = { + name, + }; + + // Run request + const response = await shellClient.getEnvironment(request); + console.log(response); + } + + callGetEnvironment(); + // [END cloudshell_v1_generated_CloudShellService_GetEnvironment_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.remove_public_key.js b/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.remove_public_key.js new file mode 100644 index 00000000000..1806a372bc7 --- /dev/null +++ b/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.remove_public_key.js @@ -0,0 +1,66 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main() { + // [START cloudshell_v1_generated_CloudShellService_RemovePublicKey_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Environment this key should be removed from, e.g. + * `users/me/environments/default`. + */ + // const environment = 'abc123' + /** + * Key that should be removed from the environment. + */ + // const key = 'abc123' + + // Imports the Shell library + const {CloudShellServiceClient} = require('@google-cloud/shell').v1; + + // Instantiates a client + const shellClient = new CloudShellServiceClient(); + + async function callRemovePublicKey() { + // Construct request + const request = { + }; + + // Run request + const [operation] = await shellClient.removePublicKey(request); + const [response] = await operation.promise(); + console.log(response); + } + + callRemovePublicKey(); + // [END cloudshell_v1_generated_CloudShellService_RemovePublicKey_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.start_environment.js b/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.start_environment.js new file mode 100644 index 00000000000..fccae558254 --- /dev/null +++ b/packages/google-cloud-shell/samples/generated/v1/cloud_shell_service.start_environment.js @@ -0,0 +1,74 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main() { + // [START cloudshell_v1_generated_CloudShellService_StartEnvironment_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Name of the resource that should be started, for example + * `users/me/environments/default` or + * `users/someone@example.com/environments/default`. + */ + // const name = 'abc123' + /** + * The initial access token passed to the environment. If this is present and + * valid, the environment will be pre-authenticated with gcloud so that the + * user can run gcloud commands in Cloud Shell without having to log in. This + * code can be updated later by calling AuthorizeEnvironment. + */ + // const accessToken = 'abc123' + /** + * Public keys that should be added to the environment before it is started. + */ + // const publicKeys = 'abc123' + + // Imports the Shell library + const {CloudShellServiceClient} = require('@google-cloud/shell').v1; + + // Instantiates a client + const shellClient = new CloudShellServiceClient(); + + async function callStartEnvironment() { + // Construct request + const request = { + }; + + // Run request + const [operation] = await shellClient.startEnvironment(request); + const [response] = await operation.promise(); + console.log(response); + } + + callStartEnvironment(); + // [END cloudshell_v1_generated_CloudShellService_StartEnvironment_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-shell/samples/generated/v1/snippet_metadata.google.cloud.shell.v1.json b/packages/google-cloud-shell/samples/generated/v1/snippet_metadata.google.cloud.shell.v1.json new file mode 100644 index 00000000000..41005e0faca --- /dev/null +++ b/packages/google-cloud-shell/samples/generated/v1/snippet_metadata.google.cloud.shell.v1.json @@ -0,0 +1,243 @@ +{ + "clientLibrary": { + "name": "nodejs-shell", + "version": "2.0.4", + "language": "TYPESCRIPT", + "apis": [ + { + "id": "google.cloud.shell.v1", + "version": "v1" + } + ] + }, + "snippets": [ + { + "regionTag": "cloudshell_v1_generated_CloudShellService_GetEnvironment_async", + "title": "CloudShellService getEnvironment Sample", + "origin": "API_DEFINITION", + "description": " Gets an environment. Returns NOT_FOUND if the environment does not exist.", + "canonical": true, + "file": "cloud_shell_service.get_environment.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 54, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetEnvironment", + "fullName": "google.cloud.shell.v1.CloudShellService.GetEnvironment", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.shell.v1.Environment", + "client": { + "shortName": "CloudShellServiceClient", + "fullName": "google.cloud.shell.v1.CloudShellServiceClient" + }, + "method": { + "shortName": "GetEnvironment", + "fullName": "google.cloud.shell.v1.CloudShellService.GetEnvironment", + "service": { + "shortName": "CloudShellService", + "fullName": "google.cloud.shell.v1.CloudShellService" + } + } + } + }, + { + "regionTag": "cloudshell_v1_generated_CloudShellService_StartEnvironment_async", + "title": "CloudShellService startEnvironment Sample", + "origin": "API_DEFINITION", + "description": " Starts an existing environment, allowing clients to connect to it. The returned operation will contain an instance of StartEnvironmentMetadata in its metadata field. Users can wait for the environment to start by polling this operation via GetOperation. Once the environment has finished starting and is ready to accept connections, the operation will contain a StartEnvironmentResponse in its response field.", + "canonical": true, + "file": "cloud_shell_service.start_environment.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 66, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "StartEnvironment", + "fullName": "google.cloud.shell.v1.CloudShellService.StartEnvironment", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "access_token", + "type": "TYPE_STRING" + }, + { + "name": "public_keys", + "type": "TYPE_STRING[]" + } + ], + "resultType": ".google.longrunning.Operation", + "client": { + "shortName": "CloudShellServiceClient", + "fullName": "google.cloud.shell.v1.CloudShellServiceClient" + }, + "method": { + "shortName": "StartEnvironment", + "fullName": "google.cloud.shell.v1.CloudShellService.StartEnvironment", + "service": { + "shortName": "CloudShellService", + "fullName": "google.cloud.shell.v1.CloudShellService" + } + } + } + }, + { + "regionTag": "cloudshell_v1_generated_CloudShellService_AuthorizeEnvironment_async", + "title": "CloudShellService authorizeEnvironment Sample", + "origin": "API_DEFINITION", + "description": " Sends OAuth credentials to a running environment on behalf of a user. When this completes, the environment will be authorized to run various Google Cloud command line tools without requiring the user to manually authenticate.", + "canonical": true, + "file": "cloud_shell_service.authorize_environment.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 68, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "AuthorizeEnvironment", + "fullName": "google.cloud.shell.v1.CloudShellService.AuthorizeEnvironment", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "access_token", + "type": "TYPE_STRING" + }, + { + "name": "id_token", + "type": "TYPE_STRING" + }, + { + "name": "expire_time", + "type": ".google.protobuf.Timestamp" + } + ], + "resultType": ".google.longrunning.Operation", + "client": { + "shortName": "CloudShellServiceClient", + "fullName": "google.cloud.shell.v1.CloudShellServiceClient" + }, + "method": { + "shortName": "AuthorizeEnvironment", + "fullName": "google.cloud.shell.v1.CloudShellService.AuthorizeEnvironment", + "service": { + "shortName": "CloudShellService", + "fullName": "google.cloud.shell.v1.CloudShellService" + } + } + } + }, + { + "regionTag": "cloudshell_v1_generated_CloudShellService_AddPublicKey_async", + "title": "CloudShellService addPublicKey Sample", + "origin": "API_DEFINITION", + "description": " Adds a public SSH key to an environment, allowing clients with the corresponding private key to connect to that environment via SSH. If a key with the same content already exists, this will error with ALREADY_EXISTS.", + "canonical": true, + "file": "cloud_shell_service.add_public_key.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 63, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "AddPublicKey", + "fullName": "google.cloud.shell.v1.CloudShellService.AddPublicKey", + "async": true, + "parameters": [ + { + "name": "environment", + "type": "TYPE_STRING" + }, + { + "name": "key", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.longrunning.Operation", + "client": { + "shortName": "CloudShellServiceClient", + "fullName": "google.cloud.shell.v1.CloudShellServiceClient" + }, + "method": { + "shortName": "AddPublicKey", + "fullName": "google.cloud.shell.v1.CloudShellService.AddPublicKey", + "service": { + "shortName": "CloudShellService", + "fullName": "google.cloud.shell.v1.CloudShellService" + } + } + } + }, + { + "regionTag": "cloudshell_v1_generated_CloudShellService_RemovePublicKey_async", + "title": "CloudShellService removePublicKey Sample", + "origin": "API_DEFINITION", + "description": " Removes a public SSH key from an environment. Clients will no longer be able to connect to the environment using the corresponding private key. If a key with the same content is not present, this will error with NOT_FOUND.", + "canonical": true, + "file": "cloud_shell_service.remove_public_key.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 58, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "RemovePublicKey", + "fullName": "google.cloud.shell.v1.CloudShellService.RemovePublicKey", + "async": true, + "parameters": [ + { + "name": "environment", + "type": "TYPE_STRING" + }, + { + "name": "key", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.longrunning.Operation", + "client": { + "shortName": "CloudShellServiceClient", + "fullName": "google.cloud.shell.v1.CloudShellServiceClient" + }, + "method": { + "shortName": "RemovePublicKey", + "fullName": "google.cloud.shell.v1.CloudShellService.RemovePublicKey", + "service": { + "shortName": "CloudShellService", + "fullName": "google.cloud.shell.v1.CloudShellService" + } + } + } + } + ] +} \ No newline at end of file diff --git a/packages/google-cloud-shell/src/v1/cloud_shell_service_client.ts b/packages/google-cloud-shell/src/v1/cloud_shell_service_client.ts index 74d4a4b80ab..0ae65c95113 100644 --- a/packages/google-cloud-shell/src/v1/cloud_shell_service_client.ts +++ b/packages/google-cloud-shell/src/v1/cloud_shell_service_client.ts @@ -1,4 +1,4 @@ -// Copyright 2021 Google LLC +// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,12 +17,13 @@ // ** All changes to this file may be overwritten. ** /* global window */ -import * as gax from 'google-gax'; -import { +import type * as gax from 'google-gax'; +import type { Callback, CallOptions, Descriptors, ClientOptions, + GrpcClientOptions, LROperation, } from 'google-gax'; @@ -34,7 +35,6 @@ import jsonProtos = require('../../protos/protos.json'); * This file defines retry strategy and timeouts for all API methods in this library. */ import * as gapicConfig from './cloud_shell_service_client_config.json'; -import {operationsProtos} from 'google-gax'; const version = require('../../../package.json').version; /** @@ -51,6 +51,7 @@ const version = require('../../../package.json').version; export class CloudShellServiceClient { private _terminated = false; private _opts: ClientOptions; + private _providedCustomServicePath: boolean; private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; @@ -62,6 +63,7 @@ export class CloudShellServiceClient { longrunning: {}, batching: {}, }; + warn: (code: string, message: string, warnType?: string) => void; innerApiCalls: {[name: string]: Function}; pathTemplates: {[name: string]: gax.PathTemplate}; operationsClient: gax.OperationsClient; @@ -72,7 +74,7 @@ export class CloudShellServiceClient { * * @param {object} [options] - The configuration object. * The options accepted by the constructor are described in detail - * in [this document](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#creating-the-client-instance). + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). * The common options are: * @param {object} [options.credentials] - Credentials object. * @param {string} [options.credentials.client_email] @@ -95,17 +97,29 @@ export class CloudShellServiceClient { * API remote host. * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. * Follows the structure of {@link gapicConfig}. - * @param {boolean} [options.fallback] - Use HTTP fallback mode. - * In fallback mode, a special browser-compatible transport implementation is used - * instead of gRPC transport. In browser context (if the `window` object is defined) - * the fallback mode is enabled automatically; set `options.fallback` to `false` - * if you need to override this behavior. + * @param {boolean | "rest"} [options.fallback] - Use HTTP fallback mode. + * Pass "rest" to use HTTP/1.1 REST API instead of gRPC. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new CloudShellServiceClient({fallback: 'rest'}, gax); + * ``` */ - constructor(opts?: ClientOptions) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof CloudShellServiceClient; const servicePath = opts?.servicePath || opts?.apiEndpoint || staticMembers.servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; const fallback = @@ -113,13 +127,21 @@ export class CloudShellServiceClient { (typeof window !== 'undefined' && typeof window?.fetch === 'function'); opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + // Request numeric enum values if REST transport is used. + opts.numericEnums = true; + // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== staticMembers.servicePath && !('scopes' in opts)) { opts['scopes'] = staticMembers.scopes; } + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + // Choose either gRPC or proto-over-HTTP implementation of google-gax. - this._gaxModule = opts.fallback ? gax.fallback : gax; + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. this._gaxGrpc = new this._gaxModule.GrpcClient(opts); @@ -130,6 +152,12 @@ export class CloudShellServiceClient { // Save the auth object to the client, for use by other methods. this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = staticMembers.servicePath; + // Set the default scopes in auth client if needed. if (servicePath === staticMembers.servicePath) { this.auth.defaultScopes = staticMembers.scopes; @@ -163,16 +191,19 @@ export class CloudShellServiceClient { }; const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos); - // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. - + const lroOptions: GrpcClientOptions = { + auth: this.auth, + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, + }; + if (opts.fallback === 'rest') { + lroOptions.protoJson = protoFilesRoot; + lroOptions.httpRules = []; + } this.operationsClient = this._gaxModule - .lro({ - auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, - }) + .lro(lroOptions) .operationsClient(opts); const startEnvironmentResponse = protoFilesRoot.lookup( '.google.cloud.shell.v1.StartEnvironmentResponse' @@ -234,6 +265,9 @@ export class CloudShellServiceClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; } /** @@ -262,7 +296,8 @@ export class CloudShellServiceClient { ) : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.shell.v1.CloudShellService, - this._opts + this._opts, + this._providedCustomServicePath ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides @@ -293,7 +328,8 @@ export class CloudShellServiceClient { const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], - descriptor + descriptor, + this._opts.fallback ); this.innerApiCalls[methodName] = apiCall; @@ -355,8 +391,26 @@ export class CloudShellServiceClient { // ------------------- // -- Service calls -- // ------------------- + /** + * Gets an environment. Returns NOT_FOUND if the environment does not exist. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the requested resource, for example `users/me/environments/default` + * or `users/someone@example.com/environments/default`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing [Environment]{@link google.cloud.shell.v1.Environment}. + * Please see the + * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * for more details and examples. + * @example include:samples/generated/v1/cloud_shell_service.get_environment.js + * region_tag:cloudshell_v1_generated_CloudShellService_GetEnvironment_async + */ getEnvironment( - request: protos.google.cloud.shell.v1.IGetEnvironmentRequest, + request?: protos.google.cloud.shell.v1.IGetEnvironmentRequest, options?: CallOptions ): Promise< [ @@ -382,26 +436,8 @@ export class CloudShellServiceClient { {} | null | undefined > ): void; - /** - * Gets an environment. Returns NOT_FOUND if the environment does not exist. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Name of the requested resource, for example `users/me/environments/default` - * or `users/someone@example.com/environments/default`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Environment]{@link google.cloud.shell.v1.Environment}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) - * for more details and examples. - * @example - * const [response] = await client.getEnvironment(request); - */ getEnvironment( - request: protos.google.cloud.shell.v1.IGetEnvironmentRequest, + request?: protos.google.cloud.shell.v1.IGetEnvironmentRequest, optionsOrCallback?: | CallOptions | Callback< @@ -435,15 +471,48 @@ export class CloudShellServiceClient { options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = - gax.routingHeader.fromParams({ - name: request.name || '', + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', }); this.initialize(); return this.innerApiCalls.getEnvironment(request, options, callback); } + /** + * Starts an existing environment, allowing clients to connect to it. The + * returned operation will contain an instance of StartEnvironmentMetadata in + * its metadata field. Users can wait for the environment to start by polling + * this operation via GetOperation. Once the environment has finished starting + * and is ready to accept connections, the operation will contain a + * StartEnvironmentResponse in its response field. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Name of the resource that should be started, for example + * `users/me/environments/default` or + * `users/someone@example.com/environments/default`. + * @param {string} request.accessToken + * The initial access token passed to the environment. If this is present and + * valid, the environment will be pre-authenticated with gcloud so that the + * user can run gcloud commands in Cloud Shell without having to log in. This + * code can be updated later by calling AuthorizeEnvironment. + * @param {string[]} request.publicKeys + * Public keys that should be added to the environment before it is started. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the + * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * for more details and examples. + * @example include:samples/generated/v1/cloud_shell_service.start_environment.js + * region_tag:cloudshell_v1_generated_CloudShellService_StartEnvironment_async + */ startEnvironment( - request: protos.google.cloud.shell.v1.IStartEnvironmentRequest, + request?: protos.google.cloud.shell.v1.IStartEnvironmentRequest, options?: CallOptions ): Promise< [ @@ -478,42 +547,8 @@ export class CloudShellServiceClient { {} | null | undefined > ): void; - /** - * Starts an existing environment, allowing clients to connect to it. The - * returned operation will contain an instance of StartEnvironmentMetadata in - * its metadata field. Users can wait for the environment to start by polling - * this operation via GetOperation. Once the environment has finished starting - * and is ready to accept connections, the operation will contain a - * StartEnvironmentResponse in its response field. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Name of the resource that should be started, for example - * `users/me/environments/default` or - * `users/someone@example.com/environments/default`. - * @param {string} request.accessToken - * The initial access token passed to the environment. If this is present and - * valid, the environment will be pre-authenticated with gcloud so that the - * user can run gcloud commands in Cloud Shell without having to log in. This - * code can be updated later by calling AuthorizeEnvironment. - * @param {string[]} request.publicKeys - * Public keys that should be added to the environment before it is started. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) - * for more details and examples. - * @example - * const [operation] = await client.startEnvironment(request); - * const [response] = await operation.promise(); - */ startEnvironment( - request: protos.google.cloud.shell.v1.IStartEnvironmentRequest, + request?: protos.google.cloud.shell.v1.IStartEnvironmentRequest, optionsOrCallback?: | CallOptions | Callback< @@ -554,8 +589,8 @@ export class CloudShellServiceClient { options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = - gax.routingHeader.fromParams({ - name: request.name || '', + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', }); this.initialize(); return this.innerApiCalls.startEnvironment(request, options, callback); @@ -569,11 +604,8 @@ export class CloudShellServiceClient { * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) * for more details and examples. - * @example - * const decodedOperation = await checkStartEnvironmentProgress(name); - * console.log(decodedOperation.result); - * console.log(decodedOperation.done); - * console.log(decodedOperation.metadata); + * @example include:samples/generated/v1/cloud_shell_service.start_environment.js + * region_tag:cloudshell_v1_generated_CloudShellService_StartEnvironment_async */ async checkStartEnvironmentProgress( name: string @@ -583,22 +615,54 @@ export class CloudShellServiceClient { protos.google.cloud.shell.v1.StartEnvironmentMetadata > > { - const request = new operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new gax.Operation( + const decodeOperation = new this._gaxModule.Operation( operation, this.descriptors.longrunning.startEnvironment, - gax.createDefaultBackoffSettings() + this._gaxModule.createDefaultBackoffSettings() ); return decodeOperation as LROperation< protos.google.cloud.shell.v1.StartEnvironmentResponse, protos.google.cloud.shell.v1.StartEnvironmentMetadata >; } + /** + * Sends OAuth credentials to a running environment on behalf of a user. When + * this completes, the environment will be authorized to run various Google + * Cloud command line tools without requiring the user to manually + * authenticate. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Name of the resource that should receive the credentials, for example + * `users/me/environments/default` or + * `users/someone@example.com/environments/default`. + * @param {string} request.accessToken + * The OAuth access token that should be sent to the environment. + * @param {string} request.idToken + * The OAuth ID token that should be sent to the environment. + * @param {google.protobuf.Timestamp} request.expireTime + * The time when the credentials expire. If not set, defaults to one hour from + * when the server received the request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the + * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * for more details and examples. + * @example include:samples/generated/v1/cloud_shell_service.authorize_environment.js + * region_tag:cloudshell_v1_generated_CloudShellService_AuthorizeEnvironment_async + */ authorizeEnvironment( - request: protos.google.cloud.shell.v1.IAuthorizeEnvironmentRequest, + request?: protos.google.cloud.shell.v1.IAuthorizeEnvironmentRequest, options?: CallOptions ): Promise< [ @@ -633,40 +697,8 @@ export class CloudShellServiceClient { {} | null | undefined > ): void; - /** - * Sends OAuth credentials to a running environment on behalf of a user. When - * this completes, the environment will be authorized to run various Google - * Cloud command line tools without requiring the user to manually - * authenticate. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Name of the resource that should receive the credentials, for example - * `users/me/environments/default` or - * `users/someone@example.com/environments/default`. - * @param {string} request.accessToken - * The OAuth access token that should be sent to the environment. - * @param {string} request.idToken - * The OAuth ID token that should be sent to the environment. - * @param {google.protobuf.Timestamp} request.expireTime - * The time when the credentials expire. If not set, defaults to one hour from - * when the server received the request. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) - * for more details and examples. - * @example - * const [operation] = await client.authorizeEnvironment(request); - * const [response] = await operation.promise(); - */ authorizeEnvironment( - request: protos.google.cloud.shell.v1.IAuthorizeEnvironmentRequest, + request?: protos.google.cloud.shell.v1.IAuthorizeEnvironmentRequest, optionsOrCallback?: | CallOptions | Callback< @@ -707,8 +739,8 @@ export class CloudShellServiceClient { options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = - gax.routingHeader.fromParams({ - name: request.name || '', + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', }); this.initialize(); return this.innerApiCalls.authorizeEnvironment(request, options, callback); @@ -722,11 +754,8 @@ export class CloudShellServiceClient { * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) * for more details and examples. - * @example - * const decodedOperation = await checkAuthorizeEnvironmentProgress(name); - * console.log(decodedOperation.result); - * console.log(decodedOperation.done); - * console.log(decodedOperation.metadata); + * @example include:samples/generated/v1/cloud_shell_service.authorize_environment.js + * region_tag:cloudshell_v1_generated_CloudShellService_AuthorizeEnvironment_async */ async checkAuthorizeEnvironmentProgress( name: string @@ -736,22 +765,52 @@ export class CloudShellServiceClient { protos.google.cloud.shell.v1.AuthorizeEnvironmentMetadata > > { - const request = new operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new gax.Operation( + const decodeOperation = new this._gaxModule.Operation( operation, this.descriptors.longrunning.authorizeEnvironment, - gax.createDefaultBackoffSettings() + this._gaxModule.createDefaultBackoffSettings() ); return decodeOperation as LROperation< protos.google.cloud.shell.v1.AuthorizeEnvironmentResponse, protos.google.cloud.shell.v1.AuthorizeEnvironmentMetadata >; } + /** + * Adds a public SSH key to an environment, allowing clients with the + * corresponding private key to connect to that environment via SSH. If a key + * with the same content already exists, this will error with ALREADY_EXISTS. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.environment + * Environment this key should be added to, e.g. + * `users/me/environments/default`. + * @param {string} request.key + * Key that should be added to the environment. Supported formats are + * `ssh-dss` (see RFC4253), `ssh-rsa` (see RFC4253), `ecdsa-sha2-nistp256` + * (see RFC5656), `ecdsa-sha2-nistp384` (see RFC5656) and + * `ecdsa-sha2-nistp521` (see RFC5656). It should be structured as + * <format> <content>, where <content> part is encoded with + * Base64. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the + * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * for more details and examples. + * @example include:samples/generated/v1/cloud_shell_service.add_public_key.js + * region_tag:cloudshell_v1_generated_CloudShellService_AddPublicKey_async + */ addPublicKey( - request: protos.google.cloud.shell.v1.IAddPublicKeyRequest, + request?: protos.google.cloud.shell.v1.IAddPublicKeyRequest, options?: CallOptions ): Promise< [ @@ -786,38 +845,8 @@ export class CloudShellServiceClient { {} | null | undefined > ): void; - /** - * Adds a public SSH key to an environment, allowing clients with the - * corresponding private key to connect to that environment via SSH. If a key - * with the same content already exists, this will error with ALREADY_EXISTS. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.environment - * Environment this key should be added to, e.g. - * `users/me/environments/default`. - * @param {string} request.key - * Key that should be added to the environment. Supported formats are - * `ssh-dss` (see RFC4253), `ssh-rsa` (see RFC4253), `ecdsa-sha2-nistp256` - * (see RFC5656), `ecdsa-sha2-nistp384` (see RFC5656) and - * `ecdsa-sha2-nistp521` (see RFC5656). It should be structured as - * <format> <content>, where <content> part is encoded with - * Base64. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) - * for more details and examples. - * @example - * const [operation] = await client.addPublicKey(request); - * const [response] = await operation.promise(); - */ addPublicKey( - request: protos.google.cloud.shell.v1.IAddPublicKeyRequest, + request?: protos.google.cloud.shell.v1.IAddPublicKeyRequest, optionsOrCallback?: | CallOptions | Callback< @@ -858,8 +887,8 @@ export class CloudShellServiceClient { options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = - gax.routingHeader.fromParams({ - environment: request.environment || '', + this._gaxModule.routingHeader.fromParams({ + environment: request.environment ?? '', }); this.initialize(); return this.innerApiCalls.addPublicKey(request, options, callback); @@ -873,11 +902,8 @@ export class CloudShellServiceClient { * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) * for more details and examples. - * @example - * const decodedOperation = await checkAddPublicKeyProgress(name); - * console.log(decodedOperation.result); - * console.log(decodedOperation.done); - * console.log(decodedOperation.metadata); + * @example include:samples/generated/v1/cloud_shell_service.add_public_key.js + * region_tag:cloudshell_v1_generated_CloudShellService_AddPublicKey_async */ async checkAddPublicKeyProgress( name: string @@ -887,22 +913,48 @@ export class CloudShellServiceClient { protos.google.cloud.shell.v1.AddPublicKeyMetadata > > { - const request = new operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new gax.Operation( + const decodeOperation = new this._gaxModule.Operation( operation, this.descriptors.longrunning.addPublicKey, - gax.createDefaultBackoffSettings() + this._gaxModule.createDefaultBackoffSettings() ); return decodeOperation as LROperation< protos.google.cloud.shell.v1.AddPublicKeyResponse, protos.google.cloud.shell.v1.AddPublicKeyMetadata >; } + /** + * Removes a public SSH key from an environment. Clients will no longer be + * able to connect to the environment using the corresponding private key. + * If a key with the same content is not present, this will error with + * NOT_FOUND. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.environment + * Environment this key should be removed from, e.g. + * `users/me/environments/default`. + * @param {string} request.key + * Key that should be removed from the environment. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the + * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * for more details and examples. + * @example include:samples/generated/v1/cloud_shell_service.remove_public_key.js + * region_tag:cloudshell_v1_generated_CloudShellService_RemovePublicKey_async + */ removePublicKey( - request: protos.google.cloud.shell.v1.IRemovePublicKeyRequest, + request?: protos.google.cloud.shell.v1.IRemovePublicKeyRequest, options?: CallOptions ): Promise< [ @@ -937,34 +989,8 @@ export class CloudShellServiceClient { {} | null | undefined > ): void; - /** - * Removes a public SSH key from an environment. Clients will no longer be - * able to connect to the environment using the corresponding private key. - * If a key with the same content is not present, this will error with - * NOT_FOUND. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.environment - * Environment this key should be removed from, e.g. - * `users/me/environments/default`. - * @param {string} request.key - * Key that should be removed from the environment. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) - * for more details and examples. - * @example - * const [operation] = await client.removePublicKey(request); - * const [response] = await operation.promise(); - */ removePublicKey( - request: protos.google.cloud.shell.v1.IRemovePublicKeyRequest, + request?: protos.google.cloud.shell.v1.IRemovePublicKeyRequest, optionsOrCallback?: | CallOptions | Callback< @@ -1005,8 +1031,8 @@ export class CloudShellServiceClient { options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = - gax.routingHeader.fromParams({ - environment: request.environment || '', + this._gaxModule.routingHeader.fromParams({ + environment: request.environment ?? '', }); this.initialize(); return this.innerApiCalls.removePublicKey(request, options, callback); @@ -1020,11 +1046,8 @@ export class CloudShellServiceClient { * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) * for more details and examples. - * @example - * const decodedOperation = await checkRemovePublicKeyProgress(name); - * console.log(decodedOperation.result); - * console.log(decodedOperation.done); - * console.log(decodedOperation.metadata); + * @example include:samples/generated/v1/cloud_shell_service.remove_public_key.js + * region_tag:cloudshell_v1_generated_CloudShellService_RemovePublicKey_async */ async checkRemovePublicKeyProgress( name: string @@ -1034,20 +1057,198 @@ export class CloudShellServiceClient { protos.google.cloud.shell.v1.RemovePublicKeyMetadata > > { - const request = new operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new gax.Operation( + const decodeOperation = new this._gaxModule.Operation( operation, this.descriptors.longrunning.removePublicKey, - gax.createDefaultBackoffSettings() + this._gaxModule.createDefaultBackoffSettings() ); return decodeOperation as LROperation< protos.google.cloud.shell.v1.RemovePublicKeyResponse, protos.google.cloud.shell.v1.RemovePublicKeyMetadata >; } + /** + * Gets the latest state of a long-running operation. Clients can use this + * method to poll the operation result at intervals as recommended by the API + * service. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @param {function(?Error, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"}. + * @return {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * [google.longrunning.Operation]{@link + * external:"google.longrunning.Operation"}. The promise has a method named + * "cancel" which cancels the ongoing API call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * const name = ''; + * const [response] = await client.getOperation({name}); + * // doThingsWith(response) + * ``` + */ + getOperation( + request: protos.google.longrunning.GetOperationRequest, + options?: + | gax.CallOptions + | Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + > + ): Promise<[protos.google.longrunning.Operation]> { + return this.operationsClient.getOperation(request, options, callback); + } + /** + * Lists operations that match the specified filter in the request. If the + * server doesn't support this method, it returns `UNIMPLEMENTED`. Returns an iterable object. + * + * For-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @returns {Object} + * An iterable Object that conforms to @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * for await (const response of client.listOperationsAsync(request)); + * // doThingsWith(response) + * ``` + */ + listOperationsAsync( + request: protos.google.longrunning.ListOperationsRequest, + options?: gax.CallOptions + ): AsyncIterable { + return this.operationsClient.listOperationsAsync(request, options); + } + /** + * Starts asynchronous cancellation on a long-running operation. The server + * makes a best effort to cancel the operation, but success is not + * guaranteed. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. Clients can use + * {@link Operations.GetOperation} or + * other methods to check whether the cancellation succeeded or whether the + * operation completed despite cancellation. On successful cancellation, + * the operation is not deleted; instead, it becomes an operation with + * an {@link Operation.error} value with a {@link google.rpc.Status.code} of + * 1, corresponding to `Code.CANCELLED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be cancelled. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.cancelOperation({name: ''}); + * ``` + */ + cancelOperation( + request: protos.google.longrunning.CancelOperationRequest, + options?: + | gax.CallOptions + | Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.CancelOperationRequest, + {} | undefined | null + >, + callback?: Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + > + ): Promise { + return this.operationsClient.cancelOperation(request, options, callback); + } + + /** + * Deletes a long-running operation. This method indicates that the client is + * no longer interested in the operation result. It does not cancel the + * operation. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be deleted. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.deleteOperation({name: ''}); + * ``` + */ + deleteOperation( + request: protos.google.longrunning.DeleteOperationRequest, + options?: + | gax.CallOptions + | Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + > + ): Promise { + return this.operationsClient.deleteOperation(request, options, callback); + } + // -------------------- // -- Path templates -- // -------------------- @@ -1097,11 +1298,11 @@ export class CloudShellServiceClient { * @returns {Promise} A promise that resolves when the client is closed. */ close(): Promise { - this.initialize(); - if (!this._terminated) { - return this.cloudShellServiceStub!.then(stub => { + if (this.cloudShellServiceStub && !this._terminated) { + return this.cloudShellServiceStub.then(stub => { this._terminated = true; stub.close(); + this.operationsClient.close(); }); } return Promise.resolve(); diff --git a/packages/google-cloud-shell/src/v1/index.ts b/packages/google-cloud-shell/src/v1/index.ts index f56f0d6ebd4..18009968e59 100644 --- a/packages/google-cloud-shell/src/v1/index.ts +++ b/packages/google-cloud-shell/src/v1/index.ts @@ -1,4 +1,4 @@ -// Copyright 2021 Google LLC +// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-shell/system-test/fixtures/sample/src/index.js b/packages/google-cloud-shell/system-test/fixtures/sample/src/index.js index 6656dcae689..aa880939423 100644 --- a/packages/google-cloud-shell/system-test/fixtures/sample/src/index.js +++ b/packages/google-cloud-shell/system-test/fixtures/sample/src/index.js @@ -1,4 +1,4 @@ -// Copyright 2021 Google LLC +// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-shell/system-test/fixtures/sample/src/index.ts b/packages/google-cloud-shell/system-test/fixtures/sample/src/index.ts index d4d46e08a1d..2abdfc411b6 100644 --- a/packages/google-cloud-shell/system-test/fixtures/sample/src/index.ts +++ b/packages/google-cloud-shell/system-test/fixtures/sample/src/index.ts @@ -1,4 +1,4 @@ -// Copyright 2021 Google LLC +// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-shell/system-test/install.ts b/packages/google-cloud-shell/system-test/install.ts index d2d61c0396f..6dd1eaadafa 100644 --- a/packages/google-cloud-shell/system-test/install.ts +++ b/packages/google-cloud-shell/system-test/install.ts @@ -1,4 +1,4 @@ -// Copyright 2021 Google LLC +// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/packages/google-cloud-shell/test/gapic_cloud_shell_service_v1.ts b/packages/google-cloud-shell/test/gapic_cloud_shell_service_v1.ts index 6920622e1dc..132bf5c42c5 100644 --- a/packages/google-cloud-shell/test/gapic_cloud_shell_service_v1.ts +++ b/packages/google-cloud-shell/test/gapic_cloud_shell_service_v1.ts @@ -1,4 +1,4 @@ -// Copyright 2021 Google LLC +// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,6 +25,21 @@ import * as cloudshellserviceModule from '../src'; import {protobuf, LROperation, operationsProtos} from 'google-gax'; +// Dynamically loaded proto JSON is needed to get the type information +// to fill in default values for request objects +const root = protobuf.Root.fromJSON( + require('../protos/protos.json') +).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + function generateSampleMessage(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message @@ -81,87 +96,127 @@ function stubLongRunningCallWithCallback( : sinon.stub().callsArgWith(2, null, mockOperation); } +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); +} + describe('v1.CloudShellServiceClient', () => { - it('has servicePath', () => { - const servicePath = - cloudshellserviceModule.v1.CloudShellServiceClient.servicePath; - assert(servicePath); - }); + describe('Common methods', () => { + it('has servicePath', () => { + const servicePath = + cloudshellserviceModule.v1.CloudShellServiceClient.servicePath; + assert(servicePath); + }); - it('has apiEndpoint', () => { - const apiEndpoint = - cloudshellserviceModule.v1.CloudShellServiceClient.apiEndpoint; - assert(apiEndpoint); - }); + it('has apiEndpoint', () => { + const apiEndpoint = + cloudshellserviceModule.v1.CloudShellServiceClient.apiEndpoint; + assert(apiEndpoint); + }); - it('has port', () => { - const port = cloudshellserviceModule.v1.CloudShellServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has port', () => { + const port = cloudshellserviceModule.v1.CloudShellServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with no option', () => { - const client = new cloudshellserviceModule.v1.CloudShellServiceClient(); - assert(client); - }); + it('should create a client with no option', () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient(); + assert(client); + }); - it('should create a client with gRPC fallback', () => { - const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ - fallback: true, + it('should create a client with gRPC fallback', () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + fallback: true, + }); + assert(client); }); - assert(client); - }); - it('has initialize method and supports deferred initialization', async () => { - const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', + it('has initialize method and supports deferred initialization', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudShellServiceStub, undefined); + await client.initialize(); + assert(client.cloudShellServiceStub); }); - assert.strictEqual(client.cloudShellServiceStub, undefined); - await client.initialize(); - assert(client.cloudShellServiceStub); - }); - it('has close method', () => { - const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', + it('has close method for the initialized client', done => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + assert(client.cloudShellServiceStub); + client.close().then(() => { + done(); + }); }); - client.close(); - }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', + it('has close method for the non-initialized client', done => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudShellServiceStub, undefined); + client.close().then(() => { + done(); + }); }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - client.auth.getProjectId = sinon - .stub() - .callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error | null, projectId?: string | null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); }); describe('getEnvironment', () => { @@ -174,26 +229,26 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.GetEnvironmentRequest() ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.GetEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; const expectedResponse = generateSampleMessage( new protos.google.cloud.shell.v1.Environment() ); client.innerApiCalls.getEnvironment = stubSimpleCall(expectedResponse); const [response] = await client.getEnvironment(request); assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.getEnvironment as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.getEnvironment as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEnvironment as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes getEnvironment without error using callback', async () => { @@ -205,15 +260,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.GetEnvironmentRequest() ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.GetEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; const expectedResponse = generateSampleMessage( new protos.google.cloud.shell.v1.Environment() ); @@ -236,11 +288,14 @@ describe('v1.CloudShellServiceClient', () => { }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.getEnvironment as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions /*, callback defined above */) - ); + const actualRequest = ( + client.innerApiCalls.getEnvironment as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEnvironment as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes getEnvironment with error', async () => { @@ -252,26 +307,45 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.GetEnvironmentRequest() ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.GetEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; const expectedError = new Error('expected'); client.innerApiCalls.getEnvironment = stubSimpleCall( undefined, expectedError ); await assert.rejects(client.getEnvironment(request), expectedError); - assert( - (client.innerApiCalls.getEnvironment as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) + const actualRequest = ( + client.innerApiCalls.getEnvironment as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEnvironment as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getEnvironment with closed client', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.shell.v1.GetEnvironmentRequest() ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.GetEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close(); + await assert.rejects(client.getEnvironment(request), expectedError); }); }); @@ -285,15 +359,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.StartEnvironmentRequest() ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.StartEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation() ); @@ -302,11 +373,14 @@ describe('v1.CloudShellServiceClient', () => { const [operation] = await client.startEnvironment(request); const [response] = await operation.promise(); assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.startEnvironment as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.startEnvironment as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.startEnvironment as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes startEnvironment without error using callback', async () => { @@ -318,15 +392,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.StartEnvironmentRequest() ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.StartEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation() ); @@ -356,11 +427,14 @@ describe('v1.CloudShellServiceClient', () => { >; const [response] = await operation.promise(); assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.startEnvironment as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions /*, callback defined above */) - ); + const actualRequest = ( + client.innerApiCalls.startEnvironment as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.startEnvironment as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes startEnvironment with call error', async () => { @@ -372,26 +446,26 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.StartEnvironmentRequest() ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.StartEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; const expectedError = new Error('expected'); client.innerApiCalls.startEnvironment = stubLongRunningCall( undefined, expectedError ); await assert.rejects(client.startEnvironment(request), expectedError); - assert( - (client.innerApiCalls.startEnvironment as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.startEnvironment as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.startEnvironment as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes startEnvironment with LRO error', async () => { @@ -403,15 +477,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.StartEnvironmentRequest() ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.StartEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; const expectedError = new Error('expected'); client.innerApiCalls.startEnvironment = stubLongRunningCall( undefined, @@ -420,11 +491,14 @@ describe('v1.CloudShellServiceClient', () => { ); const [operation] = await client.startEnvironment(request); await assert.rejects(operation.promise(), expectedError); - assert( - (client.innerApiCalls.startEnvironment as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.startEnvironment as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.startEnvironment as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes checkStartEnvironmentProgress without error', async () => { @@ -479,15 +553,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.AuthorizeEnvironmentRequest() ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.AuthorizeEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation() ); @@ -496,11 +567,14 @@ describe('v1.CloudShellServiceClient', () => { const [operation] = await client.authorizeEnvironment(request); const [response] = await operation.promise(); assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.authorizeEnvironment as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.authorizeEnvironment as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.authorizeEnvironment as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes authorizeEnvironment without error using callback', async () => { @@ -512,15 +586,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.AuthorizeEnvironmentRequest() ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.AuthorizeEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation() ); @@ -550,11 +621,14 @@ describe('v1.CloudShellServiceClient', () => { >; const [response] = await operation.promise(); assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.authorizeEnvironment as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions /*, callback defined above */) - ); + const actualRequest = ( + client.innerApiCalls.authorizeEnvironment as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.authorizeEnvironment as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes authorizeEnvironment with call error', async () => { @@ -566,26 +640,26 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.AuthorizeEnvironmentRequest() ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.AuthorizeEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; const expectedError = new Error('expected'); client.innerApiCalls.authorizeEnvironment = stubLongRunningCall( undefined, expectedError ); await assert.rejects(client.authorizeEnvironment(request), expectedError); - assert( - (client.innerApiCalls.authorizeEnvironment as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.authorizeEnvironment as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.authorizeEnvironment as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes authorizeEnvironment with LRO error', async () => { @@ -597,15 +671,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.AuthorizeEnvironmentRequest() ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.AuthorizeEnvironmentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; const expectedError = new Error('expected'); client.innerApiCalls.authorizeEnvironment = stubLongRunningCall( undefined, @@ -614,11 +685,14 @@ describe('v1.CloudShellServiceClient', () => { ); const [operation] = await client.authorizeEnvironment(request); await assert.rejects(operation.promise(), expectedError); - assert( - (client.innerApiCalls.authorizeEnvironment as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.authorizeEnvironment as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.authorizeEnvironment as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes checkAuthorizeEnvironmentProgress without error', async () => { @@ -673,15 +747,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.AddPublicKeyRequest() ); - request.environment = ''; - const expectedHeaderRequestParams = 'environment='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.AddPublicKeyRequest', + ['environment'] + ); + request.environment = defaultValue1; + const expectedHeaderRequestParams = `environment=${defaultValue1}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation() ); @@ -689,11 +760,14 @@ describe('v1.CloudShellServiceClient', () => { const [operation] = await client.addPublicKey(request); const [response] = await operation.promise(); assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.addPublicKey as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.addPublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addPublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes addPublicKey without error using callback', async () => { @@ -705,15 +779,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.AddPublicKeyRequest() ); - request.environment = ''; - const expectedHeaderRequestParams = 'environment='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.AddPublicKeyRequest', + ['environment'] + ); + request.environment = defaultValue1; + const expectedHeaderRequestParams = `environment=${defaultValue1}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation() ); @@ -743,11 +814,14 @@ describe('v1.CloudShellServiceClient', () => { >; const [response] = await operation.promise(); assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.addPublicKey as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions /*, callback defined above */) - ); + const actualRequest = ( + client.innerApiCalls.addPublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addPublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes addPublicKey with call error', async () => { @@ -759,26 +833,26 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.AddPublicKeyRequest() ); - request.environment = ''; - const expectedHeaderRequestParams = 'environment='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.AddPublicKeyRequest', + ['environment'] + ); + request.environment = defaultValue1; + const expectedHeaderRequestParams = `environment=${defaultValue1}`; const expectedError = new Error('expected'); client.innerApiCalls.addPublicKey = stubLongRunningCall( undefined, expectedError ); await assert.rejects(client.addPublicKey(request), expectedError); - assert( - (client.innerApiCalls.addPublicKey as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.addPublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addPublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes addPublicKey with LRO error', async () => { @@ -790,15 +864,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.AddPublicKeyRequest() ); - request.environment = ''; - const expectedHeaderRequestParams = 'environment='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.AddPublicKeyRequest', + ['environment'] + ); + request.environment = defaultValue1; + const expectedHeaderRequestParams = `environment=${defaultValue1}`; const expectedError = new Error('expected'); client.innerApiCalls.addPublicKey = stubLongRunningCall( undefined, @@ -807,11 +878,14 @@ describe('v1.CloudShellServiceClient', () => { ); const [operation] = await client.addPublicKey(request); await assert.rejects(operation.promise(), expectedError); - assert( - (client.innerApiCalls.addPublicKey as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.addPublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addPublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes checkAddPublicKeyProgress without error', async () => { @@ -863,15 +937,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.RemovePublicKeyRequest() ); - request.environment = ''; - const expectedHeaderRequestParams = 'environment='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.RemovePublicKeyRequest', + ['environment'] + ); + request.environment = defaultValue1; + const expectedHeaderRequestParams = `environment=${defaultValue1}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation() ); @@ -880,11 +951,14 @@ describe('v1.CloudShellServiceClient', () => { const [operation] = await client.removePublicKey(request); const [response] = await operation.promise(); assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.removePublicKey as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.removePublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removePublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes removePublicKey without error using callback', async () => { @@ -896,15 +970,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.RemovePublicKeyRequest() ); - request.environment = ''; - const expectedHeaderRequestParams = 'environment='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.RemovePublicKeyRequest', + ['environment'] + ); + request.environment = defaultValue1; + const expectedHeaderRequestParams = `environment=${defaultValue1}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation() ); @@ -934,11 +1005,14 @@ describe('v1.CloudShellServiceClient', () => { >; const [response] = await operation.promise(); assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.removePublicKey as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions /*, callback defined above */) - ); + const actualRequest = ( + client.innerApiCalls.removePublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removePublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes removePublicKey with call error', async () => { @@ -950,26 +1024,26 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.RemovePublicKeyRequest() ); - request.environment = ''; - const expectedHeaderRequestParams = 'environment='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.RemovePublicKeyRequest', + ['environment'] + ); + request.environment = defaultValue1; + const expectedHeaderRequestParams = `environment=${defaultValue1}`; const expectedError = new Error('expected'); client.innerApiCalls.removePublicKey = stubLongRunningCall( undefined, expectedError ); await assert.rejects(client.removePublicKey(request), expectedError); - assert( - (client.innerApiCalls.removePublicKey as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.removePublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removePublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes removePublicKey with LRO error', async () => { @@ -981,15 +1055,12 @@ describe('v1.CloudShellServiceClient', () => { const request = generateSampleMessage( new protos.google.cloud.shell.v1.RemovePublicKeyRequest() ); - request.environment = ''; - const expectedHeaderRequestParams = 'environment='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.shell.v1.RemovePublicKeyRequest', + ['environment'] + ); + request.environment = defaultValue1; + const expectedHeaderRequestParams = `environment=${defaultValue1}`; const expectedError = new Error('expected'); client.innerApiCalls.removePublicKey = stubLongRunningCall( undefined, @@ -998,11 +1069,14 @@ describe('v1.CloudShellServiceClient', () => { ); const [operation] = await client.removePublicKey(request); await assert.rejects(operation.promise(), expectedError); - assert( - (client.innerApiCalls.removePublicKey as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + const actualRequest = ( + client.innerApiCalls.removePublicKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.removePublicKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); it('invokes checkRemovePublicKeyProgress without error', async () => { @@ -1046,6 +1120,311 @@ describe('v1.CloudShellServiceClient', () => { assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); }); + describe('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const response = await client.getOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); + }); + it('invokes getOperation without error using callback', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + client.operationsClient.getOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient.getOperation( + request, + undefined, + ( + err?: Error | null, + result?: operationsProtos.google.longrunning.Operation | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + it('invokes getOperation with error', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(async () => { + await client.getOperation(request); + }, expectedError); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); + }); + }); + describe('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.cancelOperation = + stubSimpleCall(expectedResponse); + const response = await client.cancelOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); + }); + it('invokes cancelOperation without error using callback', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.cancelOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient.cancelOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.cancelOperation as SinonStub).getCall(0)); + }); + it('invokes cancelOperation with error', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.cancelOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(async () => { + await client.cancelOperation(request); + }, expectedError); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); + }); + }); + describe('deleteOperation', () => { + it('invokes deleteOperation without error', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.deleteOperation = + stubSimpleCall(expectedResponse); + const response = await client.deleteOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); + }); + it('invokes deleteOperation without error using callback', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.deleteOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient.deleteOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.deleteOperation as SinonStub).getCall(0)); + }); + it('invokes deleteOperation with error', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.deleteOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(async () => { + await client.deleteOperation(request); + }, expectedError); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); + }); + }); + describe('listOperationsAsync', () => { + it('uses async iteration with listOperations without error', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest() + ); + const expectedResponse = [ + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse() + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse() + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse() + ), + ]; + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: operationsProtos.google.longrunning.ListOperationsResponse[] = + []; + const iterable = client.operationsClient.listOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + }); + it('uses async iteration with listOperations with error', async () => { + const client = new cloudshellserviceModule.v1.CloudShellServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.operationsClient.listOperationsAsync(request); + await assert.rejects(async () => { + const responses: operationsProtos.google.longrunning.ListOperationsResponse[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + }); + }); describe('Path templates', () => { describe('environment', () => {