// Copyright 2022 Luca Casonato. All rights reserved. MIT license. /** * Google Workspace Events API Client for Deno * =========================================== * * The Google Workspace Events API lets you subscribe to events and manage change notifications across Google Workspace applications. * * Docs: https://developers.google.com/workspace/events * Source: https://googleapis.deno.dev/v1/workspaceevents:v1.ts */ import { auth, CredentialsClient, GoogleAuth, request } from "/_/base@v1/mod.ts"; export { auth, GoogleAuth }; export type { CredentialsClient }; /** * The Google Workspace Events API lets you subscribe to events and manage * change notifications across Google Workspace applications. */ export class WorkspaceEvents { #client: CredentialsClient | undefined; #baseUrl: string; constructor(client?: CredentialsClient, baseUrl: string = "https://workspaceevents.googleapis.com/") { this.#client = client; this.#baseUrl = baseUrl; } /** * SendStreamingMessage is a streaming call that will return a stream of task * update events until the Task is in an interrupted or terminal state. * */ async messageStream(req: SendMessageRequest): Promise { req = serializeSendMessageRequest(req); const url = new URL(`${this.#baseUrl}v1/message:stream`); const body = JSON.stringify(req); const data = await request(url.href, { client: this.#client, method: "POST", body, }); return deserializeStreamResponse(data); } /** * 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 name The name of the operation resource. */ async operationsGet(name: string): Promise { const url = new URL(`${this.#baseUrl}v1/${ name }`); const data = await request(url.href, { client: this.#client, method: "GET", }); return data as Operation; } /** * Creates a Google Workspace subscription. To learn how to use this method, * see [Create a Google Workspace * subscription](https://developers.google.com/workspace/events/guides/create-subscription). * For a subscription on a [Chat target * resource](https://developers.google.com/workspace/events/guides/events-chat), * you can create a subscription as: - A Chat app by specifying an * authorization scope that begins with `chat.app` and getting one-time * administrator approval ([Developer * Preview](https://developers.google.com/workspace/preview)). To learn more, * see [Authorize as a Chat app with administrator * approval](https://developers.google.com/workspace/chat/authenticate-authorize-chat-app). * - A user by specifying an authorization scope that doesn't include `app` in * its name. To learn more, see [Authorize as a Chat * user](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user). * */ async subscriptionsCreate(req: Subscription, opts: SubscriptionsCreateOptions = {}): Promise { req = serializeSubscription(req); const url = new URL(`${this.#baseUrl}v1/subscriptions`); if (opts.validateOnly !== undefined) { url.searchParams.append("validateOnly", String(opts.validateOnly)); } const body = JSON.stringify(req); const data = await request(url.href, { client: this.#client, method: "POST", body, }); return data as Operation; } /** * Deletes a Google Workspace subscription. To learn how to use this method, * see [Delete a Google Workspace * subscription](https://developers.google.com/workspace/events/guides/delete-subscription). * * @param name Required. Resource name of the subscription to delete. Format: `subscriptions/{subscription}` */ async subscriptionsDelete(name: string, opts: SubscriptionsDeleteOptions = {}): Promise { const url = new URL(`${this.#baseUrl}v1/${ name }`); if (opts.allowMissing !== undefined) { url.searchParams.append("allowMissing", String(opts.allowMissing)); } if (opts.etag !== undefined) { url.searchParams.append("etag", String(opts.etag)); } if (opts.validateOnly !== undefined) { url.searchParams.append("validateOnly", String(opts.validateOnly)); } const data = await request(url.href, { client: this.#client, method: "DELETE", }); return data as Operation; } /** * Gets details about a Google Workspace subscription. To learn how to use * this method, see [Get details about a Google Workspace * subscription](https://developers.google.com/workspace/events/guides/get-subscription). * * @param name Required. Resource name of the subscription. Format: `subscriptions/{subscription}` */ async subscriptionsGet(name: string): Promise { const url = new URL(`${this.#baseUrl}v1/${ name }`); const data = await request(url.href, { client: this.#client, method: "GET", }); return deserializeSubscription(data); } /** * Lists Google Workspace subscriptions. To learn how to use this method, see * [List Google Workspace * subscriptions](https://developers.google.com/workspace/events/guides/list-subscriptions). * */ async subscriptionsList(opts: SubscriptionsListOptions = {}): Promise { const url = new URL(`${this.#baseUrl}v1/subscriptions`); if (opts.filter !== undefined) { url.searchParams.append("filter", String(opts.filter)); } if (opts.pageSize !== undefined) { url.searchParams.append("pageSize", String(opts.pageSize)); } if (opts.pageToken !== undefined) { url.searchParams.append("pageToken", String(opts.pageToken)); } const data = await request(url.href, { client: this.#client, method: "GET", }); return deserializeListSubscriptionsResponse(data); } /** * Updates or renews a Google Workspace subscription. To learn how to use * this method, see [Update or renew a Google Workspace * subscription](https://developers.google.com/workspace/events/guides/update-subscription). * For a subscription on a [Chat target * resource](https://developers.google.com/workspace/events/guides/events-chat), * you can update a subscription as: - A Chat app by specifying an * authorization scope that begins with `chat.app` andgetting one-time * administrator approval ([Developer * Preview](https://developers.google.com/workspace/preview)). To learn more, * see [Authorize as a Chat app with administrator * approval](https://developers.google.com/workspace/chat/authenticate-authorize-chat-app). * - A user by specifying an authorization scope that doesn't include `app` in * its name. To learn more, see [Authorize as a Chat * user](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user). * * @param name Identifier. Resource name of the subscription. Format: `subscriptions/{subscription}` */ async subscriptionsPatch(name: string, req: Subscription, opts: SubscriptionsPatchOptions = {}): Promise { req = serializeSubscription(req); opts = serializeSubscriptionsPatchOptions(opts); const url = new URL(`${this.#baseUrl}v1/${ name }`); if (opts.updateMask !== undefined) { url.searchParams.append("updateMask", String(opts.updateMask)); } if (opts.validateOnly !== undefined) { url.searchParams.append("validateOnly", String(opts.validateOnly)); } const body = JSON.stringify(req); const data = await request(url.href, { client: this.#client, method: "PATCH", body, }); return data as Operation; } /** * Reactivates a suspended Google Workspace subscription. This method resets * your subscription's `State` field to `ACTIVE`. Before you use this method, * you must fix the error that suspended the subscription. This method will * ignore or reject any subscription that isn't currently in a suspended * state. To learn how to use this method, see [Reactivate a Google Workspace * subscription](https://developers.google.com/workspace/events/guides/reactivate-subscription). * For a subscription on a [Chat target * resource](https://developers.google.com/workspace/events/guides/events-chat), * you can reactivate a subscription as: - A Chat app by specifying an * authorization scope that begins with `chat.app` andgetting one-time * administrator approval ([Developer * Preview](https://developers.google.com/workspace/preview)). To learn more, * see [Authorize as a Chat app with administrator * approval](https://developers.google.com/workspace/chat/authenticate-authorize-chat-app). * - A user by specifying an authorization scope that doesn't include `app` in * its name. To learn more, see [Authorize as a Chat * user](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user). * * @param name Required. Resource name of the subscription. Format: `subscriptions/{subscription}` */ async subscriptionsReactivate(name: string, req: ReactivateSubscriptionRequest): Promise { const url = new URL(`${this.#baseUrl}v1/${ name }:reactivate`); const body = JSON.stringify(req); const data = await request(url.href, { client: this.#client, method: "POST", body, }); return data as Operation; } /** * Cancel a task from the agent. If supported one should expect no more task * updates for the task. * * @param name The resource name of the task to cancel. Format: tasks/{task_id} */ async tasksCancel(name: string, req: CancelTaskRequest): Promise { const url = new URL(`${this.#baseUrl}v1/${ name }:cancel`); const body = JSON.stringify(req); const data = await request(url.href, { client: this.#client, method: "POST", body, }); return deserializeTask(data); } /** * Get the current state of a task from the agent. * * @param name Required. The resource name of the task. Format: tasks/{task_id} */ async tasksGet(name: string, opts: TasksGetOptions = {}): Promise { const url = new URL(`${this.#baseUrl}v1/${ name }`); if (opts.historyLength !== undefined) { url.searchParams.append("historyLength", String(opts.historyLength)); } if (opts.tenant !== undefined) { url.searchParams.append("tenant", String(opts.tenant)); } const data = await request(url.href, { client: this.#client, method: "GET", }); return deserializeTask(data); } /** * Set a push notification config for a task. * * @param parent Required. The parent task resource for this config. Format: tasks/{task_id} */ async tasksPushNotificationConfigsCreate(parent: string, req: TaskPushNotificationConfig, opts: TasksPushNotificationConfigsCreateOptions = {}): Promise { const url = new URL(`${this.#baseUrl}v1/${ parent }`); if (opts.configId !== undefined) { url.searchParams.append("configId", String(opts.configId)); } if (opts.tenant !== undefined) { url.searchParams.append("tenant", String(opts.tenant)); } const body = JSON.stringify(req); const data = await request(url.href, { client: this.#client, method: "POST", body, }); return data as TaskPushNotificationConfig; } /** * Delete a push notification config for a task. * * @param name The resource name of the config to delete. Format: tasks/{task_id}/pushNotificationConfigs/{config_id} */ async tasksPushNotificationConfigsDelete(name: string, opts: TasksPushNotificationConfigsDeleteOptions = {}): Promise { const url = new URL(`${this.#baseUrl}v1/${ name }`); if (opts.tenant !== undefined) { url.searchParams.append("tenant", String(opts.tenant)); } const data = await request(url.href, { client: this.#client, method: "DELETE", }); return data as Empty; } /** * Get a push notification config for a task. * * @param name The resource name of the config to retrieve. Format: tasks/{task_id}/pushNotificationConfigs/{config_id} */ async tasksPushNotificationConfigsGet(name: string, opts: TasksPushNotificationConfigsGetOptions = {}): Promise { const url = new URL(`${this.#baseUrl}v1/${ name }`); if (opts.tenant !== undefined) { url.searchParams.append("tenant", String(opts.tenant)); } const data = await request(url.href, { client: this.#client, method: "GET", }); return data as TaskPushNotificationConfig; } /** * Get a list of push notifications configured for a task. * * @param parent The parent task resource. Format: tasks/{task_id} */ async tasksPushNotificationConfigsList(parent: string, opts: TasksPushNotificationConfigsListOptions = {}): Promise { const url = new URL(`${this.#baseUrl}v1/${ parent }/pushNotificationConfigs`); if (opts.pageSize !== undefined) { url.searchParams.append("pageSize", String(opts.pageSize)); } if (opts.pageToken !== undefined) { url.searchParams.append("pageToken", String(opts.pageToken)); } if (opts.tenant !== undefined) { url.searchParams.append("tenant", String(opts.tenant)); } const data = await request(url.href, { client: this.#client, method: "GET", }); return data as ListTaskPushNotificationConfigResponse; } /** * TaskSubscription is a streaming call that will return a stream of task * update events. This attaches the stream to an existing in process task. If * the task is complete the stream will return the completed task (like * GetTask) and close the stream. * * @param name The resource name of the task to subscribe to. Format: tasks/{task_id} */ async tasksSubscribe(name: string, opts: TasksSubscribeOptions = {}): Promise { const url = new URL(`${this.#baseUrl}v1/${ name }:subscribe`); if (opts.tenant !== undefined) { url.searchParams.append("tenant", String(opts.tenant)); } const data = await request(url.href, { client: this.#client, method: "GET", }); return deserializeStreamResponse(data); } } /** * Artifacts are the container for task completed results. These are similar to * Messages but are intended to be the product of a task, as opposed to * point-to-point communication. */ export interface Artifact { /** * Unique identifier (e.g. UUID) for the artifact. It must be at least unique * within a task. */ artifactId?: string; /** * A human readable description of the artifact, optional. */ description?: string; /** * The URIs of extensions that are present or contributed to this Artifact. */ extensions?: string[]; /** * Optional metadata included with the artifact. */ metadata?: { [key: string]: any }; /** * A human readable name for the artifact. */ name?: string; /** * The content of the artifact. */ parts?: Part[]; } function serializeArtifact(data: any): Artifact { return { ...data, parts: data["parts"] !== undefined ? data["parts"].map((item: any) => (serializePart(item))) : undefined, }; } function deserializeArtifact(data: any): Artifact { return { ...data, parts: data["parts"] !== undefined ? data["parts"].map((item: any) => (deserializePart(item))) : undefined, }; } /** * Defines authentication details, used for push notifications. */ export interface AuthenticationInfo { /** * Optional credentials */ credentials?: string; /** * Supported authentication schemes - e.g. Basic, Bearer, etc */ schemes?: string[]; } export interface CancelTaskRequest { /** * Optional tenant, provided as a path parameter. Experimental, might still * change for 1.0 release. */ tenant?: string; } /** * DataPart represents a structured blob. This is most commonly a JSON payload. */ export interface DataPart { data?: { [key: string]: any }; } /** * A generic empty message that you can re-use to avoid defining duplicated * empty messages in your APIs. A typical example is to use it as the request or * the response type of an API method. For instance: service Foo { rpc * Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } */ export interface Empty { } /** * FilePart represents the different ways files can be provided. If files are * small, directly feeding the bytes is supported via file_with_bytes. If the * file is large, the agent should read the content as appropriate directly from * the file_with_uri source. */ export interface FilePart { fileWithBytes?: Uint8Array; fileWithUri?: string; mimeType?: string; name?: string; } function serializeFilePart(data: any): FilePart { return { ...data, fileWithBytes: data["fileWithBytes"] !== undefined ? encodeBase64(data["fileWithBytes"]) : undefined, }; } function deserializeFilePart(data: any): FilePart { return { ...data, fileWithBytes: data["fileWithBytes"] !== undefined ? decodeBase64(data["fileWithBytes"] as string) : undefined, }; } /** * The response message for SubscriptionsService.ListSubscriptions. */ export interface ListSubscriptionsResponse { /** * A token, which can be sent as `page_token` to retrieve the next page. If * this field is omitted, there are no subsequent pages. */ nextPageToken?: string; /** * List of subscriptions. */ subscriptions?: Subscription[]; } function serializeListSubscriptionsResponse(data: any): ListSubscriptionsResponse { return { ...data, subscriptions: data["subscriptions"] !== undefined ? data["subscriptions"].map((item: any) => (serializeSubscription(item))) : undefined, }; } function deserializeListSubscriptionsResponse(data: any): ListSubscriptionsResponse { return { ...data, subscriptions: data["subscriptions"] !== undefined ? data["subscriptions"].map((item: any) => (deserializeSubscription(item))) : undefined, }; } export interface ListTaskPushNotificationConfigResponse { /** * The list of push notification configurations. */ configs?: TaskPushNotificationConfig[]; /** * A token, which can be sent as `page_token` to retrieve the next page. If * this field is omitted, there are no subsequent pages. */ nextPageToken?: string; } /** * Message is one unit of communication between client and server. It is * associated with a context and optionally a task. Since the server is * responsible for the context definition, it must always provide a context_id * in its messages. The client can optionally provide the context_id if it knows * the context to associate the message to. Similarly for task_id, except the * server decides if a task is created and whether to include the task_id. */ export interface Message { /** * protolint:disable REPEATED_FIELD_NAMES_PLURALIZED Content is the container * of the message content. */ content?: Part[]; /** * The context id of the message. This is optional and if set, the message * will be associated with the given context. */ contextId?: string; /** * The URIs of extensions that are present or contributed to this Message. */ extensions?: string[]; /** * The unique identifier (e.g. UUID)of the message. This is required and * created by the message creator. */ messageId?: string; /** * protolint:enable REPEATED_FIELD_NAMES_PLURALIZED Any optional metadata to * provide along with the message. */ metadata?: { [key: string]: any }; /** * A role for the message. */ role?: | "ROLE_UNSPECIFIED" | "ROLE_USER" | "ROLE_AGENT"; /** * The task id of the message. This is optional and if set, the message will * be associated with the given task. */ taskId?: string; } function serializeMessage(data: any): Message { return { ...data, content: data["content"] !== undefined ? data["content"].map((item: any) => (serializePart(item))) : undefined, }; } function deserializeMessage(data: any): Message { return { ...data, content: data["content"] !== undefined ? data["content"].map((item: any) => (deserializePart(item))) : undefined, }; } /** * The endpoint where the subscription delivers events. */ export interface NotificationEndpoint { /** * Immutable. The Pub/Sub topic that receives events for the subscription. * Format: `projects/{project}/topics/{topic}` You must create the topic in * the same Google Cloud project where you create this subscription. Note: The * Google Workspace Events API uses [ordering * keys](https://cloud.google.com/pubsub/docs/ordering) for the benefit of * sequential events. If the Cloud Pub/Sub topic has a [message storage * policy](https://cloud.google.com/pubsub/docs/resource-location-restriction#exceptions) * configured to exclude the nearest Google Cloud region, publishing events * with ordering keys will fail. When the topic receives events, the events * are encoded as Pub/Sub messages. For details, see the [Google Cloud Pub/Sub * Protocol Binding for * CloudEvents](https://github.com/googleapis/google-cloudevents/blob/main/docs/spec/pubsub.md). */ pubsubTopic?: string; } /** * This resource represents a long-running operation that is the result of a * network API call. */ export interface Operation { /** * If the value is `false`, it means the operation is still in progress. If * `true`, the operation is completed, and either `error` or `response` is * available. */ done?: boolean; /** * The error result of the operation in case of failure or cancellation. */ error?: Status; /** * Service-specific metadata associated with the operation. It typically * contains progress information and common metadata such as create time. Some * services might not provide such metadata. Any method that returns a * long-running operation should document the metadata type, if any. */ metadata?: { [key: string]: any }; /** * The server-assigned name, which is only unique within the same service * that originally returns it. If you use the default HTTP mapping, the `name` * should be a resource name ending with `operations/{unique_id}`. */ name?: string; /** * The normal, successful response of the operation. If the original method * returns no data on success, such as `Delete`, the response is * `google.protobuf.Empty`. If the original method is standard * `Get`/`Create`/`Update`, the response should be the resource. For other * methods, the response should have the type `XxxResponse`, where `Xxx` is * the original method name. For example, if the original method name is * `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. */ response?: { [key: string]: any }; } /** * Part represents a container for a section of communication content. Parts * can be purely textual, some sort of file (image, video, etc) or a structured * data blob (i.e. JSON). */ export interface Part { data?: DataPart; file?: FilePart; /** * Optional metadata associated with this part. */ metadata?: { [key: string]: any }; text?: string; } function serializePart(data: any): Part { return { ...data, file: data["file"] !== undefined ? serializeFilePart(data["file"]) : undefined, }; } function deserializePart(data: any): Part { return { ...data, file: data["file"] !== undefined ? deserializeFilePart(data["file"]) : undefined, }; } /** * Options about what data to include in the event payload. Only supported for * Google Chat and Google Drive events. */ export interface PayloadOptions { /** * Optional. If `include_resource` is set to `true`, the list of fields to * include in the event payload. Separate fields with a comma. For example, to * include a Google Chat message's sender and create time, enter * `message.sender,message.createTime`. If omitted, the payload includes all * fields for the resource. If you specify a field that doesn't exist for the * resource, the system ignores the field. */ fieldMask?: string /* FieldMask */; /** * Optional. Whether the event payload includes data about the resource that * changed. For example, for an event where a Google Chat message was created, * whether the payload contains data about the * [`Message`](https://developers.google.com/chat/api/reference/rest/v1/spaces.messages) * resource. If false, the event payload only includes the name of the changed * resource. */ includeResource?: boolean; } function serializePayloadOptions(data: any): PayloadOptions { return { ...data, fieldMask: data["fieldMask"] !== undefined ? data["fieldMask"] : undefined, }; } function deserializePayloadOptions(data: any): PayloadOptions { return { ...data, fieldMask: data["fieldMask"] !== undefined ? data["fieldMask"] : undefined, }; } /** * Configuration for setting up push notifications for task updates. */ export interface PushNotificationConfig { /** * Information about the authentication to sent with the notification */ authentication?: AuthenticationInfo; /** * A unique identifier (e.g. UUID) for this push notification. */ id?: string; /** * Token unique for this task/session */ token?: string; /** * Url to send the notification too */ url?: string; } /** * The request message for SubscriptionsService.ReactivateSubscription. */ export interface ReactivateSubscriptionRequest { } /** * Configuration of a send message request. */ export interface SendMessageConfiguration { /** * The output modes that the agent is expected to respond with. */ acceptedOutputModes?: string[]; /** * If true, the message will be blocking until the task is completed. If * false, the message will be non-blocking and the task will be returned * immediately. It is the caller's responsibility to check for any task * updates. */ blocking?: boolean; /** * The maximum number of messages to include in the history. if 0, the * history will be unlimited. */ historyLength?: number; /** * A configuration of a webhook that can be used to receive updates */ pushNotification?: PushNotificationConfig; } /** * /////////// Request Messages /////////// */ export interface SendMessageRequest { /** * Configuration for the send request. */ configuration?: SendMessageConfiguration; /** * Required. The message to send to the agent. */ message?: Message; /** * Optional metadata for the request. */ metadata?: { [key: string]: any }; /** * Optional tenant, provided as a path parameter. Experimental, might still * change for 1.0 release. */ tenant?: string; } function serializeSendMessageRequest(data: any): SendMessageRequest { return { ...data, message: data["message"] !== undefined ? serializeMessage(data["message"]) : undefined, }; } function deserializeSendMessageRequest(data: any): SendMessageRequest { return { ...data, message: data["message"] !== undefined ? deserializeMessage(data["message"]) : undefined, }; } /** * The `Status` type defines a logical error model that is suitable for * different programming environments, including REST APIs and RPC APIs. It is * used by [gRPC](https://github.com/grpc). Each `Status` message contains three * pieces of data: error code, error message, and error details. You can find * out more about this error model and how to work with it in the [API Design * Guide](https://cloud.google.com/apis/design/errors). */ export interface Status { /** * The status code, which should be an enum value of google.rpc.Code. */ code?: number; /** * A list of messages that carry the error details. There is a common set of * message types for APIs to use. */ details?: { [key: string]: any }[]; /** * A developer-facing error message, which should be in English. Any * user-facing error message should be localized and sent in the * google.rpc.Status.details field, or localized by the client. */ message?: string; } /** * The stream response for a message. The stream should be one of the following * sequences: If the response is a message, the stream should contain one, and * only one, message and then close If the response is a task lifecycle, the * first response should be a Task object followed by zero or more * TaskStatusUpdateEvents and TaskArtifactUpdateEvents. The stream should * complete when the Task if in an interrupted or terminal state. A stream that * ends before these conditions are met are */ export interface StreamResponse { artifactUpdate?: TaskArtifactUpdateEvent; message?: Message; statusUpdate?: TaskStatusUpdateEvent; task?: Task; } function serializeStreamResponse(data: any): StreamResponse { return { ...data, artifactUpdate: data["artifactUpdate"] !== undefined ? serializeTaskArtifactUpdateEvent(data["artifactUpdate"]) : undefined, message: data["message"] !== undefined ? serializeMessage(data["message"]) : undefined, statusUpdate: data["statusUpdate"] !== undefined ? serializeTaskStatusUpdateEvent(data["statusUpdate"]) : undefined, task: data["task"] !== undefined ? serializeTask(data["task"]) : undefined, }; } function deserializeStreamResponse(data: any): StreamResponse { return { ...data, artifactUpdate: data["artifactUpdate"] !== undefined ? deserializeTaskArtifactUpdateEvent(data["artifactUpdate"]) : undefined, message: data["message"] !== undefined ? deserializeMessage(data["message"]) : undefined, statusUpdate: data["statusUpdate"] !== undefined ? deserializeTaskStatusUpdateEvent(data["statusUpdate"]) : undefined, task: data["task"] !== undefined ? deserializeTask(data["task"]) : undefined, }; } /** * A subscription to receive events about a Google Workspace resource. To learn * more about subscriptions, see the [Google Workspace Events API * overview](https://developers.google.com/workspace/events). */ export interface Subscription { /** * Output only. The user who authorized the creation of the subscription. * When a user authorizes the subscription, this field and the * `user_authority` field have the same value and the format is: Format: * `users/{user}` For Google Workspace users, the `{user}` value is the * [`user.id`](https://developers.google.com/admin-sdk/directory/reference/rest/v1/users#User.FIELDS.ids) * field from the Directory API. When a Chat app authorizes the subscription, * only `service_account_authority` field populates and this field is empty. */ readonly authority?: string; /** * Output only. The time when the subscription is created. */ readonly createTime?: Date; /** * Optional. This checksum is computed by the server based on the value of * other fields, and might be sent on update requests to ensure the client has * an up-to-date value before proceeding. */ etag?: string; /** * Required. Unordered list. Input for creating a subscription. Otherwise, * output only. One or more types of events to receive about the target * resource. Formatted according to the CloudEvents specification. The * supported event types depend on the target resource of your subscription. * For details, see [Supported Google Workspace * events](https://developers.google.com/workspace/events/guides#supported-events). * By default, you also receive events about the [lifecycle of your * subscription](https://developers.google.com/workspace/events/guides/events-lifecycle). * You don't need to specify lifecycle events for this field. If you specify * an event type that doesn't exist for the target resource, the request * returns an HTTP `400 Bad Request` status code. */ eventTypes?: string[]; /** * Non-empty default. The timestamp in UTC when the subscription expires. * Always displayed on output, regardless of what was used on input. */ expireTime?: Date; /** * Identifier. Resource name of the subscription. Format: * `subscriptions/{subscription}` */ name?: string; /** * Required. Immutable. The endpoint where the subscription delivers events, * such as a Pub/Sub topic. */ notificationEndpoint?: NotificationEndpoint; /** * Optional. Options about what data to include in the event payload. Only * supported for Google Chat and Google Drive events. */ payloadOptions?: PayloadOptions; /** * Output only. If `true`, the subscription is in the process of being * updated. */ readonly reconciling?: boolean; /** * Output only. The state of the subscription. Determines whether the * subscription can receive events and deliver them to the notification * endpoint. */ readonly state?: | "STATE_UNSPECIFIED" | "ACTIVE" | "SUSPENDED" | "DELETED"; /** * Output only. The error that suspended the subscription. To reactivate the * subscription, resolve the error and call the `ReactivateSubscription` * method. */ readonly suspensionReason?: | "ERROR_TYPE_UNSPECIFIED" | "USER_SCOPE_REVOKED" | "RESOURCE_DELETED" | "USER_AUTHORIZATION_FAILURE" | "ENDPOINT_PERMISSION_DENIED" | "ENDPOINT_NOT_FOUND" | "ENDPOINT_RESOURCE_EXHAUSTED" | "OTHER"; /** * Required. Immutable. The Google Workspace resource that's monitored for * events, formatted as the [full resource * name](https://google.aip.dev/122#full-resource-names). To learn about * target resources and the events that they support, see [Supported Google * Workspace * events](https://developers.google.com/workspace/events#supported-events). A * user can only authorize your app to create one subscription for a given * target resource. If your app tries to create another subscription with the * same user credentials, the request returns an `ALREADY_EXISTS` error. */ targetResource?: string; /** * Input only. The time-to-live (TTL) or duration for the subscription. If * unspecified or set to `0`, uses the maximum possible duration. */ ttl?: number /* Duration */; /** * Output only. System-assigned unique identifier for the subscription. */ readonly uid?: string; /** * Output only. The last time that the subscription is updated. */ readonly updateTime?: Date; } function serializeSubscription(data: any): Subscription { return { ...data, expireTime: data["expireTime"] !== undefined ? data["expireTime"].toISOString() : undefined, payloadOptions: data["payloadOptions"] !== undefined ? serializePayloadOptions(data["payloadOptions"]) : undefined, ttl: data["ttl"] !== undefined ? data["ttl"] : undefined, }; } function deserializeSubscription(data: any): Subscription { return { ...data, createTime: data["createTime"] !== undefined ? new Date(data["createTime"]) : undefined, expireTime: data["expireTime"] !== undefined ? new Date(data["expireTime"]) : undefined, payloadOptions: data["payloadOptions"] !== undefined ? deserializePayloadOptions(data["payloadOptions"]) : undefined, ttl: data["ttl"] !== undefined ? data["ttl"] : undefined, updateTime: data["updateTime"] !== undefined ? new Date(data["updateTime"]) : undefined, }; } /** * Additional options for WorkspaceEvents#subscriptionsCreate. */ export interface SubscriptionsCreateOptions { /** * Optional. If set to `true`, validates and previews the request, but * doesn't create the subscription. */ validateOnly?: boolean; } /** * Additional options for WorkspaceEvents#subscriptionsDelete. */ export interface SubscriptionsDeleteOptions { /** * Optional. If set to `true` and the subscription isn't found, the request * succeeds but doesn't delete the subscription. */ allowMissing?: boolean; /** * Optional. Etag of the subscription. If present, it must match with the * server's etag. Otherwise, request fails with the status `ABORTED`. */ etag?: string; /** * Optional. If set to `true`, validates and previews the request, but * doesn't delete the subscription. */ validateOnly?: boolean; } /** * Additional options for WorkspaceEvents#subscriptionsList. */ export interface SubscriptionsListOptions { /** * Required. A query filter. You can filter subscriptions by event type * (`event_types`) and target resource (`target_resource`). You must specify * at least one event type in your query. To filter for multiple event types, * use the `OR` operator. To filter by both event type and target resource, * use the `AND` operator and specify the full resource name, such as * `//chat.googleapis.com/spaces/{space}`. For example, the following queries * are valid: ``` event_types:"google.workspace.chat.membership.v1.updated" OR * event_types:"google.workspace.chat.message.v1.created" * event_types:"google.workspace.chat.message.v1.created" AND * target_resource="//chat.googleapis.com/spaces/{space}" ( * event_types:"google.workspace.chat.membership.v1.updated" OR * event_types:"google.workspace.chat.message.v1.created" ) AND * target_resource="//chat.googleapis.com/spaces/{space}" ``` The server * rejects invalid queries with an `INVALID_ARGUMENT` error. */ filter?: string; /** * Optional. The maximum number of subscriptions to return. The service might * return fewer than this value. If unspecified or set to `0`, up to 50 * subscriptions are returned. The maximum value is 100. If you specify a * value more than 100, the system only returns 100 subscriptions. */ pageSize?: number; /** * Optional. A page token, received from a previous list subscriptions call. * Provide this parameter to retrieve the subsequent page. When paginating, * the filter value should match the call that provided the page token. * Passing a different value might lead to unexpected results. */ pageToken?: string; } /** * Additional options for WorkspaceEvents#subscriptionsPatch. */ export interface SubscriptionsPatchOptions { /** * Optional. The field to update. If omitted, updates any fields included in * the request. You can update one of the following fields in a subscription: * * `expire_time`: The timestamp when the subscription expires. * `ttl`: The * time-to-live (TTL) or duration of the subscription. * `event_types`: The * list of event types to receive about the target resource. When using the * `*` wildcard (equivalent to `PUT`), omitted fields are set to empty values * and rejected if they're invalid. */ updateMask?: string /* FieldMask */; /** * Optional. If set to `true`, validates and previews the request, but * doesn't update the subscription. */ validateOnly?: boolean; } function serializeSubscriptionsPatchOptions(data: any): SubscriptionsPatchOptions { return { ...data, updateMask: data["updateMask"] !== undefined ? data["updateMask"] : undefined, }; } function deserializeSubscriptionsPatchOptions(data: any): SubscriptionsPatchOptions { return { ...data, updateMask: data["updateMask"] !== undefined ? data["updateMask"] : undefined, }; } /** * Task is the core unit of action for A2A. It has a current status and when * results are created for the task they are stored in the artifact. If there * are multiple turns for a task, these are stored in history. */ export interface Task { /** * A set of output artifacts for a Task. */ artifacts?: Artifact[]; /** * Unique identifier (e.g. UUID) for the contextual collection of * interactions (tasks and messages). Created by the A2A server. */ contextId?: string; /** * protolint:disable REPEATED_FIELD_NAMES_PLURALIZED The history of * interactions from a task. */ history?: Message[]; /** * Unique identifier (e.g. UUID) for the task, generated by the server for a * new task. */ id?: string; /** * protolint:enable REPEATED_FIELD_NAMES_PLURALIZED A key/value object to * store custom metadata about a task. */ metadata?: { [key: string]: any }; /** * The current status of a Task, including state and a message. */ status?: TaskStatus; } function serializeTask(data: any): Task { return { ...data, artifacts: data["artifacts"] !== undefined ? data["artifacts"].map((item: any) => (serializeArtifact(item))) : undefined, history: data["history"] !== undefined ? data["history"].map((item: any) => (serializeMessage(item))) : undefined, status: data["status"] !== undefined ? serializeTaskStatus(data["status"]) : undefined, }; } function deserializeTask(data: any): Task { return { ...data, artifacts: data["artifacts"] !== undefined ? data["artifacts"].map((item: any) => (deserializeArtifact(item))) : undefined, history: data["history"] !== undefined ? data["history"].map((item: any) => (deserializeMessage(item))) : undefined, status: data["status"] !== undefined ? deserializeTaskStatus(data["status"]) : undefined, }; } /** * TaskArtifactUpdateEvent represents a task delta where an artifact has been * generated. */ export interface TaskArtifactUpdateEvent { /** * Whether this should be appended to a prior one produced */ append?: boolean; /** * The artifact itself */ artifact?: Artifact; /** * The id of the context that this task belongs too */ contextId?: string; /** * Whether this represents the last part of an artifact */ lastChunk?: boolean; /** * Optional metadata associated with the artifact update. */ metadata?: { [key: string]: any }; /** * The id of the task for this artifact */ taskId?: string; } function serializeTaskArtifactUpdateEvent(data: any): TaskArtifactUpdateEvent { return { ...data, artifact: data["artifact"] !== undefined ? serializeArtifact(data["artifact"]) : undefined, }; } function deserializeTaskArtifactUpdateEvent(data: any): TaskArtifactUpdateEvent { return { ...data, artifact: data["artifact"] !== undefined ? deserializeArtifact(data["artifact"]) : undefined, }; } export interface TaskPushNotificationConfig { /** * The resource name of the config. Format: * tasks/{task_id}/pushNotificationConfigs/{config_id} */ name?: string; /** * The push notification configuration details. */ pushNotificationConfig?: PushNotificationConfig; } /** * Additional options for WorkspaceEvents#tasksGet. */ export interface TasksGetOptions { /** * The number of most recent messages from the task's history to retrieve. */ historyLength?: number; /** * Optional tenant, provided as a path parameter. Experimental, might still * change for 1.0 release. */ tenant?: string; } /** * Additional options for WorkspaceEvents#tasksPushNotificationConfigsCreate. */ export interface TasksPushNotificationConfigsCreateOptions { /** * Required. The ID for the new config. */ configId?: string; /** * Optional tenant, provided as a path parameter. Experimental, might still * change for 1.0 release. */ tenant?: string; } /** * Additional options for WorkspaceEvents#tasksPushNotificationConfigsDelete. */ export interface TasksPushNotificationConfigsDeleteOptions { /** * Optional tenant, provided as a path parameter. Experimental, might still * change for 1.0 release. */ tenant?: string; } /** * Additional options for WorkspaceEvents#tasksPushNotificationConfigsGet. */ export interface TasksPushNotificationConfigsGetOptions { /** * Optional tenant, provided as a path parameter. Experimental, might still * change for 1.0 release. */ tenant?: string; } /** * Additional options for WorkspaceEvents#tasksPushNotificationConfigsList. */ export interface TasksPushNotificationConfigsListOptions { /** * For AIP-158 these fields are present. Usually not used/needed. The maximum * number of configurations to return. If unspecified, all configs will be * returned. */ pageSize?: number; /** * A page token received from a previous * ListTaskPushNotificationConfigRequest call. Provide this to retrieve the * subsequent page. When paginating, all other parameters provided to * `ListTaskPushNotificationConfigRequest` must match the call that provided * the page token. */ pageToken?: string; /** * Optional tenant, provided as a path parameter. Experimental, might still * change for 1.0 release. */ tenant?: string; } /** * Additional options for WorkspaceEvents#tasksSubscribe. */ export interface TasksSubscribeOptions { /** * Optional tenant, provided as a path parameter. Experimental, might still * change for 1.0 release. */ tenant?: string; } /** * A container for the status of a task */ export interface TaskStatus { /** * A message associated with the status. */ message?: Message; /** * The current state of this task */ state?: | "TASK_STATE_UNSPECIFIED" | "TASK_STATE_SUBMITTED" | "TASK_STATE_WORKING" | "TASK_STATE_COMPLETED" | "TASK_STATE_FAILED" | "TASK_STATE_CANCELLED" | "TASK_STATE_INPUT_REQUIRED" | "TASK_STATE_REJECTED" | "TASK_STATE_AUTH_REQUIRED"; /** * Timestamp when the status was recorded. Example: "2023-10-27T10:00:00Z" */ timestamp?: Date; } function serializeTaskStatus(data: any): TaskStatus { return { ...data, message: data["message"] !== undefined ? serializeMessage(data["message"]) : undefined, timestamp: data["timestamp"] !== undefined ? data["timestamp"].toISOString() : undefined, }; } function deserializeTaskStatus(data: any): TaskStatus { return { ...data, message: data["message"] !== undefined ? deserializeMessage(data["message"]) : undefined, timestamp: data["timestamp"] !== undefined ? new Date(data["timestamp"]) : undefined, }; } /** * TaskStatusUpdateEvent is a delta even on a task indicating that a task has * changed. */ export interface TaskStatusUpdateEvent { /** * The id of the context that the task belongs to */ contextId?: string; /** * Whether this is the last status update expected for this task. */ final?: boolean; /** * Optional metadata to associate with the task update. */ metadata?: { [key: string]: any }; /** * The new status of the task. */ status?: TaskStatus; /** * The id of the task that is changed */ taskId?: string; } function serializeTaskStatusUpdateEvent(data: any): TaskStatusUpdateEvent { return { ...data, status: data["status"] !== undefined ? serializeTaskStatus(data["status"]) : undefined, }; } function deserializeTaskStatusUpdateEvent(data: any): TaskStatusUpdateEvent { return { ...data, status: data["status"] !== undefined ? deserializeTaskStatus(data["status"]) : undefined, }; } function decodeBase64(b64: string): Uint8Array { const binString = atob(b64); const size = binString.length; const bytes = new Uint8Array(size); for (let i = 0; i < size; i++) { bytes[i] = binString.charCodeAt(i); } return bytes; } const base64abc = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"]; /** * CREDIT: https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727 * Encodes a given Uint8Array, ArrayBuffer or string into RFC4648 base64 representation * @param data */ function encodeBase64(uint8: Uint8Array): string { let result = "", i; const l = uint8.length; for (i = 2; i < l; i += 3) { result += base64abc[uint8[i - 2] >> 2]; result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)]; result += base64abc[((uint8[i - 1] & 0x0f) << 2) | (uint8[i] >> 6)]; result += base64abc[uint8[i] & 0x3f]; } if (i === l + 1) { // 1 octet yet to write result += base64abc[uint8[i - 2] >> 2]; result += base64abc[(uint8[i - 2] & 0x03) << 4]; result += "=="; } if (i === l) { // 2 octets yet to write result += base64abc[uint8[i - 2] >> 2]; result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)]; result += base64abc[(uint8[i - 1] & 0x0f) << 2]; result += "="; } return result; }