From 69c7fc240a8a14a6d1e636864dde5d32c85d862d Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Thu, 19 Dec 2024 03:54:19 +0000 Subject: [PATCH] CodeGen from PR 31549 in Azure/azure-rest-api-specs Merge 3fbf4d5d3696d0c2887f2fac0371059a1a8933bd into 96c44f99e15d99f1ae43a793f1845f912f664964 --- common/config/rush/pnpm-lock.yaml | 57 +- .../communication-messages-rest/CHANGELOG.md | 52 +- .../communication-messages-rest/LICENSE | 21 + .../communication-messages-rest/README.md | 216 +------ .../api-extractor.json | 6 +- .../communication-messages-rest/assets.json | 6 - .../eslint.config.mjs | 16 +- .../communication-messages-rest/package.json | 179 +++--- .../review/communication-messages.api.md | 162 ++++- .../communication-messages-rest/sample.env | 19 - .../samples-dev/DownloadMedia.ts | 31 - .../samples-dev/GetMessageTemplateList.ts | 42 -- .../samples-dev/SendAudioMessage.ts | 44 -- .../samples-dev/SendDocumentMessage.ts | 46 -- .../samples-dev/SendImageMessage.ts | 44 -- .../samples-dev/SendTemplateMessage.ts | 98 --- .../samples-dev/SendTextMessage.ts | 44 -- .../SendTextTemplateMessageUsingAAD.ts | 93 --- .../samples-dev/SendVideoMessage.ts | 45 -- .../samples/v1/javascript/DownloadMedia.js | 33 - .../v1/javascript/GetMessageTemplateList.js | 40 -- .../samples/v1/javascript/README.md | 57 -- .../samples/v1/javascript/SendMediaMessage.js | 43 -- .../v1/javascript/SendTemplateMessage.js | 89 --- .../samples/v1/javascript/SendTextMessage.js | 42 -- .../SendTextTemplateMessageUsingAAD.js | 91 --- .../samples/v1/javascript/package.json | 35 -- .../samples/v1/javascript/sample.env | 19 - .../samples/v1/typescript/README.md | 70 --- .../samples/v1/typescript/package.json | 44 -- .../samples/v1/typescript/sample.env | 19 - .../v1/typescript/src/DownloadMedia.ts | 31 - .../typescript/src/GetMessageTemplateList.ts | 40 -- .../v1/typescript/src/SendMediaMessage.ts | 45 -- .../v1/typescript/src/SendTemplateMessage.ts | 98 --- .../v1/typescript/src/SendTextMessage.ts | 45 -- .../src/SendTextTemplateMessageUsingAAD.ts | 92 --- .../samples/v1/typescript/tsconfig.json | 17 - .../samples/v2/javascript/DownloadMedia.js | 33 - .../v2/javascript/GetMessageTemplateList.js | 42 -- .../samples/v2/javascript/README.md | 76 --- .../samples/v2/javascript/SendAudioMessage.js | 44 -- .../v2/javascript/SendDocumentMessage.js | 45 -- .../samples/v2/javascript/SendImageMessage.js | 44 -- .../v2/javascript/SendTemplateMessage.js | 90 --- .../samples/v2/javascript/SendTextMessage.js | 43 -- .../SendTextTemplateMessageUsingAAD.js | 92 --- .../samples/v2/javascript/SendVideoMessage.js | 45 -- .../samples/v2/javascript/package.json | 35 -- .../samples/v2/javascript/sample.env | 19 - .../samples/v2/typescript/README.md | 89 --- .../samples/v2/typescript/package.json | 44 -- .../samples/v2/typescript/sample.env | 19 - .../v2/typescript/src/DownloadMedia.ts | 31 - .../typescript/src/GetMessageTemplateList.ts | 42 -- .../v2/typescript/src/SendAudioMessage.ts | 44 -- .../v2/typescript/src/SendDocumentMessage.ts | 46 -- .../v2/typescript/src/SendImageMessage.ts | 44 -- .../v2/typescript/src/SendTemplateMessage.ts | 98 --- .../v2/typescript/src/SendTextMessage.ts | 44 -- .../src/SendTextTemplateMessageUsingAAD.ts | 93 --- .../v2/typescript/src/SendVideoMessage.ts | 45 -- .../samples/v2/typescript/tsconfig.json | 17 - .../{generated/src => }/clientDefinitions.ts | 0 .../src/generated/src/index.ts | 15 - .../generated/src/messagesServiceClient.ts | 72 --- .../src/generated/src/paginateHelper.ts | 154 ----- .../communication-messages-rest/src/index.ts | 18 +- .../src/{generated/src => }/isUnexpected.ts | 0 .../src/{generated/src => }/logger.ts | 0 .../src/messagesServiceClient.ts | 101 +-- .../src/{generated/src => }/models.ts | 182 ++++++ .../src/{generated/src => }/outputModels.ts | 12 +- .../src/paginateHelper.ts | 297 +++++++++ .../src/{generated/src => }/parameters.ts | 0 .../src/{generated/src => }/responses.ts | 0 .../test/public/messageTest.spec.ts | 419 ------------- .../test/public/sampleTest.spec.ts | 21 + .../test/public/utils/env-browser.mts | 2 - .../test/public/utils/env.ts | 6 - .../test/public/utils/recordedClient.ts | 90 +-- .../communication-messages-rest/tests.yml | 16 - .../tsconfig.browser.config.json | 9 +- .../communication-messages-rest/tsconfig.json | 19 +- .../tsconfig.samples.json | 8 - .../tsconfig.src.json | 3 - .../tsconfig.test.json | 3 - .../tsp-location.yaml | 6 +- .../vitest.browser.config.ts | 44 +- .../vitest.config.ts | 39 +- .../vitest.esm.config.ts | 11 - .../baseline/review/index.ts | 443 +++++++++++++ .../current/review/index.ts | 585 ++++++++++++++++++ .../.tmp-breaking-change-detect/tsconfig.json | 17 + 94 files changed, 2065 insertions(+), 3962 deletions(-) create mode 100644 sdk/communication/communication-messages-rest/LICENSE delete mode 100644 sdk/communication/communication-messages-rest/assets.json delete mode 100644 sdk/communication/communication-messages-rest/sample.env delete mode 100644 sdk/communication/communication-messages-rest/samples-dev/DownloadMedia.ts delete mode 100644 sdk/communication/communication-messages-rest/samples-dev/GetMessageTemplateList.ts delete mode 100644 sdk/communication/communication-messages-rest/samples-dev/SendAudioMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples-dev/SendDocumentMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples-dev/SendImageMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples-dev/SendTemplateMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples-dev/SendTextMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples-dev/SendTextTemplateMessageUsingAAD.ts delete mode 100644 sdk/communication/communication-messages-rest/samples-dev/SendVideoMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/javascript/DownloadMedia.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/javascript/GetMessageTemplateList.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/javascript/README.md delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/javascript/SendMediaMessage.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/javascript/SendTemplateMessage.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/javascript/SendTextMessage.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/javascript/SendTextTemplateMessageUsingAAD.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/javascript/package.json delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/javascript/sample.env delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/typescript/README.md delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/typescript/package.json delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/typescript/sample.env delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/typescript/src/DownloadMedia.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/typescript/src/GetMessageTemplateList.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendMediaMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTemplateMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTextMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTextTemplateMessageUsingAAD.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v1/typescript/tsconfig.json delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/DownloadMedia.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/GetMessageTemplateList.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/README.md delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/SendAudioMessage.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/SendDocumentMessage.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/SendImageMessage.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/SendTemplateMessage.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/SendTextMessage.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/SendTextTemplateMessageUsingAAD.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/SendVideoMessage.js delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/package.json delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/javascript/sample.env delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/README.md delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/package.json delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/sample.env delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/src/DownloadMedia.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/src/GetMessageTemplateList.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendAudioMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendDocumentMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendImageMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTemplateMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTextMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTextTemplateMessageUsingAAD.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendVideoMessage.ts delete mode 100644 sdk/communication/communication-messages-rest/samples/v2/typescript/tsconfig.json rename sdk/communication/communication-messages-rest/src/{generated/src => }/clientDefinitions.ts (100%) delete mode 100644 sdk/communication/communication-messages-rest/src/generated/src/index.ts delete mode 100644 sdk/communication/communication-messages-rest/src/generated/src/messagesServiceClient.ts delete mode 100644 sdk/communication/communication-messages-rest/src/generated/src/paginateHelper.ts rename sdk/communication/communication-messages-rest/src/{generated/src => }/isUnexpected.ts (100%) rename sdk/communication/communication-messages-rest/src/{generated/src => }/logger.ts (100%) rename sdk/communication/communication-messages-rest/src/{generated/src => }/models.ts (57%) rename sdk/communication/communication-messages-rest/src/{generated/src => }/outputModels.ts (90%) create mode 100644 sdk/communication/communication-messages-rest/src/paginateHelper.ts rename sdk/communication/communication-messages-rest/src/{generated/src => }/parameters.ts (100%) rename sdk/communication/communication-messages-rest/src/{generated/src => }/responses.ts (100%) delete mode 100644 sdk/communication/communication-messages-rest/test/public/messageTest.spec.ts create mode 100644 sdk/communication/communication-messages-rest/test/public/sampleTest.spec.ts delete mode 100644 sdk/communication/communication-messages-rest/test/public/utils/env-browser.mts delete mode 100644 sdk/communication/communication-messages-rest/test/public/utils/env.ts delete mode 100644 sdk/communication/communication-messages-rest/tests.yml delete mode 100644 sdk/communication/communication-messages-rest/tsconfig.samples.json delete mode 100644 sdk/communication/communication-messages-rest/tsconfig.src.json delete mode 100644 sdk/communication/communication-messages-rest/tsconfig.test.json delete mode 100644 sdk/communication/communication-messages-rest/vitest.esm.config.ts create mode 100644 sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/baseline/review/index.ts create mode 100644 sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/current/review/index.ts create mode 100644 sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/tsconfig.json diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index e8d6a3df56f5..673c474019c1 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -3556,7 +3556,7 @@ packages: version: 0.0.0 '@rush-temp/communication-messages@file:projects/communication-messages.tgz': - resolution: {integrity: sha512-ReB7ZS3ys+VFPUzPcmiUQlhyqhaiR08drMVGcMcPYJMCfNmenW6+cZ1AzriNVY0CSio71MQyyh3WDJk/0Z3aPA==, tarball: file:projects/communication-messages.tgz} + resolution: {integrity: sha512-iTokfARn+j8j32u6ePJ5+hRBTJsqRebY49clBkg9RgsgOcIW1XuwY+Vc7dWg13BaaZ9XO5DqJNMl6bSFwPeLyQ==, tarball: file:projects/communication-messages.tgz} version: 0.0.0 '@rush-temp/communication-phone-numbers@file:projects/communication-phone-numbers.tgz': @@ -15844,16 +15844,15 @@ snapshots: '@rush-temp/communication-messages@file:projects/communication-messages.tgz(msw@2.6.8(@types/node@22.7.9)(typescript@5.7.2))(vite@5.4.11(@types/node@22.7.9))': dependencies: + '@microsoft/api-extractor': 7.48.0(@types/node@18.19.68) '@types/node': 18.19.68 - '@vitest/browser': 2.1.8(@types/node@18.19.68)(playwright@1.49.1)(typescript@5.7.2)(vite@5.4.11(@types/node@22.7.9))(vitest@2.1.8) + '@vitest/browser': 2.1.8(@types/node@18.19.68)(playwright@1.49.1)(typescript@5.6.3)(vite@5.4.11(@types/node@22.7.9))(vitest@2.1.8) '@vitest/coverage-istanbul': 2.1.8(vitest@2.1.8) - autorest: 3.7.1 dotenv: 16.4.7 eslint: 9.17.0 - karma-source-map-support: 1.4.0 playwright: 1.49.1 tslib: 2.8.1 - typescript: 5.7.2 + typescript: 5.6.3 vitest: 2.1.8(@types/node@18.19.68)(@vitest/browser@2.1.8)(msw@2.6.8(@types/node@22.7.9)(typescript@5.7.2)) transitivePeerDependencies: - '@edge-runtime/vm' @@ -20346,6 +20345,27 @@ snapshots: '@ungap/structured-clone@1.2.1': {} + '@vitest/browser@2.1.8(@types/node@18.19.68)(playwright@1.49.1)(typescript@5.6.3)(vite@5.4.11(@types/node@22.7.9))(vitest@2.1.8)': + dependencies: + '@testing-library/dom': 10.4.0 + '@testing-library/user-event': 14.5.2(@testing-library/dom@10.4.0) + '@vitest/mocker': 2.1.8(msw@2.6.8(@types/node@22.7.9)(typescript@5.7.2))(vite@5.4.11(@types/node@22.7.9)) + '@vitest/utils': 2.1.8 + magic-string: 0.30.15 + msw: 2.6.8(@types/node@18.19.68)(typescript@5.6.3) + sirv: 3.0.0 + tinyrainbow: 1.2.0 + vitest: 2.1.8(@types/node@22.7.9)(@vitest/browser@2.1.8)(msw@2.6.8(@types/node@22.7.9)(typescript@5.7.2)) + ws: 8.18.0 + optionalDependencies: + playwright: 1.49.1 + transitivePeerDependencies: + - '@types/node' + - bufferutil + - typescript + - utf-8-validate + - vite + '@vitest/browser@2.1.8(@types/node@18.19.68)(playwright@1.49.1)(typescript@5.7.2)(vite@5.4.11(@types/node@22.7.9))(vitest@2.1.8)': dependencies: '@testing-library/dom': 10.4.0 @@ -20490,7 +20510,7 @@ snapshots: ajv-formats@3.0.1: dependencies: - ajv: 8.13.0 + ajv: 8.17.1 ajv@6.12.6: dependencies: @@ -22718,6 +22738,31 @@ snapshots: ms@2.1.3: {} + msw@2.6.8(@types/node@18.19.68)(typescript@5.6.3): + dependencies: + '@bundled-es-modules/cookie': 2.0.1 + '@bundled-es-modules/statuses': 1.0.1 + '@bundled-es-modules/tough-cookie': 0.1.6 + '@inquirer/confirm': 5.1.0(@types/node@18.19.68) + '@mswjs/interceptors': 0.37.3 + '@open-draft/deferred-promise': 2.2.0 + '@open-draft/until': 2.1.0 + '@types/cookie': 0.6.0 + '@types/statuses': 2.0.5 + chalk: 4.1.2 + graphql: 16.9.0 + headers-polyfill: 4.0.3 + is-node-process: 1.2.0 + outvariant: 1.4.3 + path-to-regexp: 6.3.0 + strict-event-emitter: 0.5.1 + type-fest: 4.30.1 + yargs: 17.7.2 + optionalDependencies: + typescript: 5.6.3 + transitivePeerDependencies: + - '@types/node' + msw@2.6.8(@types/node@18.19.68)(typescript@5.7.2): dependencies: '@bundled-es-modules/cookie': 2.0.1 diff --git a/sdk/communication/communication-messages-rest/CHANGELOG.md b/sdk/communication/communication-messages-rest/CHANGELOG.md index ac44489bd566..f6681f71817e 100644 --- a/sdk/communication/communication-messages-rest/CHANGELOG.md +++ b/sdk/communication/communication-messages-rest/CHANGELOG.md @@ -1,49 +1,15 @@ # Release History - -## 2.0.1 (Unreleased) - -### Features Added - -### Breaking Changes - -### Bugs Fixed - -### Other Changes - -## 2.0.0 (2024-10-23) - + +## 3.0.0-beta.1 (2024-12-19) +Compared with version 2.0.0 + ### Features Added -- Added ImageNotificationContent to send image messgae. -- Added DocumentNotificationContent to send document message. -- Added VideoNotificationContent to send video message. -- Added AudioNotificationContent to send audio message. -- Deprecated MediaNotificationContent. + - Added Interface PagedAsyncIterableIterator + - Added Interface PageSettings ### Breaking Changes -- MediaNotificationContent interface kind field is update with value "image_v0" from "image". - -## 1.0.1 (2024-03-07) - -Using MessagesServiceClient: - -- Send WhatsApp messages. -- Get Template List. -- Download media file from WhatsApp server for incoming media message. - -### Other Changes - -- Fixed CI pipeline to publish MS doc. - -## 1.0.0 (2024-02-29) - -### Features Added - -This is the initial release of the @azure-rest version of Azure Communication Messages Services. - -Using MessagesServiceClient: - -- Send WhatsApp messages. -- Get Template List. -- Download media file from WhatsApp server for incoming media message. + - Removed function overload "function createClient(connectionString: string, options?: ClientOptions): MessagesServiceClient;" + - Removed Type Alias PagedMessageTemplateItemOutput + diff --git a/sdk/communication/communication-messages-rest/LICENSE b/sdk/communication/communication-messages-rest/LICENSE new file mode 100644 index 000000000000..7d5934740965 --- /dev/null +++ b/sdk/communication/communication-messages-rest/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/communication/communication-messages-rest/README.md b/sdk/communication/communication-messages-rest/README.md index a0f02d124cba..deb25ecd23bf 100644 --- a/sdk/communication/communication-messages-rest/README.md +++ b/sdk/communication/communication-messages-rest/README.md @@ -1,22 +1,24 @@ # Azure CommunicationMessages REST client library for JavaScript -This package contains a JavaScript SDK for Azure Communication Messages Services. +Azure Communication Messages Service + +**Please rely heavily on our [REST client docs](https://github.com/Azure/azure-sdk-for-js/blob/main/documentation/rest-clients.md) to use this library** Key links: -- [Quick Start][azure_communication_messaging_qs] +- [Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-messages-rest) +- [Package (NPM)](https://www.npmjs.com/package/@azure-rest/communication-messages) +- [API reference documentation](https://docs.microsoft.com/javascript/api/@azure-rest/communication-messages?view=azure-node-preview) ## Getting started ### Currently supported environments -- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule) +- LTS versions of Node.js ### Prerequisites -- You must have an [Azure subscription][azure_sub] to use this package. -- An existing Communication Services resource. If you need to create the resource, you can use the [Azure Portal][azure_portal], the [Azure PowerShell][azure_powershell], or the [Azure CLI][azure_cli]. -- See [how to register whatsapp business account & create a channel][register_whatsapp_business_account] for registering whatsapp channel to your Communication Services resource. +- You must have an [Azure subscription](https://azure.microsoft.com/free/) to use this package. ### Install the `@azure-rest/communication-messages` package @@ -26,179 +28,17 @@ Install the Azure CommunicationMessages REST client REST client library for Java npm install @azure-rest/communication-messages ``` -## Authentication - -You can get a key and/or connection string from your Communication Services resource in [Azure Portal][azure_portal]. Once you have a key, you may authenticate with any of the following methods: - -### Using a connection string - -```typescript -import MessageClient, { MessagesServiceClient } from "@azure-rest/communication-messages"; - -const connectionString = `endpoint=https://.communication.azure.com/;accessKey=`; -const client: MessagesServiceClient = MessageClient(connectionString); -``` - -### Using `AzureKeyCredential` - -```typescript -import { AzureKeyCredential } from "@azure/core-auth"; -import MessageClient, { MessagesServiceClient } from "@azure-rest/communication-messages"; - -const endpoint = "https://.communication.azure.com"; -const credential = new AzureKeyCredential(""); -const client: MessagesServiceClient = MessageClient(endpoint, credential); -``` - -### Using Azure Active Directory managed identity - -Client API key authentication is used in most of the examples, but you can also authenticate with Azure Active Directory using the [Azure Identity library][azure_identity]. To use the [DefaultAzureCredential][defaultazurecredential] provider shown below, or other credential providers provided with the Azure SDK, please install the [`@azure/identity`][azure_identity] package: - -```bash -npm install @azure/identity -``` - -The [`@azure/identity`][azure_identity] package provides a variety of credential types that your application can use to do this. The README for @azure/identity provides more details and samples to get you started. -AZURE_CLIENT_SECRET, AZURE_CLIENT_ID and AZURE_TENANT_ID environment variables are needed to create a DefaultAzureCredential object. - -```typescript -import { DefaultAzureCredential } from "@azure/identity"; -import MessageClient, { MessagesServiceClient } from "@azure-rest/communication-messages"; +### Create and authenticate a `MessagesServiceClient` -const endpoint = "https://.communication.azure.com"; -const credential = new DefaultAzureCredential(); -const client: MessagesServiceClient = MessageClient(endpoint, credential); -``` +To use an [Azure Active Directory (AAD) token credential](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-a-pre-fetched-access-token), +provide an instance of the desired credential type obtained from the +[@azure/identity](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#credentials) library. -## Send a Template Message with WhatsApp Channel +To authenticate with AAD, you must first `npm` install [`@azure/identity`](https://www.npmjs.com/package/@azure/identity) -`Note: Business always starts the conversation with a template message.` - -To send an Template Message, you need add template to your WhatsApp Bussiness Account. For more detail on WhatsApp Template, refer [Create and Manage Templates][create-manage-whatsapp-template]. In below example, we are using - -``` - Template Name: sample_issue_resolution - Template Language: en_US - - Template Body: "Hi {{1}}, were we able to solve the issue that you were facing?" - - With Quick Action Button (Yes, No) - -``` - -```typescript -const nameValue: MessageTemplateValue = { - kind: "text", - name: "name", - text: "Arif", -}; - -const yesAction: MessageTemplateValue = { - kind: "quickAction", - name: "Yes", - payload: "Yes", -}; - -const noAction: MessageTemplateValue = { - kind: "quickAction", - name: "No", - payload: "No", -}; - -const templateBindings: MessageTemplateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "name", - }, - ], - buttons: [ - { - subType: "quickReply", - refValue: "Yes", - }, - { - subType: "quickReply", - refValue: "No", - }, - ], -}; - -const template: MessageTemplate = { - name: "sample_issue_resolution", - language: "en_US", - bindings: templateBindings, - values: [nameValue, yesAction, noAction], -}; - -const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: "", - to: [""], - kind: "template", - template: template, - }, -}); -if (result.status === "202") { - const response: Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} else { - throw new Error("Failed to send message"); -} -``` - -## Send a Text Message with WhatsApp Channel - -`Note: Business can't start a conversation with a text message. It needs to be user initiated.` - -```typescript -const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: "", - to: [""], - kind: "text", - content: "Hello World!!", - }, -}); - -if (result.status === "202") { - const response: Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} else { - throw new Error("Failed to send message"); -} -``` - -## Send a Media Message with WhatsApp Channel - -`Note: Business can't start a conversation with a media message. It needs to be user initiated.` - -```typescript -const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: "", - to: [""], - kind: "image", - mediaUri: "https://", - }, -}); - -if (result.status === "202") { - const response: Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} else { - throw new Error("Failed to send message"); -} -``` +After setup, you can choose which type of [credential](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#credentials) from `@azure/identity` to use. +As an example, [DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential) +can be used to authenticate the client. ## Troubleshooting @@ -213,27 +53,3 @@ setLogLevel("info"); ``` For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger). - -## Next steps - -Please take a look at the [samples](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples) directory for detailed examples on how to use this library. - -## Contributing - -If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code. - -## Related projects - -- [Microsoft Azure SDK for Javascript](https://github.com/Azure/azure-sdk-for-js) - -[azure_cli]: https://learn.microsoft.com/cli/azure -[azure_sub]: https://azure.microsoft.com/free/ -[azure_portal]: https://portal.azure.com -[azure_powershell]: https://learn.microsoft.com/powershell/module/az.communication/new-azcommunicationservice -[defaultazurecredential]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential -[azure_identity]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity -[azure_communication_messaging_qs]: https://learn.microsoft.com/azure/communication-services/concepts/advanced-messaging/whatsapp/whatsapp-overview -[register_whatsapp_business_account]: https://learn.microsoft.com/azure/communication-services/quickstarts/advanced-messaging/whatsapp/connect-whatsapp-business-account -[create-manage-whatsapp-template]: https://developers.facebook.com/docs/whatsapp/business-management-api/message-templates/ - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fcommunication%2Fcommunication-sms%2FREADME.png) diff --git a/sdk/communication/communication-messages-rest/api-extractor.json b/sdk/communication/communication-messages-rest/api-extractor.json index b5983fcc4f78..b0b49d2b0f9d 100644 --- a/sdk/communication/communication-messages-rest/api-extractor.json +++ b/sdk/communication/communication-messages-rest/api-extractor.json @@ -1,6 +1,6 @@ { "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", - "mainEntryPointFilePath": "dist/esm/index.d.ts", + "mainEntryPointFilePath": "./dist/esm/index.d.ts", "docModel": { "enabled": true }, @@ -11,7 +11,7 @@ "dtsRollup": { "enabled": true, "untrimmedFilePath": "", - "publicTrimmedFilePath": "dist/communication-messages.d.ts" + "publicTrimmedFilePath": "./types/communication-messages.d.ts" }, "messages": { "tsdocMessageReporting": { @@ -28,4 +28,4 @@ } } } -} +} \ No newline at end of file diff --git a/sdk/communication/communication-messages-rest/assets.json b/sdk/communication/communication-messages-rest/assets.json deleted file mode 100644 index 1ff533867d26..000000000000 --- a/sdk/communication/communication-messages-rest/assets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "AssetsRepo": "Azure/azure-sdk-assets", - "AssetsRepoPrefixPath": "js", - "TagPrefix": "js/communication/communication-messages-rest", - "Tag": "js/communication/communication-messages-rest_2ccfd5f35e" -} diff --git a/sdk/communication/communication-messages-rest/eslint.config.mjs b/sdk/communication/communication-messages-rest/eslint.config.mjs index 93359ab21816..113bdc3eaf5f 100644 --- a/sdk/communication/communication-messages-rest/eslint.config.mjs +++ b/sdk/communication/communication-messages-rest/eslint.config.mjs @@ -1,9 +1,17 @@ import azsdkEslint from "@azure/eslint-plugin-azure-sdk"; -export default azsdkEslint.config([ +export default [ + ...azsdkEslint.configs.recommended, { rules: { - "@azure/azure-sdk/ts-modules-only-named": "warn" + "@azure/azure-sdk/ts-modules-only-named": "warn", + "@azure/azure-sdk/ts-apiextractor-json-types": "warn", + "@azure/azure-sdk/ts-package-json-types": "warn", + "@azure/azure-sdk/ts-package-json-engine-is-present": "warn", + "@azure/azure-sdk/ts-package-json-module": "off", + "@azure/azure-sdk/ts-package-json-files-required": "off", + "@azure/azure-sdk/ts-package-json-main-is-cjs": "off", + "tsdoc/syntax": "warn" } - }, -]); + } +]; diff --git a/sdk/communication/communication-messages-rest/package.json b/sdk/communication/communication-messages-rest/package.json index d765002130e2..d2e8bba0102d 100644 --- a/sdk/communication/communication-messages-rest/package.json +++ b/sdk/communication/communication-messages-rest/package.json @@ -1,9 +1,28 @@ { "name": "@azure-rest/communication-messages", - "sdk-type": "client", - "author": "Microsoft Corporation", - "version": "2.0.1", + "version": "3.0.0-beta.1", "description": "Azure client library for Azure Communication Messages services", + "engines": { + "node": ">=18.0.0" + }, + "sideEffects": false, + "autoPublish": false, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + }, + "dialects": [ + "esm", + "commonjs" + ], + "esmDialects": [ + "browser", + "react-native" + ], + "selfLink": false + }, + "type": "module", "keywords": [ "node", "azure", @@ -12,113 +31,77 @@ "browser", "isomorphic" ], + "author": "Microsoft Corporation", "license": "MIT", - "main": "./dist/commonjs/index.js", - "module": "./dist/esm/index.js", - "types": "./dist/commonjs/index.d.ts", - "repository": "github:Azure/azure-sdk-for-js", - "bugs": { - "url": "https://github.com/Azure/azure-sdk-for-js/issues" - }, "files": [ - "dist/", + "dist", "README.md", - "LICENSE" + "LICENSE", + "review/*", + "CHANGELOG.md" ], - "engines": { - "node": ">=18.0.0" + "sdk-type": "client", + "repository": "github:Azure/azure-sdk-for-js", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" }, - "scripts": { - "build": "npm run clean && dev-tool run build-package && dev-tool run extract-api", - "build:browser": "dev-tool run build-package && dev-tool run vendored cross-env ONLY_BROWSER=true rollup -c 2>&1", - "build:debug": "dev-tool run build-package && dev-tool run bundle && dev-tool run extract-api", - "build:node": "dev-tool run build-package && dev-tool run vendored cross-env ONLY_NODE=true rollup -c 2>&1", - "build:samples": "echo skipped.", - "build:test": "dev-tool run build-package && dev-tool run bundle", - "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"test/**/*.ts\"", - "clean": "dev-tool run vendored rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz *.log", - "execute:samples": "echo skipped", - "extract-api": "dev-tool run vendored rimraf review && dev-tool run vendored mkdirp ./review && dev-tool run extract-api", - "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"test/**/*.ts\"", - "generate:client": "echo skipped", - "integration-test": "npm run integration-test:node && npm run integration-test:browser", - "integration-test:browser": "dev-tool run test:browser", - "integration-test:node": "dev-tool run test:vitest --esm", - "lint": "eslint package.json api-extractor.json src test", - "lint:fix": "eslint package.json api-extractor.json src test --fix --fix-type [problem,suggestion]", - "pack": "npm pack 2>&1", - "test": "npm run clean && npm run build:test && npm run unit-test", - "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser", - "test:node": "npm run clean && npm run build:test && npm run unit-test:node", - "unit-test": "npm run unit-test:node && npm run unit-test:browser", - "unit-test:browser": "npm run clean && dev-tool run build-package && dev-tool run build-test && dev-tool run test:vitest --browser", - "unit-test:node": "dev-tool run test:vitest", - "update-snippets": "echo skipped" + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-messages-rest/README.md", + "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", + "//metadata": { + "constantPaths": [ + { + "path": "src/messagesServiceClient.ts", + "prefix": "userAgentInfo" + } + ] }, - "sideEffects": false, - "autoPublish": false, "dependencies": { "@azure-rest/core-client": "^2.3.1", - "@azure/communication-common": "^2.3.1", "@azure/core-auth": "^1.6.0", - "@azure/core-paging": "^1.5.0", - "@azure/core-rest-pipeline": "^1.12.0", - "@azure/core-util": "^1.7.0", + "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", - "tslib": "^2.2.0" + "tslib": "^2.6.2" }, "devDependencies": { - "@azure-tools/test-credential": "^2.0.0", - "@azure-tools/test-recorder": "^4.1.0", - "@azure-tools/test-utils-vitest": "^1.0.0", - "@azure/dev-tool": "^1.0.0", - "@azure/eslint-plugin-azure-sdk": "^3.0.0", - "@azure/identity": "^4.2.1", - "@types/node": "^18.0.0", - "@vitest/browser": "^2.1.5", - "@vitest/coverage-istanbul": "^2.1.5", - "autorest": "latest", "dotenv": "^16.0.0", + "@microsoft/api-extractor": "^7.40.3", + "@types/node": "^18.0.0", "eslint": "^9.9.0", - "karma-source-map-support": "~1.4.0", - "playwright": "^1.48.2", - "typescript": "~5.7.2", - "vitest": "^2.1.5" - }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-messages-rest-rest/README.md", - "//metadata": { - "constantPaths": [ - { - "path": "src/messagesServiceClient.ts", - "prefix": "userAgentInfo" - } - ] - }, - "browser": "./dist/browser/index.js", - "//sampleConfiguration": { - "productName": "Azure client library for Azure Communication Messages Services", - "productSlugs": [ - "azure", - "azure-communication-services" - ], - "apiRefLink": "https://learn.microsoft.com/javascript/api/overview/azure/communication-messages-rest-readme?view=azure-node-latest" + "typescript": "~5.6.2", + "@azure/identity": "^4.2.1", + "@vitest/browser": "^2.0.5", + "@vitest/coverage-istanbul": "^2.0.5", + "playwright": "^1.41.2", + "vitest": "^2.0.5", + "@azure-tools/test-credential": "^2.0.0", + "@azure-tools/test-recorder": "^4.0.0", + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0" }, - "type": "module", - "tshy": { - "exports": { - "./package.json": "./package.json", - ".": "./src/index.ts" - }, - "dialects": [ - "esm", - "commonjs" - ], - "esmDialects": [ - "browser", - "react-native" - ], - "selfLink": false, - "project": "./tsconfig.src.json" + "scripts": { + "clean": "dev-tool run vendored rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz *.log", + "extract-api": "dev-tool run vendored rimraf review && dev-tool run vendored mkdirp ./review && dev-tool run extract-api", + "pack": "npm pack 2>&1", + "lint": "eslint package.json api-extractor.json src test", + "lint:fix": "eslint package.json api-extractor.json src test --fix --fix-type [problem,suggestion]", + "unit-test": "npm run unit-test:node && npm run unit-test:browser", + "unit-test:browser": "npm run build:test && dev-tool run test:vitest --browser", + "unit-test:node": "dev-tool run test:vitest", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "integration-test:browser": "echo skipped", + "integration-test:node": "echo skipped", + "build:samples": "echo skipped", + "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\" ", + "execute:samples": "echo skipped", + "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\" ", + "generate:client": "echo skipped", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", + "minify": "dev-tool run vendored uglifyjs -c -m --comments --source-map \"content='./dist/index.js.map'\" -o ./dist/index.min.js ./dist/index.js", + "build:test": "npm run clean && dev-tool run build-package && dev-tool run build-test", + "build": "npm run clean && dev-tool run build-package && dev-tool run vendored mkdirp ./review && dev-tool run extract-api", + "test:node": "npm run clean && dev-tool run build-package && npm run unit-test:node && npm run integration-test:node", + "test": "npm run clean && dev-tool run build-package && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test", + "update-snippets": "echo skipped" }, "exports": { "./package.json": "./package.json", @@ -140,5 +123,7 @@ "default": "./dist/commonjs/index.js" } } - } -} + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts" +} \ No newline at end of file diff --git a/sdk/communication/communication-messages-rest/review/communication-messages.api.md b/sdk/communication/communication-messages-rest/review/communication-messages.api.md index 726e335bf7d6..91025bf795d3 100644 --- a/sdk/communication/communication-messages-rest/review/communication-messages.api.md +++ b/sdk/communication/communication-messages-rest/review/communication-messages.api.md @@ -8,15 +8,42 @@ import { Client } from '@azure-rest/core-client'; import { ClientOptions } from '@azure-rest/core-client'; import { ErrorResponse } from '@azure-rest/core-client'; import { HttpResponse } from '@azure-rest/core-client'; -import type { KeyCredential } from '@azure/core-auth'; -import { Paged } from '@azure/core-paging'; -import { PagedAsyncIterableIterator } from '@azure/core-paging'; +import { KeyCredential } from '@azure/core-auth'; import { PathUncheckedResponse } from '@azure-rest/core-client'; import { RawHttpHeaders } from '@azure/core-rest-pipeline'; import { RawHttpHeadersInput } from '@azure/core-rest-pipeline'; import { RequestParameters } from '@azure-rest/core-client'; import { StreamableMethod } from '@azure-rest/core-client'; -import type { TokenCredential } from '@azure/core-auth'; +import { TokenCredential } from '@azure/core-auth'; + +// @public +export type ActionBindings = ActionBindingsParent | WhatsAppListActionBindings | WhatsAppButtonActionBindings | WhatsAppUrlActionBindings; + +// @public +export interface ActionBindingsParent { + // (undocumented) + kind: MessageActionBindingKind; +} + +// @public +export interface ActionGroup { + items: Array; + title: string; +} + +// @public +export interface ActionGroupContent extends MessageContentParent { + groups: Array; + kind: "group"; + title: string; +} + +// @public +export interface ActionGroupItem { + description: string; + id: string; + title: string; +} // @public export interface AudioNotificationContent extends NotificationContentParent { @@ -24,6 +51,18 @@ export interface AudioNotificationContent extends NotificationContentParent { mediaUri: string; } +// @public +export interface ButtonContent { + id: string; + title: string; +} + +// @public +export interface ButtonSetContent extends MessageContentParent { + buttons: Array; + kind: "buttonSet"; +} + // @public export type CommunicationMessageKind = string; @@ -31,11 +70,14 @@ export type CommunicationMessageKind = string; export type CommunicationMessagesChannelOutput = string; // @public -function createClient(connectionString: string, options?: ClientOptions): MessagesServiceClient; +function createClient(endpointParam: string, credentials: TokenCredential | KeyCredential, { apiVersion, ...options }?: MessagesServiceClientOptions): MessagesServiceClient; +export default createClient; // @public -function createClient(endpoint: string, credential: KeyCredential | TokenCredential, options?: ClientOptions): MessagesServiceClient; -export default createClient; +export interface DocumentMessageContent extends MessageContentParent { + kind: "document"; + mediaUri: string; +} // @public export interface DocumentNotificationContent extends NotificationContentParent { @@ -98,11 +140,17 @@ export interface GetMediaHeaders { export type GetMediaParameters = GetMediaHeaderParam & RequestParameters; // @public -export type GetPage = (pageLink: string, maxPageSize?: number) => Promise<{ +export type GetPage = (pageLink: string) => Promise<{ page: TPage; nextPageLink?: string; }>; +// @public +export interface ImageMessageContent extends MessageContentParent { + kind: "image"; + mediaUri: string; +} + // @public export interface ImageNotificationContent extends NotificationContentParent { caption?: string; @@ -110,6 +158,20 @@ export interface ImageNotificationContent extends NotificationContentParent { mediaUri: string; } +// @public +export interface InteractiveMessage { + action: ActionBindings; + body: TextMessageContent; + footer?: TextMessageContent; + header?: MessageContent; +} + +// @public +export interface InteractiveNotificationContent extends NotificationContentParent { + interactiveMessage: InteractiveMessage; + kind: "interactive"; +} + // @public (undocumented) export function isUnexpected(response: GetMedia200Response | GetMediaDefaultResponse): response is GetMediaDefaultResponse; @@ -119,6 +181,13 @@ export function isUnexpected(response: Send202Response | SendDefaultResponse): r // @public (undocumented) export function isUnexpected(response: ListTemplates200Response | ListTemplatesDefaultResponse): response is ListTemplatesDefaultResponse; +// @public +export interface LinkContent extends MessageContentParent { + kind: "url"; + title: string; + url: string; +} + // @public (undocumented) export interface ListTemplates { get(options?: ListTemplatesParameters): StreamableMethod; @@ -186,6 +255,21 @@ export interface MediaNotificationContent extends NotificationContentParent { mediaUri: string; } +// @public +export type MessageActionBindingKind = string; + +// @public +export type MessageContent = MessageContentParent | TextMessageContent | DocumentMessageContent | ImageMessageContent | VideoMessageContent | ButtonSetContent | LinkContent | ActionGroupContent; + +// @public +export type MessageContentKind = string; + +// @public +export interface MessageContentParent { + // (undocumented) + kind: MessageContentKind; +} + // @public export interface MessageReceiptOutput { messageId: string; @@ -297,7 +381,7 @@ export interface MessageTemplateVideo extends MessageTemplateValueParent { } // @public -export type NotificationContent = NotificationContentParent | TextNotificationContent | MediaNotificationContent | ImageNotificationContent | DocumentNotificationContent | VideoNotificationContent | AudioNotificationContent | TemplateNotificationContent; +export type NotificationContent = NotificationContentParent | TextNotificationContent | MediaNotificationContent | ImageNotificationContent | DocumentNotificationContent | VideoNotificationContent | AudioNotificationContent | ReactionNotificationContent | StickerNotificationContent | InteractiveNotificationContent | TemplateNotificationContent; // @public export interface NotificationContentParent { @@ -308,7 +392,22 @@ export interface NotificationContentParent { } // @public -export type PagedMessageTemplateItemOutput = Paged; +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator; + next(): Promise>; +} + +// @public +export interface PagedMessageTemplateItemOutput { + nextLink?: string; + value: Array; +} + +// @public +export interface PageSettings { + continuationToken?: string; +} // @public export function paginate(client: Client, initialResponse: TResponse, options?: PagingOptions): PagedAsyncIterableIterator>; @@ -325,6 +424,13 @@ export interface PagingOptions { customGetPage?: GetPage[]>; } +// @public +export interface ReactionNotificationContent extends NotificationContentParent { + emoji: string; + kind: "reaction"; + messageId: string; +} + // @public export type RepeatabilityResultOutput = "accepted" | "rejected"; @@ -397,18 +503,36 @@ export interface SendMessageResultOutput { // @public (undocumented) export type SendParameters = SendHeaderParam & SendBodyParam & RequestParameters; +// @public +export interface StickerNotificationContent extends NotificationContentParent { + kind: "sticker"; + mediaUri: string; +} + // @public export interface TemplateNotificationContent extends NotificationContentParent { kind: "template"; template: MessageTemplate; } +// @public +export interface TextMessageContent extends MessageContentParent { + kind: "text"; + text: string; +} + // @public export interface TextNotificationContent extends NotificationContentParent { content: string; kind: "text"; } +// @public +export interface VideoMessageContent extends MessageContentParent { + kind: "video"; + mediaUri: string; +} + // @public export interface VideoNotificationContent extends NotificationContentParent { caption?: string; @@ -416,6 +540,18 @@ export interface VideoNotificationContent extends NotificationContentParent { mediaUri: string; } +// @public +export interface WhatsAppButtonActionBindings extends ActionBindingsParent { + content: ButtonSetContent; + kind: "whatsAppButtonAction"; +} + +// @public +export interface WhatsAppListActionBindings extends ActionBindingsParent { + content: ActionGroupContent; + kind: "whatsAppListAction"; +} + // @public export type WhatsAppMessageButtonSubType = string; @@ -445,6 +581,12 @@ export interface WhatsAppMessageTemplateItemOutput extends MessageTemplateItemOu kind: "whatsApp"; } +// @public +export interface WhatsAppUrlActionBindings extends ActionBindingsParent { + content: LinkContent; + kind: "whatsAppUrlAction"; +} + // (No @packageDocumentation comment for this package) ``` diff --git a/sdk/communication/communication-messages-rest/sample.env b/sdk/communication/communication-messages-rest/sample.env deleted file mode 100644 index 56051dfffe19..000000000000 --- a/sdk/communication/communication-messages-rest/sample.env +++ /dev/null @@ -1,19 +0,0 @@ -# Used in most samples. Retrieve these values from a Communication Services instance -# in the Azure Portal. -COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING="endpoint=https://.communication.azure.net/;accessKey=" - -ACS_URL="https://.communication.azure.net" -ACS_ACCESS_KEY="" - -# The client ID of an Azure Active Directory application. -AZURE_CLIENT_ID="" -# The client secret of an Azure Active Directory application. -AZURE_CLIENT_SECRET="" -#The Tenant ID of your organization in Azure Active Directory. -AZURE_TENANT_ID="" - -# The Channel Id -CHANNEL_ID="" - -# Comma separated list of phone numbers to receive SMS messages -RECIPIENT_PHONE_NUMBER="" diff --git a/sdk/communication/communication-messages-rest/samples-dev/DownloadMedia.ts b/sdk/communication/communication-messages-rest/samples-dev/DownloadMedia.ts deleted file mode 100644 index d2e4454bdd2b..000000000000 --- a/sdk/communication/communication-messages-rest/samples-dev/DownloadMedia.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Download a media file - */ - -import NotificationClient from "@azure-rest/communication-messages"; -import { AzureKeyCredential } from "@azure/core-auth"; -import * as fs from "node:fs"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Downloading..."); - await client.path("/messages/streams/{id}", "").get() - .asNodeStream().then((resp) => { - resp.body?.pipe(fs.createWriteStream("downloadedMedia.jpeg")); - return; - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples-dev/GetMessageTemplateList.ts b/sdk/communication/communication-messages-rest/samples-dev/GetMessageTemplateList.ts deleted file mode 100644 index 8460fc9f3056..000000000000 --- a/sdk/communication/communication-messages-rest/samples-dev/GetMessageTemplateList.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Get Template list for a channel - */ - -import { isUnexpected, paginate } from "@azure-rest/communication-messages"; -import MessageTemplateClient from "@azure-rest/communication-messages"; -import { AzureKeyCredential } from "@azure/core-auth"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = MessageTemplateClient(endpoint, credential); - console.log("Fetch Templates..."); - const response = await client.path("/messages/channels/{channelId}/templates", process.env.CHANNEl_ID || "") - .get({ - queryParameters: { maxPageSize: 2 } - }); - - if(isUnexpected(response)) { - throw new Error("Failed to get template for the channel."); - } - - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(client, response); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(JSON.stringify(item, null, 2)); - } -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples-dev/SendAudioMessage.ts b/sdk/communication/communication-messages-rest/samples-dev/SendAudioMessage.ts deleted file mode 100644 index d0cdd3a156fb..000000000000 --- a/sdk/communication/communication-messages-rest/samples-dev/SendAudioMessage.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a audio message - */ - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { isUnexpected, Send202Response } from "@azure-rest/communication-messages"; -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "audio", - mediaUri: "https://sample-videos.com/audio/mp3/wave.mp3" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples-dev/SendDocumentMessage.ts b/sdk/communication/communication-messages-rest/samples-dev/SendDocumentMessage.ts deleted file mode 100644 index 3f8a98d48ff1..000000000000 --- a/sdk/communication/communication-messages-rest/samples-dev/SendDocumentMessage.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a document message - */ - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { isUnexpected, Send202Response } from "@azure-rest/communication-messages"; -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "document", - mediaUri: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", - caption: "important!!" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); - -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples-dev/SendImageMessage.ts b/sdk/communication/communication-messages-rest/samples-dev/SendImageMessage.ts deleted file mode 100644 index 52e13c023928..000000000000 --- a/sdk/communication/communication-messages-rest/samples-dev/SendImageMessage.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send an image message - */ - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { isUnexpected, Send202Response } from "@azure-rest/communication-messages"; -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "image", - mediaUri: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples-dev/SendTemplateMessage.ts b/sdk/communication/communication-messages-rest/samples-dev/SendTemplateMessage.ts deleted file mode 100644 index 8b60e3b70d47..000000000000 --- a/sdk/communication/communication-messages-rest/samples-dev/SendTemplateMessage.ts +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a template message - */ - - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { - MessagesServiceClient, - Send202Response, - MessageTemplate, - MessageTemplateValue, - MessageTemplateBindings, - isUnexpected, -} from "@azure-rest/communication-messages"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client:MessagesServiceClient = NotificationClient(endpoint, credential); - - const nameValue:MessageTemplateValue = { - kind: "text", - name: "name", - text: "Arif" - }; - - const yesAction: MessageTemplateValue = { - kind: "quickAction", - name: "Yes", - payload: "Yes" - }; - - const noAction: MessageTemplateValue = { - kind: "quickAction", - name: "No", - payload: "No" - }; - - const templateBindings:MessageTemplateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "name" - } - ], - buttons: [ - { - subType: "quickReply", - refValue: "Yes" - }, - { - subType: "quickReply", - refValue: "No" - } - ] - }; - - const template:MessageTemplate = { - name: "sample_issue_resolution", - language: "en_US", - bindings: templateBindings, - values: [nameValue, yesAction, noAction] - }; - - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples-dev/SendTextMessage.ts b/sdk/communication/communication-messages-rest/samples-dev/SendTextMessage.ts deleted file mode 100644 index 2b41db44e1f8..000000000000 --- a/sdk/communication/communication-messages-rest/samples-dev/SendTextMessage.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a text message - */ - - -import NotificationClient, { isUnexpected, Send202Response } from "@azure-rest/communication-messages"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const connectionString = process.env.COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING || ""; - const client = NotificationClient(connectionString); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "text", - content: "Arif The Great!!!" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples-dev/SendTextTemplateMessageUsingAAD.ts b/sdk/communication/communication-messages-rest/samples-dev/SendTextTemplateMessageUsingAAD.ts deleted file mode 100644 index 2b30b76eb628..000000000000 --- a/sdk/communication/communication-messages-rest/samples-dev/SendTextTemplateMessageUsingAAD.ts +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Use AAD token credentials when sending a whatsapp template message. - */ - -import { isNode } from "@azure/core-util"; -import { ClientSecretCredential, DefaultAzureCredential, TokenCredential } from "@azure/identity"; -import NotificationClient, { - Send202Response, - MessageTemplate, - MessageTemplateValue, - MessageTemplateBindings, - isUnexpected, -} from "@azure-rest/communication-messages"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -export async function main(): Promise { - // You will need to set this environment variable or edit the following values - const endpoint = process.env.ACS_URL || ""; - - // Azure AD Credential information is required to run this sample: - if ( - !process.env.AZURE_TENANT_ID || - !process.env.AZURE_CLIENT_ID || - !process.env.AZURE_CLIENT_SECRET - ) { - console.error("Azure AD authentication information not provided, but it is required to run this sample. Exiting."); - return; - } - - // get credentials - const credential: TokenCredential = isNode ? new DefaultAzureCredential() - : new ClientSecretCredential( - process.env.AZURE_TENANT_ID, - process.env.AZURE_CLIENT_ID, - process.env.AZURE_CLIENT_SECRET, - ); - - const client = NotificationClient(endpoint, credential); - - const DaysTemplateValue:MessageTemplateValue = { - kind: "text", - name: "Days", - text: "5" - }; - - const templateBindings:MessageTemplateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "Days" - } - ] - }; - - const template:MessageTemplate = { - name: "sample_shipping_confirmation", - language: "en_US", - bindings: templateBindings, - values: [DaysTemplateValue] - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples-dev/SendVideoMessage.ts b/sdk/communication/communication-messages-rest/samples-dev/SendVideoMessage.ts deleted file mode 100644 index b4db2d84ad83..000000000000 --- a/sdk/communication/communication-messages-rest/samples-dev/SendVideoMessage.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a video message - */ - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { isUnexpected, Send202Response } from "@azure-rest/communication-messages"; -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "video", - mediaUri: "https://sample-videos.com/video321/mp4/480/big_buck_bunny_480p_1mb.mp4", - caption: "happy time!!" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v1/javascript/DownloadMedia.js b/sdk/communication/communication-messages-rest/samples/v1/javascript/DownloadMedia.js deleted file mode 100644 index b1003e6dbc53..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/javascript/DownloadMedia.js +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Download a media file - */ - -const NotificationClient = require("@azure-rest/communication-messages").default; -const { AzureKeyCredential } = require("@azure/core-auth"); -const fs = require("fs"); - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Downloading..."); - await client - .path("/messages/streams/{id}", "") - .get() - .asNodeStream() - .then((resp) => { - resp.body?.pipe(fs.createWriteStream("downloadedMedia.jpeg")); - return; - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); diff --git a/sdk/communication/communication-messages-rest/samples/v1/javascript/GetMessageTemplateList.js b/sdk/communication/communication-messages-rest/samples/v1/javascript/GetMessageTemplateList.js deleted file mode 100644 index 212c5e8dcb7b..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/javascript/GetMessageTemplateList.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Get Template list for a channel - */ - -const { paginate } = require("@azure-rest/communication-messages"); -const MessageTemplateClient = require("@azure-rest/communication-messages").default; -const { AzureKeyCredential } = require("@azure/core-auth"); - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = MessageTemplateClient(endpoint, credential); - console.log("Fetch Templates..."); - const response = await client - .path("/messages/channels/{channelId}/templates", process.env.CHANNEl_ID || "") - .get({ - queryParameters: { maxPageSize: 2 }, - }); - - if (response.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(client, response); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(JSON.stringify(item, null, 2)); - } - } -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); diff --git a/sdk/communication/communication-messages-rest/samples/v1/javascript/README.md b/sdk/communication/communication-messages-rest/samples/v1/javascript/README.md deleted file mode 100644 index ab28fb0a0cc4..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/javascript/README.md +++ /dev/null @@ -1,57 +0,0 @@ -# Azure client library for Azure Communication Messages Services client library samples for JavaScript - -These sample programs show how to use the JavaScript client libraries for Azure client library for Azure Communication Messages Services in some common scenarios. - -| **File Name** | **Description** | -| --------------------------------------------------------------------- | ------------------------------------------------------------------- | -| [DownloadMedia.js][downloadmedia] | Download a media file | -| [GetMessageTemplateList.js][getmessagetemplatelist] | Get Template list for a channel | -| [SendMediaMessage.js][sendmediamessage] | Send a media message | -| [SendTemplateMessage.js][sendtemplatemessage] | Send a template message | -| [SendTextMessage.js][sendtextmessage] | Send a text message | -| [SendTextTemplateMessageUsingAAD.js][sendtexttemplatemessageusingaad] | Use AAD token credentials when sending a whatsapp template message. | - -## Prerequisites - -The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). - -You need [an Azure subscription][freesub] to run these sample programs. - -Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. - -Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. - -## Setup - -To run the samples using the published version of the package: - -1. Install the dependencies using `npm`: - -```bash -npm install -``` - -2. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. - -3. Run whichever samples you like (note that some samples may require additional setup, see the table above): - -```bash -node DownloadMedia.js -``` - -Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): - -```bash -npx dev-tool run vendored cross-env ACS_ACCESS_KEY="" ACS_URL="" node DownloadMedia.js -``` - -## Next Steps - -[downloadmedia]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/javascript/DownloadMedia.js -[getmessagetemplatelist]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/javascript/GetMessageTemplateList.js -[sendmediamessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/javascript/SendMediaMessage.js -[sendtemplatemessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTemplateMessage.js -[sendtextmessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTextMessage.js -[sendtexttemplatemessageusingaad]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTextTemplateMessageUsingAAD.js -[freesub]: https://azure.microsoft.com/free/ -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-messages-rest/README.md diff --git a/sdk/communication/communication-messages-rest/samples/v1/javascript/SendMediaMessage.js b/sdk/communication/communication-messages-rest/samples/v1/javascript/SendMediaMessage.js deleted file mode 100644 index d54451b77a7c..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/javascript/SendMediaMessage.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a media message - */ - -const { AzureKeyCredential } = require("@azure/core-auth"); -const NotificationClient = require("@azure-rest/communication-messages").default; -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "image", - mediaUri: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg", - }, - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (result.status === "202") { - const response = result; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); - } else { - throw new Error("Failed to send message"); - } -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); diff --git a/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTemplateMessage.js b/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTemplateMessage.js deleted file mode 100644 index 28d7ef052e61..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTemplateMessage.js +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a template message - */ - -const { AzureKeyCredential } = require("@azure/core-auth"); -const NotificationClient = require("@azure-rest/communication-messages").default; - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - - const nameValue = { - kind: "text", - name: "name", - text: "Arif", - }; - - const yesAction = { - kind: "quickAction", - name: "Yes", - payload: "Yes", - }; - - const noAction = { - kind: "quickAction", - name: "No", - payload: "No", - }; - - const templateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "name", - }, - ], - buttons: [ - { - subType: "quickReply", - refValue: "Yes", - }, - { - subType: "quickReply", - refValue: "No", - }, - ], - }; - - const template = { - name: "sample_issue_resolution", - language: "en_US", - bindings: templateBindings, - values: [nameValue, yesAction, noAction], - }; - - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template, - }, - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (result.status === "202") { - const response = result; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); - } else { - throw new Error("Failed to send message"); - } -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); diff --git a/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTextMessage.js b/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTextMessage.js deleted file mode 100644 index c03f0539ae99..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTextMessage.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a text message - */ - -const NotificationClient = require("@azure-rest/communication-messages").default; - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const connectionString = process.env.COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING || ""; - const client = NotificationClient(connectionString); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "text", - content: "Arif The Great!!!", - }, - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (result.status === "202") { - const response = result; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); - } else { - throw new Error("Failed to send message"); - } -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); diff --git a/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTextTemplateMessageUsingAAD.js b/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTextTemplateMessageUsingAAD.js deleted file mode 100644 index 3dce1c8fb268..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/javascript/SendTextTemplateMessageUsingAAD.js +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT Licence. - -/** - * @summary Use AAD token credentials when sending a whatsapp template message. - */ - -const { isNode } = require("@azure/core-util"); -const { ClientSecretCredential, DefaultAzureCredential } = require("@azure/identity"); -const NotificationClient = require("@azure-rest/communication-messages").default; - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - // You will need to set this environment variable or edit the following values - const endpoint = process.env.ACS_URL || ""; - - // Azure AD Credential information is required to run this sample: - if ( - !process.env.AZURE_TENANT_ID || - !process.env.AZURE_CLIENT_ID || - !process.env.AZURE_CLIENT_SECRET - ) { - console.error( - "Azure AD authentication information not provided, but it is required to run this sample. Exiting.", - ); - return; - } - - // get credentials - const credential = isNode - ? new DefaultAzureCredential() - : new ClientSecretCredential( - process.env.AZURE_TENANT_ID, - process.env.AZURE_CLIENT_ID, - process.env.AZURE_CLIENT_SECRET, - ); - - const client = NotificationClient(endpoint, credential); - - const DaysTemplateValue = { - kind: "text", - name: "Days", - text: "5", - }; - - const templateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "Days", - }, - ], - }; - - const template = { - name: "sample_shipping_confirmation", - language: "en_US", - bindings: templateBindings, - values: [DaysTemplateValue], - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template, - }, - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (result.status === "202") { - const response = result; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); - } else { - throw new Error("Failed to send message"); - } -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); - -module.exports = { main }; diff --git a/sdk/communication/communication-messages-rest/samples/v1/javascript/package.json b/sdk/communication/communication-messages-rest/samples/v1/javascript/package.json deleted file mode 100644 index 37f3de99a749..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/javascript/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "@azure-samples/communication-messages-js", - "private": true, - "version": "1.0.0", - "description": "Azure client library for Azure Communication Messages Services client library samples for JavaScript", - "engines": { - "node": ">=18.0.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Azure/azure-sdk-for-js.git", - "directory": "sdk/communication/communication-messages-rest" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic" - ], - "author": "Microsoft Corporation", - "license": "MIT", - "bugs": { - "url": "https://github.com/Azure/azure-sdk-for-js/issues" - }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-messages-rest", - "dependencies": { - "@azure-rest/communication-messages": "latest", - "dotenv": "latest", - "@azure/core-auth": "^1.3.0", - "@azure/core-util": "^1.7.0", - "@azure/identity": "^4.2.1" - } -} diff --git a/sdk/communication/communication-messages-rest/samples/v1/javascript/sample.env b/sdk/communication/communication-messages-rest/samples/v1/javascript/sample.env deleted file mode 100644 index 5dded8213dc4..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/javascript/sample.env +++ /dev/null @@ -1,19 +0,0 @@ -# Used in most samples. Retrieve these values from a Communication Services instance -# in the Azure Portal. -COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING="endpoint=https://.communication.azure.com/;accessKey=" - -ACS_URL="https://.communication.azure.com" -ACS_ACCESS_KEY="" - -# The client ID of an Azure Active Directory application. -AZURE_CLIENT_ID="" -# The client secret of an Azure Active Directory application. -AZURE_CLIENT_SECRET="" -#The Tenant ID of your organization in Azure Active Directory. -AZURE_TENANT_ID="" - -# The Channel Id -CHANNEL_ID="" - -# Comma separated list of phone numbers to receive SMS messages -RECIPIENT_PHONE_NUMBER="" diff --git a/sdk/communication/communication-messages-rest/samples/v1/typescript/README.md b/sdk/communication/communication-messages-rest/samples/v1/typescript/README.md deleted file mode 100644 index 89279a0c5930..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/typescript/README.md +++ /dev/null @@ -1,70 +0,0 @@ -# Azure client library for Azure Communication Messages Services client library samples for TypeScript - -These sample programs show how to use the TypeScript client libraries for Azure client library for Azure Communication Messages Services in some common scenarios. - -| **File Name** | **Description** | -| --------------------------------------------------------------------- | ------------------------------------------------------------------- | -| [DownloadMedia.ts][downloadmedia] | Download a media file | -| [GetMessageTemplateList.ts][getmessagetemplatelist] | Get Template list for a channel | -| [SendMediaMessage.ts][sendmediamessage] | Send a media message | -| [SendTemplateMessage.ts][sendtemplatemessage] | Send a template message | -| [SendTextMessage.ts][sendtextmessage] | Send a text message | -| [SendTextTemplateMessageUsingAAD.ts][sendtexttemplatemessageusingaad] | Use AAD token credentials when sending a whatsapp template message. | - -## Prerequisites - -The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). - -Before running the samples in Node, they must be compiled to JavaScript using the TypeScript compiler. For more information on TypeScript, see the [TypeScript documentation][typescript]. Install the TypeScript compiler using: - -```bash -npm install -g typescript -``` - -You need [an Azure subscription][freesub] to run these sample programs. - -Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. - -Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. - -## Setup - -To run the samples using the published version of the package: - -1. Install the dependencies using `npm`: - -```bash -npm install -``` - -2. Compile the samples: - -```bash -npm run build -``` - -3. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. - -4. Run whichever samples you like (note that some samples may require additional setup, see the table above): - -```bash -node dist/DownloadMedia.js -``` - -Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): - -```bash -npx dev-tool run vendored cross-env ACS_ACCESS_KEY="" ACS_URL="" node dist/DownloadMedia.js -``` - -## Next Steps - -[downloadmedia]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/typescript/src/DownloadMedia.ts -[getmessagetemplatelist]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/typescript/src/GetMessageTemplateList.ts -[sendmediamessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendMediaMessage.ts -[sendtemplatemessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTemplateMessage.ts -[sendtextmessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTextMessage.ts -[sendtexttemplatemessageusingaad]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTextTemplateMessageUsingAAD.ts -[freesub]: https://azure.microsoft.com/free/ -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-messages-rest/README.md -[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/communication/communication-messages-rest/samples/v1/typescript/package.json b/sdk/communication/communication-messages-rest/samples/v1/typescript/package.json deleted file mode 100644 index 7b1bc7be1481..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/typescript/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "@azure-samples/communication-messages-ts", - "private": true, - "version": "1.0.0", - "description": "Azure client library for Azure Communication Messages Services client library samples for TypeScript", - "engines": { - "node": ">=18.0.0" - }, - "scripts": { - "build": "tsc", - "prebuild": "rimraf dist/" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Azure/azure-sdk-for-js.git", - "directory": "sdk/communication/communication-messages-rest" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic" - ], - "author": "Microsoft Corporation", - "license": "MIT", - "bugs": { - "url": "https://github.com/Azure/azure-sdk-for-js/issues" - }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-messages-rest", - "dependencies": { - "@azure-rest/communication-messages": "latest", - "dotenv": "latest", - "@azure/core-auth": "^1.3.0", - "@azure/core-util": "^1.7.0", - "@azure/identity": "^4.2.1" - }, - "devDependencies": { - "@types/node": "^18.0.0", - "typescript": "~5.7.2", - "rimraf": "latest" - } -} diff --git a/sdk/communication/communication-messages-rest/samples/v1/typescript/sample.env b/sdk/communication/communication-messages-rest/samples/v1/typescript/sample.env deleted file mode 100644 index 5dded8213dc4..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/typescript/sample.env +++ /dev/null @@ -1,19 +0,0 @@ -# Used in most samples. Retrieve these values from a Communication Services instance -# in the Azure Portal. -COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING="endpoint=https://.communication.azure.com/;accessKey=" - -ACS_URL="https://.communication.azure.com" -ACS_ACCESS_KEY="" - -# The client ID of an Azure Active Directory application. -AZURE_CLIENT_ID="" -# The client secret of an Azure Active Directory application. -AZURE_CLIENT_SECRET="" -#The Tenant ID of your organization in Azure Active Directory. -AZURE_TENANT_ID="" - -# The Channel Id -CHANNEL_ID="" - -# Comma separated list of phone numbers to receive SMS messages -RECIPIENT_PHONE_NUMBER="" diff --git a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/DownloadMedia.ts b/sdk/communication/communication-messages-rest/samples/v1/typescript/src/DownloadMedia.ts deleted file mode 100644 index 3388543566c7..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/DownloadMedia.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Download a media file - */ - -import NotificationClient from "@azure-rest/communication-messages"; -import { AzureKeyCredential } from "@azure/core-auth"; -import * as fs from "fs"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Downloading..."); - await client.path("/messages/streams/{id}", "").get() - .asNodeStream().then((resp) => { - resp.body?.pipe(fs.createWriteStream("downloadedMedia.jpeg")); - return; - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); \ No newline at end of file diff --git a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/GetMessageTemplateList.ts b/sdk/communication/communication-messages-rest/samples/v1/typescript/src/GetMessageTemplateList.ts deleted file mode 100644 index 2ff5c2b5a33b..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/GetMessageTemplateList.ts +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Get Template list for a channel - */ - -import { paginate } from "@azure-rest/communication-messages"; -import MessageTemplateClient from "@azure-rest/communication-messages"; -import { AzureKeyCredential } from "@azure/core-auth"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = MessageTemplateClient(endpoint, credential); - console.log("Fetch Templates..."); - const response = await client.path("/messages/channels/{channelId}/templates", process.env.CHANNEl_ID || "") - .get({ - queryParameters: { maxPageSize: 2 } - }); - - if (response.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(client, response); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(JSON.stringify(item, null, 2)); - } - } -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); \ No newline at end of file diff --git a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendMediaMessage.ts b/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendMediaMessage.ts deleted file mode 100644 index dc642c8441a7..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendMediaMessage.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a media message - */ - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { Send202Response } from "@azure-rest/communication-messages"; -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "image", - mediaUri: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (result.status === "202") { - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId); - }); - } else { - throw new Error("Failed to send message"); - } - -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); diff --git a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTemplateMessage.ts b/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTemplateMessage.ts deleted file mode 100644 index 4245ec9f2df9..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTemplateMessage.ts +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a template message - */ - - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { - MessagesServiceClient, - Send202Response, - MessageTemplate, - MessageTemplateValue, - MessageTemplateBindings, -} from "@azure-rest/communication-messages"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL|| ""; - const client:MessagesServiceClient = NotificationClient(endpoint, credential); - - const nameValue:MessageTemplateValue = { - kind: "text", - name: "name", - text: "Arif" - }; - - const yesAction: MessageTemplateValue = { - kind: "quickAction", - name: "Yes", - payload: "Yes" - }; - - const noAction: MessageTemplateValue = { - kind: "quickAction", - name: "No", - payload: "No" - }; - - const templateBindings:MessageTemplateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "name" - } - ], - buttons: [ - { - subType: "quickReply", - refValue: "Yes" - }, - { - subType: "quickReply", - refValue: "No" - } - ] - }; - - const template:MessageTemplate = { - name: "sample_issue_resolution", - language: "en_US", - bindings: templateBindings, - values: [nameValue, yesAction, noAction] - }; - - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (result.status === "202") { - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId); - }); - } else { - throw new Error("Failed to send message"); - } - -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); diff --git a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTextMessage.ts b/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTextMessage.ts deleted file mode 100644 index ce0b7eaf840e..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTextMessage.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a text message - */ - - -import NotificationClient, { Send202Response } from "@azure-rest/communication-messages"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main() { - const connectionString = process.env.COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING || ""; - const client = NotificationClient(connectionString); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "text", - content: "Arif The Great!!!" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (result.status === "202") { - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId); - }); - } else { - throw new Error("Failed to send message"); - } - -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); diff --git a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTextTemplateMessageUsingAAD.ts b/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTextTemplateMessageUsingAAD.ts deleted file mode 100644 index 4619856ecca8..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/typescript/src/SendTextTemplateMessageUsingAAD.ts +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT Licence. - -/** - * @summary Use AAD token credentials when sending a whatsapp template message. - */ - -import { isNode } from "@azure/core-util"; -import { ClientSecretCredential, DefaultAzureCredential, TokenCredential } from "@azure/identity"; -import NotificationClient, { - Send202Response, - MessageTemplate, - MessageTemplateValue, - MessageTemplateBindings, -} from "@azure-rest/communication-messages"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -export async function main() { - // You will need to set this environment variable or edit the following values - const endpoint = process.env.ACS_URL || ""; - - // Azure AD Credential information is required to run this sample: - if ( - !process.env.AZURE_TENANT_ID || - !process.env.AZURE_CLIENT_ID || - !process.env.AZURE_CLIENT_SECRET - ) { - console.error("Azure AD authentication information not provided, but it is required to run this sample. Exiting."); - return; - } - - // get credentials - const credential: TokenCredential = isNode ? new DefaultAzureCredential() - : new ClientSecretCredential( - process.env.AZURE_TENANT_ID, - process.env.AZURE_CLIENT_ID, - process.env.AZURE_CLIENT_SECRET, - ); - - const client = NotificationClient(endpoint, credential); - - const DaysTemplateValue:MessageTemplateValue = { - kind: "text", - name: "Days", - text: "5" - }; - - const templateBindings:MessageTemplateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "Days" - } - ] - }; - - const template:MessageTemplate = { - name: "sample_shipping_confirmation", - language: "en_US", - bindings: templateBindings, - values: [DaysTemplateValue] - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (result.status === "202") { - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:"+receipt.to+" with message id:"+receipt.messageId); - }); - } else { - throw new Error("Failed to send message"); - } -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - process.exit(1); -}); diff --git a/sdk/communication/communication-messages-rest/samples/v1/typescript/tsconfig.json b/sdk/communication/communication-messages-rest/samples/v1/typescript/tsconfig.json deleted file mode 100644 index 984eed535aa8..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v1/typescript/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "module": "commonjs", - "moduleResolution": "node", - "resolveJsonModule": true, - "esModuleInterop": true, - "allowSyntheticDefaultImports": true, - "strict": true, - "alwaysStrict": true, - "outDir": "dist", - "rootDir": "src" - }, - "include": [ - "src/**/*.ts" - ] -} diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/DownloadMedia.js b/sdk/communication/communication-messages-rest/samples/v2/javascript/DownloadMedia.js deleted file mode 100644 index 37a496efdf0d..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/DownloadMedia.js +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Download a media file - */ - -const NotificationClient = require("@azure-rest/communication-messages").default; -const { AzureKeyCredential } = require("@azure/core-auth"); -const fs = require("fs"); - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Downloading..."); - await client - .path("/messages/streams/{id}", "") - .get() - .asNodeStream() - .then((resp) => { - resp.body?.pipe(fs.createWriteStream("downloadedMedia.jpeg")); - return; - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/GetMessageTemplateList.js b/sdk/communication/communication-messages-rest/samples/v2/javascript/GetMessageTemplateList.js deleted file mode 100644 index 3ae9af443be6..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/GetMessageTemplateList.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Get Template list for a channel - */ - -const { isUnexpected, paginate } = require("@azure-rest/communication-messages"); -const MessageTemplateClient = require("@azure-rest/communication-messages").default; -const { AzureKeyCredential } = require("@azure/core-auth"); - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = MessageTemplateClient(endpoint, credential); - console.log("Fetch Templates..."); - const response = await client - .path("/messages/channels/{channelId}/templates", process.env.CHANNEl_ID || "") - .get({ - queryParameters: { maxPageSize: 2 }, - }); - - if (isUnexpected(response)) { - throw new Error("Failed to get template for the channel."); - } - - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(client, response); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(JSON.stringify(item, null, 2)); - } -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/README.md b/sdk/communication/communication-messages-rest/samples/v2/javascript/README.md deleted file mode 100644 index 1f260f3a2099..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/README.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -page_type: sample -languages: - - javascript -products: - - azure - - azure-communication-services -urlFragment: communication-messages-javascript ---- - -# Azure client library for Azure Communication Messages Services client library samples for JavaScript - -These sample programs show how to use the JavaScript client libraries for Azure client library for Azure Communication Messages Services in some common scenarios. - -| **File Name** | **Description** | -| --------------------------------------------------------------------- | ------------------------------------------------------------------- | -| [DownloadMedia.js][downloadmedia] | Download a media file | -| [GetMessageTemplateList.js][getmessagetemplatelist] | Get Template list for a channel | -| [SendAudioMessage.js][sendaudiomessage] | Send a audio message | -| [SendDocumentMessage.js][senddocumentmessage] | Send a document message | -| [SendImageMessage.js][sendimagemessage] | Send an image message | -| [SendTemplateMessage.js][sendtemplatemessage] | Send a template message | -| [SendTextMessage.js][sendtextmessage] | Send a text message | -| [SendTextTemplateMessageUsingAAD.js][sendtexttemplatemessageusingaad] | Use AAD token credentials when sending a whatsapp template message. | -| [SendVideoMessage.js][sendvideomessage] | Send a video message | - -## Prerequisites - -The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). - -You need [an Azure subscription][freesub] to run these sample programs. - -Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. - -Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. - -## Setup - -To run the samples using the published version of the package: - -1. Install the dependencies using `npm`: - -```bash -npm install -``` - -2. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. - -3. Run whichever samples you like (note that some samples may require additional setup, see the table above): - -```bash -node DownloadMedia.js -``` - -Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): - -```bash -npx dev-tool run vendored cross-env ACS_ACCESS_KEY="" ACS_URL="" node DownloadMedia.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[downloadmedia]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/javascript/DownloadMedia.js -[getmessagetemplatelist]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/javascript/GetMessageTemplateList.js -[sendaudiomessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/javascript/SendAudioMessage.js -[senddocumentmessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/javascript/SendDocumentMessage.js -[sendimagemessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/javascript/SendImageMessage.js -[sendtemplatemessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTemplateMessage.js -[sendtextmessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTextMessage.js -[sendtexttemplatemessageusingaad]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTextTemplateMessageUsingAAD.js -[sendvideomessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/javascript/SendVideoMessage.js -[apiref]: https://learn.microsoft.com/javascript/api/overview/azure/communication-messages-rest-readme?view=azure-node-latest -[freesub]: https://azure.microsoft.com/free/ -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-messages-rest/README.md diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendAudioMessage.js b/sdk/communication/communication-messages-rest/samples/v2/javascript/SendAudioMessage.js deleted file mode 100644 index 007583fd548b..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendAudioMessage.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a audio message - */ - -const { AzureKeyCredential } = require("@azure/core-auth"); -const NotificationClient = require("@azure-rest/communication-messages").default, - { isUnexpected } = require("@azure-rest/communication-messages"); -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "audio", - mediaUri: "https://sample-videos.com/audio/mp3/wave.mp3", - }, - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response = result; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendDocumentMessage.js b/sdk/communication/communication-messages-rest/samples/v2/javascript/SendDocumentMessage.js deleted file mode 100644 index 34425f97cb14..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendDocumentMessage.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a document message - */ - -const { AzureKeyCredential } = require("@azure/core-auth"); -const NotificationClient = require("@azure-rest/communication-messages").default, - { isUnexpected } = require("@azure-rest/communication-messages"); -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "document", - mediaUri: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", - caption: "important!!", - }, - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response = result; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendImageMessage.js b/sdk/communication/communication-messages-rest/samples/v2/javascript/SendImageMessage.js deleted file mode 100644 index 19e01bde6162..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendImageMessage.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send an image message - */ - -const { AzureKeyCredential } = require("@azure/core-auth"); -const NotificationClient = require("@azure-rest/communication-messages").default, - { isUnexpected } = require("@azure-rest/communication-messages"); -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "image", - mediaUri: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg", - }, - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response = result; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTemplateMessage.js b/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTemplateMessage.js deleted file mode 100644 index ee108745ab67..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTemplateMessage.js +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a template message - */ - -const { AzureKeyCredential } = require("@azure/core-auth"); -const NotificationClient = require("@azure-rest/communication-messages").default, - { isUnexpected } = require("@azure-rest/communication-messages"); - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - - const nameValue = { - kind: "text", - name: "name", - text: "Arif", - }; - - const yesAction = { - kind: "quickAction", - name: "Yes", - payload: "Yes", - }; - - const noAction = { - kind: "quickAction", - name: "No", - payload: "No", - }; - - const templateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "name", - }, - ], - buttons: [ - { - subType: "quickReply", - refValue: "Yes", - }, - { - subType: "quickReply", - refValue: "No", - }, - ], - }; - - const template = { - name: "sample_issue_resolution", - language: "en_US", - bindings: templateBindings, - values: [nameValue, yesAction, noAction], - }; - - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template, - }, - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response = result; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTextMessage.js b/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTextMessage.js deleted file mode 100644 index a849defec11f..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTextMessage.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a text message - */ - -const NotificationClient = require("@azure-rest/communication-messages").default, - { isUnexpected } = require("@azure-rest/communication-messages"); - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const connectionString = process.env.COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING || ""; - const client = NotificationClient(connectionString); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "text", - content: "Arif The Great!!!", - }, - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response = result; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTextTemplateMessageUsingAAD.js b/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTextTemplateMessageUsingAAD.js deleted file mode 100644 index 66a6d5eec821..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendTextTemplateMessageUsingAAD.js +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Use AAD token credentials when sending a whatsapp template message. - */ - -const { isNode } = require("@azure/core-util"); -const { ClientSecretCredential, DefaultAzureCredential } = require("@azure/identity"); -const NotificationClient = require("@azure-rest/communication-messages").default, - { isUnexpected } = require("@azure-rest/communication-messages"); - -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - // You will need to set this environment variable or edit the following values - const endpoint = process.env.ACS_URL || ""; - - // Azure AD Credential information is required to run this sample: - if ( - !process.env.AZURE_TENANT_ID || - !process.env.AZURE_CLIENT_ID || - !process.env.AZURE_CLIENT_SECRET - ) { - console.error( - "Azure AD authentication information not provided, but it is required to run this sample. Exiting.", - ); - return; - } - - // get credentials - const credential = isNode - ? new DefaultAzureCredential() - : new ClientSecretCredential( - process.env.AZURE_TENANT_ID, - process.env.AZURE_CLIENT_ID, - process.env.AZURE_CLIENT_SECRET, - ); - - const client = NotificationClient(endpoint, credential); - - const DaysTemplateValue = { - kind: "text", - name: "Days", - text: "5", - }; - - const templateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "Days", - }, - ], - }; - - const template = { - name: "sample_shipping_confirmation", - language: "en_US", - bindings: templateBindings, - values: [DaysTemplateValue], - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template, - }, - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response = result; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); - -module.exports = { main }; diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendVideoMessage.js b/sdk/communication/communication-messages-rest/samples/v2/javascript/SendVideoMessage.js deleted file mode 100644 index ba7238e9fc43..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/SendVideoMessage.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a video message - */ - -const { AzureKeyCredential } = require("@azure/core-auth"); -const NotificationClient = require("@azure-rest/communication-messages").default, - { isUnexpected } = require("@azure-rest/communication-messages"); -// Load the .env file if it exists -require("dotenv").config(); - -async function main() { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "video", - mediaUri: "https://sample-videos.com/video321/mp4/480/big_buck_bunny_480p_1mb.mp4", - caption: "happy time!!", - }, - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if (isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response = result; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/package.json b/sdk/communication/communication-messages-rest/samples/v2/javascript/package.json deleted file mode 100644 index 0d322c5f21fd..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "@azure-samples/communication-messages-js", - "private": true, - "version": "1.0.0", - "description": "Azure client library for Azure Communication Messages Services client library samples for JavaScript", - "engines": { - "node": ">=18.0.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Azure/azure-sdk-for-js.git", - "directory": "sdk/communication/communication-messages-rest" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic" - ], - "author": "Microsoft Corporation", - "license": "MIT", - "bugs": { - "url": "https://github.com/Azure/azure-sdk-for-js/issues" - }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-messages-rest", - "dependencies": { - "@azure-rest/communication-messages": "latest", - "dotenv": "latest", - "@azure/core-auth": "^1.6.0", - "@azure/core-util": "^1.7.0", - "@azure/identity": "^4.2.1" - } -} diff --git a/sdk/communication/communication-messages-rest/samples/v2/javascript/sample.env b/sdk/communication/communication-messages-rest/samples/v2/javascript/sample.env deleted file mode 100644 index 56051dfffe19..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/javascript/sample.env +++ /dev/null @@ -1,19 +0,0 @@ -# Used in most samples. Retrieve these values from a Communication Services instance -# in the Azure Portal. -COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING="endpoint=https://.communication.azure.net/;accessKey=" - -ACS_URL="https://.communication.azure.net" -ACS_ACCESS_KEY="" - -# The client ID of an Azure Active Directory application. -AZURE_CLIENT_ID="" -# The client secret of an Azure Active Directory application. -AZURE_CLIENT_SECRET="" -#The Tenant ID of your organization in Azure Active Directory. -AZURE_TENANT_ID="" - -# The Channel Id -CHANNEL_ID="" - -# Comma separated list of phone numbers to receive SMS messages -RECIPIENT_PHONE_NUMBER="" diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/README.md b/sdk/communication/communication-messages-rest/samples/v2/typescript/README.md deleted file mode 100644 index 4b46ea0ff9ef..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/README.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -page_type: sample -languages: - - typescript -products: - - azure - - azure-communication-services -urlFragment: communication-messages-typescript ---- - -# Azure client library for Azure Communication Messages Services client library samples for TypeScript - -These sample programs show how to use the TypeScript client libraries for Azure client library for Azure Communication Messages Services in some common scenarios. - -| **File Name** | **Description** | -| --------------------------------------------------------------------- | ------------------------------------------------------------------- | -| [DownloadMedia.ts][downloadmedia] | Download a media file | -| [GetMessageTemplateList.ts][getmessagetemplatelist] | Get Template list for a channel | -| [SendAudioMessage.ts][sendaudiomessage] | Send a audio message | -| [SendDocumentMessage.ts][senddocumentmessage] | Send a document message | -| [SendImageMessage.ts][sendimagemessage] | Send an image message | -| [SendTemplateMessage.ts][sendtemplatemessage] | Send a template message | -| [SendTextMessage.ts][sendtextmessage] | Send a text message | -| [SendTextTemplateMessageUsingAAD.ts][sendtexttemplatemessageusingaad] | Use AAD token credentials when sending a whatsapp template message. | -| [SendVideoMessage.ts][sendvideomessage] | Send a video message | - -## Prerequisites - -The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). - -Before running the samples in Node, they must be compiled to JavaScript using the TypeScript compiler. For more information on TypeScript, see the [TypeScript documentation][typescript]. Install the TypeScript compiler using: - -```bash -npm install -g typescript -``` - -You need [an Azure subscription][freesub] to run these sample programs. - -Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. - -Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. - -## Setup - -To run the samples using the published version of the package: - -1. Install the dependencies using `npm`: - -```bash -npm install -``` - -2. Compile the samples: - -```bash -npm run build -``` - -3. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. - -4. Run whichever samples you like (note that some samples may require additional setup, see the table above): - -```bash -node dist/DownloadMedia.js -``` - -Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): - -```bash -npx dev-tool run vendored cross-env ACS_ACCESS_KEY="" ACS_URL="" node dist/DownloadMedia.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[downloadmedia]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/typescript/src/DownloadMedia.ts -[getmessagetemplatelist]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/typescript/src/GetMessageTemplateList.ts -[sendaudiomessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendAudioMessage.ts -[senddocumentmessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendDocumentMessage.ts -[sendimagemessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendImageMessage.ts -[sendtemplatemessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTemplateMessage.ts -[sendtextmessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTextMessage.ts -[sendtexttemplatemessageusingaad]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTextTemplateMessageUsingAAD.ts -[sendvideomessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendVideoMessage.ts -[apiref]: https://learn.microsoft.com/javascript/api/overview/azure/communication-messages-rest-readme?view=azure-node-latest -[freesub]: https://azure.microsoft.com/free/ -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-messages-rest/README.md -[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/package.json b/sdk/communication/communication-messages-rest/samples/v2/typescript/package.json deleted file mode 100644 index 961f15e5c00b..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "@azure-samples/communication-messages-ts", - "private": true, - "version": "1.0.0", - "description": "Azure client library for Azure Communication Messages Services client library samples for TypeScript", - "engines": { - "node": ">=18.0.0" - }, - "scripts": { - "build": "tsc", - "prebuild": "rimraf dist/" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Azure/azure-sdk-for-js.git", - "directory": "sdk/communication/communication-messages-rest" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic" - ], - "author": "Microsoft Corporation", - "license": "MIT", - "bugs": { - "url": "https://github.com/Azure/azure-sdk-for-js/issues" - }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-messages-rest", - "dependencies": { - "@azure-rest/communication-messages": "latest", - "dotenv": "latest", - "@azure/core-auth": "^1.6.0", - "@azure/core-util": "^1.7.0", - "@azure/identity": "^4.2.1" - }, - "devDependencies": { - "@types/node": "^18.0.0", - "typescript": "~5.7.2", - "rimraf": "latest" - } -} diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/sample.env b/sdk/communication/communication-messages-rest/samples/v2/typescript/sample.env deleted file mode 100644 index 56051dfffe19..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/sample.env +++ /dev/null @@ -1,19 +0,0 @@ -# Used in most samples. Retrieve these values from a Communication Services instance -# in the Azure Portal. -COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING="endpoint=https://.communication.azure.net/;accessKey=" - -ACS_URL="https://.communication.azure.net" -ACS_ACCESS_KEY="" - -# The client ID of an Azure Active Directory application. -AZURE_CLIENT_ID="" -# The client secret of an Azure Active Directory application. -AZURE_CLIENT_SECRET="" -#The Tenant ID of your organization in Azure Active Directory. -AZURE_TENANT_ID="" - -# The Channel Id -CHANNEL_ID="" - -# Comma separated list of phone numbers to receive SMS messages -RECIPIENT_PHONE_NUMBER="" diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/DownloadMedia.ts b/sdk/communication/communication-messages-rest/samples/v2/typescript/src/DownloadMedia.ts deleted file mode 100644 index 0d37d9255385..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/DownloadMedia.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Download a media file - */ - -import NotificationClient from "@azure-rest/communication-messages"; -import { AzureKeyCredential } from "@azure/core-auth"; -import * as fs from "fs"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Downloading..."); - await client.path("/messages/streams/{id}", "").get() - .asNodeStream().then((resp) => { - resp.body?.pipe(fs.createWriteStream("downloadedMedia.jpeg")); - return; - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/GetMessageTemplateList.ts b/sdk/communication/communication-messages-rest/samples/v2/typescript/src/GetMessageTemplateList.ts deleted file mode 100644 index 8460fc9f3056..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/GetMessageTemplateList.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Get Template list for a channel - */ - -import { isUnexpected, paginate } from "@azure-rest/communication-messages"; -import MessageTemplateClient from "@azure-rest/communication-messages"; -import { AzureKeyCredential } from "@azure/core-auth"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = MessageTemplateClient(endpoint, credential); - console.log("Fetch Templates..."); - const response = await client.path("/messages/channels/{channelId}/templates", process.env.CHANNEl_ID || "") - .get({ - queryParameters: { maxPageSize: 2 } - }); - - if(isUnexpected(response)) { - throw new Error("Failed to get template for the channel."); - } - - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(client, response); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(JSON.stringify(item, null, 2)); - } -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendAudioMessage.ts b/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendAudioMessage.ts deleted file mode 100644 index d0cdd3a156fb..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendAudioMessage.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a audio message - */ - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { isUnexpected, Send202Response } from "@azure-rest/communication-messages"; -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "audio", - mediaUri: "https://sample-videos.com/audio/mp3/wave.mp3" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendDocumentMessage.ts b/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendDocumentMessage.ts deleted file mode 100644 index 3f8a98d48ff1..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendDocumentMessage.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a document message - */ - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { isUnexpected, Send202Response } from "@azure-rest/communication-messages"; -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "document", - mediaUri: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", - caption: "important!!" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); - -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendImageMessage.ts b/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendImageMessage.ts deleted file mode 100644 index 52e13c023928..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendImageMessage.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send an image message - */ - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { isUnexpected, Send202Response } from "@azure-rest/communication-messages"; -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "image", - mediaUri: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTemplateMessage.ts b/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTemplateMessage.ts deleted file mode 100644 index 8b60e3b70d47..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTemplateMessage.ts +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a template message - */ - - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { - MessagesServiceClient, - Send202Response, - MessageTemplate, - MessageTemplateValue, - MessageTemplateBindings, - isUnexpected, -} from "@azure-rest/communication-messages"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client:MessagesServiceClient = NotificationClient(endpoint, credential); - - const nameValue:MessageTemplateValue = { - kind: "text", - name: "name", - text: "Arif" - }; - - const yesAction: MessageTemplateValue = { - kind: "quickAction", - name: "Yes", - payload: "Yes" - }; - - const noAction: MessageTemplateValue = { - kind: "quickAction", - name: "No", - payload: "No" - }; - - const templateBindings:MessageTemplateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "name" - } - ], - buttons: [ - { - subType: "quickReply", - refValue: "Yes" - }, - { - subType: "quickReply", - refValue: "No" - } - ] - }; - - const template:MessageTemplate = { - name: "sample_issue_resolution", - language: "en_US", - bindings: templateBindings, - values: [nameValue, yesAction, noAction] - }; - - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTextMessage.ts b/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTextMessage.ts deleted file mode 100644 index 2b41db44e1f8..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTextMessage.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a text message - */ - - -import NotificationClient, { isUnexpected, Send202Response } from "@azure-rest/communication-messages"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const connectionString = process.env.COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING || ""; - const client = NotificationClient(connectionString); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "text", - content: "Arif The Great!!!" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTextTemplateMessageUsingAAD.ts b/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTextTemplateMessageUsingAAD.ts deleted file mode 100644 index 2b30b76eb628..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendTextTemplateMessageUsingAAD.ts +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Use AAD token credentials when sending a whatsapp template message. - */ - -import { isNode } from "@azure/core-util"; -import { ClientSecretCredential, DefaultAzureCredential, TokenCredential } from "@azure/identity"; -import NotificationClient, { - Send202Response, - MessageTemplate, - MessageTemplateValue, - MessageTemplateBindings, - isUnexpected, -} from "@azure-rest/communication-messages"; - -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -export async function main(): Promise { - // You will need to set this environment variable or edit the following values - const endpoint = process.env.ACS_URL || ""; - - // Azure AD Credential information is required to run this sample: - if ( - !process.env.AZURE_TENANT_ID || - !process.env.AZURE_CLIENT_ID || - !process.env.AZURE_CLIENT_SECRET - ) { - console.error("Azure AD authentication information not provided, but it is required to run this sample. Exiting."); - return; - } - - // get credentials - const credential: TokenCredential = isNode ? new DefaultAzureCredential() - : new ClientSecretCredential( - process.env.AZURE_TENANT_ID, - process.env.AZURE_CLIENT_ID, - process.env.AZURE_CLIENT_SECRET, - ); - - const client = NotificationClient(endpoint, credential); - - const DaysTemplateValue:MessageTemplateValue = { - kind: "text", - name: "Days", - text: "5" - }; - - const templateBindings:MessageTemplateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "Days" - } - ] - }; - - const template:MessageTemplate = { - name: "sample_shipping_confirmation", - language: "en_US", - bindings: templateBindings, - values: [DaysTemplateValue] - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendVideoMessage.ts b/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendVideoMessage.ts deleted file mode 100644 index b4db2d84ad83..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/src/SendVideoMessage.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Send a video message - */ - -import { AzureKeyCredential } from "@azure/core-auth"; -import NotificationClient, { isUnexpected, Send202Response } from "@azure-rest/communication-messages"; -// Load the .env file if it exists -import * as dotenv from "dotenv"; -dotenv.config(); - -async function main(): Promise { - const credential = new AzureKeyCredential(process.env.ACS_ACCESS_KEY || ""); - const endpoint = process.env.ACS_URL || ""; - const client = NotificationClient(endpoint, credential); - console.log("Sending message..."); - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: process.env.CHANNEL_ID || "", - to: [process.env.RECIPIENT_PHONE_NUMBER || ""], - kind: "video", - mediaUri: "https://sample-videos.com/video321/mp4/480/big_buck_bunny_480p_1mb.mp4", - caption: "happy time!!" - } - }); - - console.log("Response: " + JSON.stringify(result, null, 2)); - - if(isUnexpected(result)) { - throw new Error("Failed to send message"); - } - - const response:Send202Response = result as Send202Response; - response.body.receipts.forEach((receipt) => { - console.log("Message sent to:" + receipt.to + " with message id:" + receipt.messageId); - }); -} - -main().catch((error) => { - console.error("Encountered an error while sending message: ", error); - throw error; -}); diff --git a/sdk/communication/communication-messages-rest/samples/v2/typescript/tsconfig.json b/sdk/communication/communication-messages-rest/samples/v2/typescript/tsconfig.json deleted file mode 100644 index 984eed535aa8..000000000000 --- a/sdk/communication/communication-messages-rest/samples/v2/typescript/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "module": "commonjs", - "moduleResolution": "node", - "resolveJsonModule": true, - "esModuleInterop": true, - "allowSyntheticDefaultImports": true, - "strict": true, - "alwaysStrict": true, - "outDir": "dist", - "rootDir": "src" - }, - "include": [ - "src/**/*.ts" - ] -} diff --git a/sdk/communication/communication-messages-rest/src/generated/src/clientDefinitions.ts b/sdk/communication/communication-messages-rest/src/clientDefinitions.ts similarity index 100% rename from sdk/communication/communication-messages-rest/src/generated/src/clientDefinitions.ts rename to sdk/communication/communication-messages-rest/src/clientDefinitions.ts diff --git a/sdk/communication/communication-messages-rest/src/generated/src/index.ts b/sdk/communication/communication-messages-rest/src/generated/src/index.ts deleted file mode 100644 index 56dbb282687a..000000000000 --- a/sdk/communication/communication-messages-rest/src/generated/src/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import MessagesServiceClient from "./messagesServiceClient.js"; - -export * from "./messagesServiceClient.js"; -export * from "./parameters.js"; -export * from "./responses.js"; -export * from "./clientDefinitions.js"; -export * from "./isUnexpected.js"; -export * from "./models.js"; -export * from "./outputModels.js"; -export * from "./paginateHelper.js"; - -export default MessagesServiceClient; diff --git a/sdk/communication/communication-messages-rest/src/generated/src/messagesServiceClient.ts b/sdk/communication/communication-messages-rest/src/generated/src/messagesServiceClient.ts deleted file mode 100644 index 2ccd514458b1..000000000000 --- a/sdk/communication/communication-messages-rest/src/generated/src/messagesServiceClient.ts +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { getClient, ClientOptions } from "@azure-rest/core-client"; -import { logger } from "./logger.js"; -import { TokenCredential, KeyCredential } from "@azure/core-auth"; -import { MessagesServiceClient } from "./clientDefinitions.js"; - -/** The optional parameters for the client */ -export interface MessagesServiceClientOptions extends ClientOptions { - /** The api version option of the client */ - apiVersion?: string; -} - -/** - * Initialize a new instance of `MessagesServiceClient` - * @param endpointParam - The communication resource, for example https://my-resource.communication.azure.com - * @param credentials - uniquely identify client credential - * @param options - the parameter for all optional parameters - */ -export default function createClient( - endpointParam: string, - credentials: TokenCredential | KeyCredential, - { apiVersion = "2024-08-30", ...options }: MessagesServiceClientOptions = {}, -): MessagesServiceClient { - const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; - const userAgentInfo = `azsdk-js-communication-messages-rest/2.0.0`; - const userAgentPrefix = - options.userAgentOptions && options.userAgentOptions.userAgentPrefix - ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` - : `${userAgentInfo}`; - options = { - ...options, - userAgentOptions: { - userAgentPrefix, - }, - loggingOptions: { - logger: options.loggingOptions?.logger ?? logger.info, - }, - credentials: { - scopes: options.credentials?.scopes ?? [ - "https://communication.azure.com/.default", - ], - apiKeyHeaderName: - options.credentials?.apiKeyHeaderName ?? "Authorization", - }, - }; - const client = getClient( - endpointUrl, - credentials, - options, - ) as MessagesServiceClient; - - client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - client.pipeline.addPolicy({ - name: "ClientApiVersionPolicy", - sendRequest: (req, next) => { - // Use the apiVersion defined in request url directly - // Append one if there is no apiVersion and we have one at client options - const url = new URL(req.url); - if (!url.searchParams.get("api-version") && apiVersion) { - req.url = `${req.url}${ - Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" - }api-version=${apiVersion}`; - } - - return next(req); - }, - }); - - return client; -} diff --git a/sdk/communication/communication-messages-rest/src/generated/src/paginateHelper.ts b/sdk/communication/communication-messages-rest/src/generated/src/paginateHelper.ts deleted file mode 100644 index 94d5220235d9..000000000000 --- a/sdk/communication/communication-messages-rest/src/generated/src/paginateHelper.ts +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { - getPagedAsyncIterator, - PagedAsyncIterableIterator, - PagedResult, -} from "@azure/core-paging"; -import { - Client, - createRestError, - PathUncheckedResponse, -} from "@azure-rest/core-client"; - -/** - * Helper type to extract the type of an array - */ -export type GetArrayType = T extends Array ? TData : never; - -/** - * The type of a custom function that defines how to get a page and a link to the next one if any. - */ -export type GetPage = ( - pageLink: string, - maxPageSize?: number, -) => Promise<{ - page: TPage; - nextPageLink?: string; -}>; - -/** - * Options for the paging helper - */ -export interface PagingOptions { - /** - * Custom function to extract pagination details for crating the PagedAsyncIterableIterator - */ - customGetPage?: GetPage[]>; -} - -/** - * Helper type to infer the Type of the paged elements from the response type - * This type is generated based on the swagger information for x-ms-pageable - * specifically on the itemName property which indicates the property of the response - * where the page items are found. The default value is `value`. - * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter - */ -export type PaginateReturn = TResult extends { - body: { value?: infer TPage }; -} - ? GetArrayType - : Array; - -/** - * Helper to paginate results from an initial response that follows the specification of Autorest `x-ms-pageable` extension - * @param client - Client to use for sending the next page requests - * @param initialResponse - Initial response containing the nextLink and current page of elements - * @param customGetPage - Optional - Function to define how to extract the page and next link to be used to paginate the results - * @returns - PagedAsyncIterableIterator to iterate the elements - */ -export function paginate( - client: Client, - initialResponse: TResponse, - options: PagingOptions = {}, -): PagedAsyncIterableIterator> { - // Extract element type from initial response - type TElement = PaginateReturn; - let firstRun = true; - const itemName = "value"; - const nextLinkName = "nextLink"; - const { customGetPage } = options; - const pagedResult: PagedResult = { - firstPageLink: "", - getPage: - typeof customGetPage === "function" - ? customGetPage - : async (pageLink: string) => { - const result = firstRun - ? initialResponse - : await client.pathUnchecked(pageLink).get(); - firstRun = false; - checkPagingRequest(result); - const nextLink = getNextLink(result.body, nextLinkName); - const values = getElements(result.body, itemName); - return { - page: values, - nextPageLink: nextLink, - }; - }, - }; - - return getPagedAsyncIterator(pagedResult); -} - -/** - * Gets for the value of nextLink in the body - */ -function getNextLink(body: unknown, nextLinkName?: string): string | undefined { - if (!nextLinkName) { - return undefined; - } - - const nextLink = (body as Record)[nextLinkName]; - - if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { - throw new Error( - `Body Property ${nextLinkName} should be a string or undefined`, - ); - } - - return nextLink; -} - -/** - * Gets the elements of the current request in the body. - */ -function getElements(body: unknown, itemName: string): T[] { - const value = (body as Record)[itemName] as T[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn - if (!Array.isArray(value)) { - throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}`, - ); - } - - return value ?? []; -} - -/** - * Checks if a request failed - */ -function checkPagingRequest(response: PathUncheckedResponse): void { - const Http2xxStatusCodes = [ - "200", - "201", - "202", - "203", - "204", - "205", - "206", - "207", - "208", - "226", - ]; - if (!Http2xxStatusCodes.includes(response.status)) { - throw createRestError( - `Pagination failed with unexpected statusCode ${response.status}`, - response, - ); - } -} diff --git a/sdk/communication/communication-messages-rest/src/index.ts b/sdk/communication/communication-messages-rest/src/index.ts index e69027f27809..56dbb282687a 100644 --- a/sdk/communication/communication-messages-rest/src/index.ts +++ b/sdk/communication/communication-messages-rest/src/index.ts @@ -2,12 +2,14 @@ // Licensed under the MIT License. import MessagesServiceClient from "./messagesServiceClient.js"; -export * from "./generated/src/messagesServiceClient.js"; -export * from "./generated/src/parameters.js"; -export * from "./generated/src/responses.js"; -export * from "./generated/src/clientDefinitions.js"; -export * from "./generated/src/isUnexpected.js"; -export * from "./generated/src/models.js"; -export * from "./generated/src/outputModels.js"; -export * from "./generated/src/paginateHelper.js"; + +export * from "./messagesServiceClient.js"; +export * from "./parameters.js"; +export * from "./responses.js"; +export * from "./clientDefinitions.js"; +export * from "./isUnexpected.js"; +export * from "./models.js"; +export * from "./outputModels.js"; +export * from "./paginateHelper.js"; + export default MessagesServiceClient; diff --git a/sdk/communication/communication-messages-rest/src/generated/src/isUnexpected.ts b/sdk/communication/communication-messages-rest/src/isUnexpected.ts similarity index 100% rename from sdk/communication/communication-messages-rest/src/generated/src/isUnexpected.ts rename to sdk/communication/communication-messages-rest/src/isUnexpected.ts diff --git a/sdk/communication/communication-messages-rest/src/generated/src/logger.ts b/sdk/communication/communication-messages-rest/src/logger.ts similarity index 100% rename from sdk/communication/communication-messages-rest/src/generated/src/logger.ts rename to sdk/communication/communication-messages-rest/src/logger.ts diff --git a/sdk/communication/communication-messages-rest/src/messagesServiceClient.ts b/sdk/communication/communication-messages-rest/src/messagesServiceClient.ts index 0732b0ca6794..a39ba2ece9b2 100644 --- a/sdk/communication/communication-messages-rest/src/messagesServiceClient.ts +++ b/sdk/communication/communication-messages-rest/src/messagesServiceClient.ts @@ -1,60 +1,75 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { TokenCredential, KeyCredential } from "@azure/core-auth"; -import { isTokenCredential, isKeyCredential } from "@azure/core-auth"; -import type { ClientOptions } from "@azure-rest/core-client"; -import { parseClientArguments, createCommunicationAuthPolicy } from "@azure/communication-common"; -import type { MessagesServiceClient } from "./generated/src/clientDefinitions.js"; -import GeneratedAzureCommunicationMessageServiceClient from "./generated/src/messagesServiceClient.js"; +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "./logger.js"; +import { TokenCredential, KeyCredential } from "@azure/core-auth"; +import { MessagesServiceClient } from "./clientDefinitions.js"; -/** - * Initialize a new instance of `MessagesServiceClient` - * @param connectionString - The connectionString or url of your Communication Services resource. - * @param options - the parameter for all optional parameters - */ -export default function createClient( - connectionString: string, - options?: ClientOptions, -): MessagesServiceClient; - -/** - * Initialize a new instance of `MessagesServiceClient` - * @param endpoint - The endpoint of your Communication Services resource. - * @param credential - The key or token credential. - * @param options - the parameter for all optional parameters - */ -export default function createClient( - endpoint: string, - credential: KeyCredential | TokenCredential, - options?: ClientOptions, -): MessagesServiceClient; +/** The optional parameters for the client */ +export interface MessagesServiceClientOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} /** * Initialize a new instance of `MessagesServiceClient` - * @param endpoint - The communication resource, for example https://my-resource.communication.azure.com + * @param endpointParam - The communication resource, for example https://my-resource.communication.azure.com * @param credentials - uniquely identify client credential * @param options - the parameter for all optional parameters */ export default function createClient( - endpointOrConnectionString: string, - credentialOrOptions?: ClientOptions | (TokenCredential | KeyCredential), - options?: ClientOptions, + endpointParam: string, + credentials: TokenCredential | KeyCredential, + { + apiVersion = "2024-11-15-preview", + ...options + }: MessagesServiceClientOptions = {}, ): MessagesServiceClient { - if (!(isTokenCredential(credentialOrOptions) || isKeyCredential(credentialOrOptions))) { - options = credentialOrOptions as ClientOptions; - } - - if (options === undefined) { - options = {}; - } + const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; + const userAgentInfo = `azsdk-js-communication-messages-rest/1.0.0-beta.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + credentials: { + scopes: options.credentials?.scopes ?? [ + "https://communication.azure.com/.default", + ], + apiKeyHeaderName: + options.credentials?.apiKeyHeaderName ?? "Authorization", + }, + }; + const client = getClient( + endpointUrl, + credentials, + options, + ) as MessagesServiceClient; - const { url, credential } = parseClientArguments(endpointOrConnectionString, credentialOrOptions); - const baseUrl = options.baseUrl ?? `${url}`; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } - const client = GeneratedAzureCommunicationMessageServiceClient(baseUrl, credential, options); - const authPolicy = createCommunicationAuthPolicy(credential); - client.pipeline.addPolicy(authPolicy); + return next(req); + }, + }); return client; } diff --git a/sdk/communication/communication-messages-rest/src/generated/src/models.ts b/sdk/communication/communication-messages-rest/src/models.ts similarity index 57% rename from sdk/communication/communication-messages-rest/src/generated/src/models.ts rename to sdk/communication/communication-messages-rest/src/models.ts index 68b1e6ae6f45..6429c2b64ef6 100644 --- a/sdk/communication/communication-messages-rest/src/generated/src/models.ts +++ b/sdk/communication/communication-messages-rest/src/models.ts @@ -68,6 +68,165 @@ export interface AudioNotificationContent extends NotificationContentParent { mediaUri: string; } +/** A request to send a Reaction notification. */ +export interface ReactionNotificationContent extends NotificationContentParent { + /** Message notification type is reaction. */ + kind: "reaction"; + /** emoji content like \uD83D\uDE00. */ + emoji: string; + /** ID of the previous message you want to reply to. */ + messageId: string; +} + +/** A request to send a Sticker notification. */ +export interface StickerNotificationContent extends NotificationContentParent { + /** Message notification type is sticker. */ + kind: "sticker"; + /** A media url for the file. Required if the type is one of the supported media types, e.g. image */ + mediaUri: string; +} + +/** A request to send an Interactive message notification. */ +export interface InteractiveNotificationContent + extends NotificationContentParent { + /** Message notification type is Interactive. */ + kind: "interactive"; + /** The interactive message content. */ + interactiveMessage: InteractiveMessage; +} + +/** The Interactive message content to which user can read and respond. */ +export interface InteractiveMessage { + /** Gets or Sets Header content. Supports the following types:text, images etc. */ + header?: MessageContent; + /** Gets or Sets Message body content. Emojis, markdown, and links are supported. */ + body: TextMessageContent; + /** Gets or Sets Message footer content. Emojis, markdown, and links are supported. */ + footer?: TextMessageContent; + /** The binding object to get or set Action which describes options user have to respond to message. */ + action: ActionBindings; +} + +/** The message content object used to create interactive messages components. */ +export interface MessageContentParent { + kind: MessageContentKind; +} + +/** The message content of type text information. */ +export interface TextMessageContent extends MessageContentParent { + /** Message content kind is text. */ + kind: "text"; + /** The text value. */ + text: string; +} + +/** The message content of type document information. */ +export interface DocumentMessageContent extends MessageContentParent { + /** Message content kind is document. */ + kind: "document"; + /** MediaUri of the media content. */ + mediaUri: string; +} + +/** The message content of type image information. */ +export interface ImageMessageContent extends MessageContentParent { + /** Message content kind is image. */ + kind: "image"; + /** MediaUri of the media content. */ + mediaUri: string; +} + +/** The message content of type video information. */ +export interface VideoMessageContent extends MessageContentParent { + /** Message content kind is video. */ + kind: "video"; + /** MediaUri of the media content. */ + mediaUri: string; +} + +/** The message content of type ButtonSet/ List of buttons information. */ +export interface ButtonSetContent extends MessageContentParent { + /** Message content kind is Button. */ + kind: "buttonSet"; + /** Unique Id of the button content. */ + buttons: Array; +} + +/** The message content of type Button information. */ +export interface ButtonContent { + /** Unique Id of the button content. */ + id: string; + /** Title of the button content. */ + title: string; +} + +/** The message content of type Url information. */ +export interface LinkContent extends MessageContentParent { + /** Message content kind is url. */ + kind: "url"; + /** Title of the url content. */ + title: string; + /** The url in the content. */ + url: string; +} + +/** The action content of type ActionGroup. */ +export interface ActionGroupContent extends MessageContentParent { + /** Message content kind is actionGroup. */ + kind: "group"; + /** Title of the actionGroup content. */ + title: string; + /** Set or group of actions. */ + groups: Array; +} + +/** The Action Group content. */ +export interface ActionGroup { + /** Title of the ActionGroup. */ + title: string; + /** Array of items in ActionGroup. */ + items: Array; +} + +/** The Action group item in the content. */ +export interface ActionGroupItem { + /** Id of the Item. */ + id: string; + /** Title of the Item. */ + title: string; + /** Description of the Item. */ + description: string; +} + +/** Binding actions to the interactive message. */ +export interface ActionBindingsParent { + kind: MessageActionBindingKind; +} + +/** WhatsApp List Binding actions to the interactive message. */ +export interface WhatsAppListActionBindings extends ActionBindingsParent { + /** Message action binding type is WhatsAppListAction. */ + kind: "whatsAppListAction"; + /** Action content of Interactive message. */ + content: ActionGroupContent; +} + +/** WhatsApp Binding actions to the interactive message. */ +export interface WhatsAppButtonActionBindings extends ActionBindingsParent { + /** Message action binding type is WhatsAppButtonAction. */ + kind: "whatsAppButtonAction"; + /** Action content of Interactive message. */ + content: ButtonSetContent; +} + +/** WhatsApp Binding actions to the interactive message. */ +export interface WhatsAppUrlActionBindings extends ActionBindingsParent { + /** Message action binding type is WhatsAppUrlAction. */ + kind: "whatsAppUrlAction"; + /** Action content of Interactive message. */ + content: LinkContent; +} + /** A request to send a template notification. */ export interface TemplateNotificationContent extends NotificationContentParent { /** Message notification type is template. */ @@ -210,7 +369,26 @@ export type NotificationContent = | DocumentNotificationContent | VideoNotificationContent | AudioNotificationContent + | ReactionNotificationContent + | StickerNotificationContent + | InteractiveNotificationContent | TemplateNotificationContent; +/** The message content object used to create interactive messages components. */ +export type MessageContent = + | MessageContentParent + | TextMessageContent + | DocumentMessageContent + | ImageMessageContent + | VideoMessageContent + | ButtonSetContent + | LinkContent + | ActionGroupContent; +/** Binding actions to the interactive message. */ +export type ActionBindings = + | ActionBindingsParent + | WhatsAppListActionBindings + | WhatsAppButtonActionBindings + | WhatsAppUrlActionBindings; /** The class describes a parameter of a template. */ export type MessageTemplateValue = | MessageTemplateValueParent @@ -226,6 +404,10 @@ export type MessageTemplateBindings = | WhatsAppMessageTemplateBindings; /** Alias for CommunicationMessageKind */ export type CommunicationMessageKind = string; +/** Alias for MessageContentKind */ +export type MessageContentKind = string; +/** Alias for MessageActionBindingKind */ +export type MessageActionBindingKind = string; /** Alias for MessageTemplateValueKind */ export type MessageTemplateValueKind = string; /** Alias for MessageTemplateBindingsKind */ diff --git a/sdk/communication/communication-messages-rest/src/generated/src/outputModels.ts b/sdk/communication/communication-messages-rest/src/outputModels.ts similarity index 90% rename from sdk/communication/communication-messages-rest/src/generated/src/outputModels.ts rename to sdk/communication/communication-messages-rest/src/outputModels.ts index 9582af995cd3..7e22b63afec5 100644 --- a/sdk/communication/communication-messages-rest/src/generated/src/outputModels.ts +++ b/sdk/communication/communication-messages-rest/src/outputModels.ts @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { Paged } from "@azure/core-paging"; - /** Result of the send message operation. */ export interface SendMessageResultOutput { /** Receipts of the send message operation. */ @@ -17,6 +15,14 @@ export interface MessageReceiptOutput { to: string; } +/** Paged collection of MessageTemplateItem items */ +export interface PagedMessageTemplateItemOutput { + /** The MessageTemplateItem items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + /** The message template as returned from the service. */ export interface MessageTemplateItemOutputParent { /** The template's name. */ @@ -47,8 +53,6 @@ export type MessageTemplateItemOutput = | WhatsAppMessageTemplateItemOutput; /** Alias for RepeatabilityResultOutput */ export type RepeatabilityResultOutput = "accepted" | "rejected"; -/** Paged collection of MessageTemplateItem items */ -export type PagedMessageTemplateItemOutput = Paged; /** Alias for MessageTemplateStatusOutput */ export type MessageTemplateStatusOutput = string; /** Alias for CommunicationMessagesChannelOutput */ diff --git a/sdk/communication/communication-messages-rest/src/paginateHelper.ts b/sdk/communication/communication-messages-rest/src/paginateHelper.ts new file mode 100644 index 000000000000..5ef95e5ea0a3 --- /dev/null +++ b/sdk/communication/communication-messages-rest/src/paginateHelper.ts @@ -0,0 +1,297 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +/** + * returns an async iterator that iterates over results. It also has a `byPage` + * method that returns pages of items at once. + * + * @param pagedResult - an object that specifies how to get pages. + * @returns a paged async iterator that iterates over results. + */ +function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings = PageSettings, + TLink = string, +>( + pagedResult: PagedResult, +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult, + ); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + (((settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken as unknown as TLink | undefined, + }); + }) as unknown as ( + settings?: TPageSettings, + ) => AsyncIterableIterator), + }; +} + +async function* getItemAsyncIterator( + pagedResult: PagedResult, +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: TLink; + } = {}, +): AsyncIterableIterator { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink, + ); + if (!response) { + return; + } + yield response.page; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + yield response.page; + } +} + +/** + * An interface that tracks the settings for paged iteration + */ +export interface PageSettings { + /** + * The token that keeps track of where to continue the iterator + */ + continuationToken?: string; +} + +/** + * An interface that allows async iterable iteration both to completion and by page. + */ +export interface PagedAsyncIterableIterator< + TElement, + TPage = TElement[], + TPageSettings = PageSettings, +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings?: TPageSettings) => AsyncIterableIterator; +} + +/** + * An interface that describes how to communicate with the service. + */ +interface PagedResult { + /** + * Link to the first page of results. + */ + firstPageLink: TLink; + /** + * A method that returns a page of results. + */ + getPage: ( + pageLink: TLink, + ) => Promise<{ page: TPage; nextPageLink?: TLink } | undefined>; + /** + * a function to implement the `byPage` method on the paged async iterator. + */ + byPage?: (settings?: TPageSettings) => AsyncIterableIterator; + + /** + * A function to extract elements from a page. + */ + toElements?: (page: TPage) => unknown[]; +} + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * The type of a custom function that defines how to get a page and a link to the next one if any. + */ +export type GetPage = (pageLink: string) => Promise<{ + page: TPage; + nextPageLink?: string; +}>; + +/** + * Options for the paging helper + */ +export interface PagingOptions { + /** + * Custom function to extract pagination details for crating the PagedAsyncIterableIterator + */ + customGetPage?: GetPage[]>; +} + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends { + body: { value?: infer TPage }; +} + ? GetArrayType + : Array; + +/** + * Helper to paginate results from an initial response that follows the specification of Autorest `x-ms-pageable` extension + * @param client - Client to use for sending the next page requests + * @param initialResponse - Initial response containing the nextLink and current page of elements + * @param customGetPage - Optional - Function to define how to extract the page and next link to be used to paginate the results + * @returns - PagedAsyncIterableIterator to iterate the elements + */ +export function paginate( + client: Client, + initialResponse: TResponse, + options: PagingOptions = {}, +): PagedAsyncIterableIterator> { + // Extract element type from initial response + type TElement = PaginateReturn; + let firstRun = true; + const itemName = "value"; + const nextLinkName = "nextLink"; + const { customGetPage } = options; + const pagedResult: PagedResult = { + firstPageLink: "", + getPage: + typeof customGetPage === "function" + ? customGetPage + : async (pageLink: string) => { + const result = firstRun + ? initialResponse + : await client.pathUnchecked(pageLink).get(); + firstRun = false; + checkPagingRequest(result); + const nextLink = getNextLink(result.body, nextLinkName); + const values = getElements(result.body, itemName); + return { + page: values, + nextPageLink: nextLink, + }; + }, + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * Gets for the value of nextLink in the body + */ +function getNextLink(body: unknown, nextLinkName?: string): string | undefined { + if (!nextLinkName) { + return undefined; + } + + const nextLink = (body as Record)[nextLinkName]; + + if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + throw new Error( + `Body Property ${nextLinkName} should be a string or undefined`, + ); + } + + return nextLink; +} + +/** + * Gets the elements of the current request in the body. + */ +function getElements(body: unknown, itemName: string): T[] { + const value = (body as Record)[itemName] as T[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}`, + ); + } + + return value ?? []; +} + +/** + * Checks if a request failed + */ +function checkPagingRequest(response: PathUncheckedResponse): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response, + ); + } +} diff --git a/sdk/communication/communication-messages-rest/src/generated/src/parameters.ts b/sdk/communication/communication-messages-rest/src/parameters.ts similarity index 100% rename from sdk/communication/communication-messages-rest/src/generated/src/parameters.ts rename to sdk/communication/communication-messages-rest/src/parameters.ts diff --git a/sdk/communication/communication-messages-rest/src/generated/src/responses.ts b/sdk/communication/communication-messages-rest/src/responses.ts similarity index 100% rename from sdk/communication/communication-messages-rest/src/generated/src/responses.ts rename to sdk/communication/communication-messages-rest/src/responses.ts diff --git a/sdk/communication/communication-messages-rest/test/public/messageTest.spec.ts b/sdk/communication/communication-messages-rest/test/public/messageTest.spec.ts deleted file mode 100644 index 2ce8b5eed45f..000000000000 --- a/sdk/communication/communication-messages-rest/test/public/messageTest.spec.ts +++ /dev/null @@ -1,419 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { Recorder } from "@azure-tools/test-recorder"; -import { env } from "@azure-tools/test-recorder"; -import { createRecorderWithConnectionString } from "./utils/recordedClient.js"; -import type { - MessagesServiceClient, - Send202Response, - MessageTemplate, - MessageTemplateValue, - MessageTemplateBindings, - PagedMessageTemplateItemOutput, - ImageNotificationContent, - AudioNotificationContent, - VideoNotificationContent, - DocumentNotificationContent, -} from "../../src/generated/src/index.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("Notification Messages Test", () => { - let recorder: Recorder; - let client: MessagesServiceClient; - - beforeEach(async (ctx) => { - ({ client, recorder } = await createRecorderWithConnectionString(ctx)); - }); - - afterEach(async (ctx) => { - if (!ctx.task.pending) { - await recorder.stop(); - } - }); - - it("send simple text message test", async () => { - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: env.CHANNEL_ID || "", - to: [env.RECIPIENT_PHONE_NUMBER || ""], - kind: "text", - content: "Arif The Great!!!", - }, - }); - assert.equal(result.status, "202"); - const response: Send202Response = result as Send202Response; - assert.equal(response.body.receipts.length, 1); - assert.isDefined(response.body.receipts[0].messageId); - }); - - it("send document message test", async () => { - const documentMessage: DocumentNotificationContent = { - kind: "document", - mediaUri: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", - channelRegistrationId: env.CHANNEL_ID || "", - to: [env.RECIPIENT_PHONE_NUMBER || ""], - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: documentMessage, - }); - assert.equal(result.status, "202"); - const response: Send202Response = result as Send202Response; - assert.equal(response.body.receipts.length, 1); - assert.isDefined(response.body.receipts[0].messageId); - }); - - it("send video message test", async () => { - const videoMessage: VideoNotificationContent = { - kind: "video", - mediaUri: "https://sample-videos.com/video321/mp4/480/big_buck_bunny_480p_1mb.mp4", - channelRegistrationId: env.CHANNEL_ID || "", - to: [env.RECIPIENT_PHONE_NUMBER || ""], - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: videoMessage, - }); - assert.equal(result.status, "202"); - const response: Send202Response = result as Send202Response; - assert.equal(response.body.receipts.length, 1); - assert.isDefined(response.body.receipts[0].messageId); - }); - - it("send audio message test", async () => { - const audioMessage: AudioNotificationContent = { - kind: "audio", - mediaUri: "https://sample-videos.com/audio/mp3/wave.mp3", - channelRegistrationId: env.CHANNEL_ID || "", - to: [env.RECIPIENT_PHONE_NUMBER || ""], - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: audioMessage, - }); - assert.equal(result.status, "202"); - const response: Send202Response = result as Send202Response; - assert.equal(response.body.receipts.length, 1); - assert.isDefined(response.body.receipts[0].messageId); - }); - - it("send image message test", async () => { - const imageMessage: ImageNotificationContent = { - kind: "image", - mediaUri: "https://www.w3schools.com/w3css/img_lights.jpg", - channelRegistrationId: env.CHANNEL_ID || "", - to: [env.RECIPIENT_PHONE_NUMBER || ""], - caption: "awesome", - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: imageMessage, - }); - assert.equal(result.status, "202"); - const response: Send202Response = result as Send202Response; - assert.equal(response.body.receipts.length, 1); - assert.isDefined(response.body.receipts[0].messageId); - }); - - it("send simple text template message test", async () => { - const DaysTemplateValue: MessageTemplateValue = { - kind: "text", - name: "Days", - text: "5", - }; - - const templateBindings: MessageTemplateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "Days", - }, - ], - }; - - const template: MessageTemplate = { - name: "sample_shipping_confirmation", - language: "en_US", - bindings: templateBindings, - values: [DaysTemplateValue], - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: env.CHANNEL_ID || "", - to: [env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template, - }, - }); - assert.equal(result.status, "202"); - const response: Send202Response = result as Send202Response; - assert.equal(response.body.receipts.length, 1); - assert.isDefined(response.body.receipts[0].messageId); - }); - - it("send template message with video test", async () => { - const HeaderVideo: MessageTemplateValue = { - kind: "video", - name: "HappyHourVideo", - url: "https://youtu.be/PSdJX1TKlNI?si=_OI_cxd5IdAFCAev", - }; - - const VenueTemplateValue: MessageTemplateValue = { - kind: "text", - name: "Venue", - text: "HardRockCafe", - }; - - const TimeTemplateValue: MessageTemplateValue = { - kind: "text", - name: "Time", - text: "Today 2-4PM", - }; - - const templateBindings: MessageTemplateBindings = { - kind: "whatsApp", - header: [ - { - refValue: "HappyHourVideo", - }, - ], - body: [ - { - refValue: "Venue", - }, - { - refValue: "Time", - }, - ], - }; - - const template: MessageTemplate = { - name: "sample_happy_hour_announcement", - language: "en_US", - bindings: templateBindings, - values: [HeaderVideo, VenueTemplateValue, TimeTemplateValue], - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: env.CHANNEL_ID || "", - to: [env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template, - }, - }); - assert.equal(result.status, "202"); - const response: Send202Response = result as Send202Response; - assert.equal(response.body.receipts.length, 1); - assert.isDefined(response.body.receipts[0].messageId); - }); - - it("send template message with image test", async () => { - const HeaderImage: MessageTemplateValue = { - kind: "image", - name: "CompanyPhoto", - url: "https://upload.wikimedia.org/wikipedia/commons/3/30/Building92microsoft.jpg", - }; - - const ProductTemplateValue: MessageTemplateValue = { - kind: "text", - name: "Product", - text: "Microsoft Office", - }; - - const templateBindings: MessageTemplateBindings = { - kind: "whatsApp", - header: [ - { - refValue: "CompanyPhoto", - }, - ], - body: [ - { - refValue: "Product", - }, - ], - }; - - const template: MessageTemplate = { - name: "sample_purchase_feedback", - language: "en_US", - bindings: templateBindings, - values: [HeaderImage, ProductTemplateValue], - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: env.CHANNEL_ID || "", - to: [env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template, - }, - }); - assert.equal(result.status, "202"); - const response: Send202Response = result as Send202Response; - assert.equal(response.body.receipts.length, 1); - assert.isDefined(response.body.receipts[0].messageId); - }); - - it("send template message with document test", async () => { - const HeaderDoc: MessageTemplateValue = { - kind: "document", - name: "BoardingPass", - url: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", - }; - - const OriginTemplateValue: MessageTemplateValue = { - kind: "text", - name: "OriginDestination", - text: "RDU", - }; - - const FinalDestinationTemplateValue: MessageTemplateValue = { - kind: "text", - name: "FinalDestination", - text: "LAX", - }; - - const TimeTemplateValue: MessageTemplateValue = { - kind: "text", - name: "BoardingTime", - text: "June 4th, 2024 @ 2PM", - }; - - const templateBindings: MessageTemplateBindings = { - kind: "whatsApp", - header: [ - { - refValue: "BoardingPass", - }, - ], - body: [ - { - refValue: "OriginDestination", - }, - { - refValue: "FinalDestination", - }, - { - refValue: "BoardingTime", - }, - ], - }; - - const template: MessageTemplate = { - name: "sample_flight_confirmation", - language: "en_US", - bindings: templateBindings, - values: [HeaderDoc, OriginTemplateValue, FinalDestinationTemplateValue, TimeTemplateValue], - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: env.CHANNEL_ID || "", - to: [env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template, - }, - }); - assert.equal(result.status, "202"); - const response: Send202Response = result as Send202Response; - assert.equal(response.body.receipts.length, 1); - assert.isDefined(response.body.receipts[0].messageId); - }); - - it("send template message with quick reply buttons test", async () => { - const NameTemplateValue: MessageTemplateValue = { - kind: "text", - name: "NameValue", - text: "Arif", - }; - - const YesQuickActionTemplateValue: MessageTemplateValue = { - kind: "quickAction", - name: "Yes", - payload: "yes", - }; - - const NoQuickActionTemplateValue: MessageTemplateValue = { - kind: "quickAction", - name: "No", - payload: "no", - }; - - const templateBindings: MessageTemplateBindings = { - kind: "whatsApp", - body: [ - { - refValue: "NameValue", - }, - ], - buttons: [ - { - subType: "quickReply", - refValue: "Yes", - }, - { - subType: "quickReply", - refValue: "No", - }, - ], - }; - - const template: MessageTemplate = { - name: "sample_issue_resolution", - language: "en_US", - bindings: templateBindings, - values: [NameTemplateValue, YesQuickActionTemplateValue, NoQuickActionTemplateValue], - }; - - const result = await client.path("/messages/notifications:send").post({ - contentType: "application/json", - body: { - channelRegistrationId: env.CHANNEL_ID || "", - to: [env.RECIPIENT_PHONE_NUMBER || ""], - kind: "template", - template: template, - }, - }); - assert.equal(result.status, "202"); - const response: Send202Response = result as Send202Response; - assert.equal(response.body.receipts.length, 1); - assert.isDefined(response.body.receipts[0].messageId); - }); -}); - -describe("Message Template Read Test", () => { - let recorder: Recorder; - let client: MessagesServiceClient; - - beforeEach(async (ctx) => { - ({ client, recorder } = await createRecorderWithConnectionString(ctx)); - }); - - afterEach(async (ctx) => { - if (!ctx.task.pending) { - await recorder.stop(); - } - }); - - it("get template test", async () => { - const result = await client - .path("/messages/channels/{channelId}/templates", env.CHANNEL_ID || "") - .get(); - assert.equal(result.status, "200"); - const response: PagedMessageTemplateItemOutput = result.body as PagedMessageTemplateItemOutput; - assert.isAtLeast(response.value.length, 1); - }); -}); diff --git a/sdk/communication/communication-messages-rest/test/public/sampleTest.spec.ts b/sdk/communication/communication-messages-rest/test/public/sampleTest.spec.ts new file mode 100644 index 000000000000..d4919ac91ac5 --- /dev/null +++ b/sdk/communication/communication-messages-rest/test/public/sampleTest.spec.ts @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { createRecorder } from "./utils/recordedClient.js"; +import { assert, beforeEach, afterEach, it, describe } from "vitest"; + +describe("My test", () => { + // let recorder: Recorder; + + beforeEach(async function () { + // recorder = await createRecorder(this); + }); + + afterEach(async function () { + // await recorder.stop(); + }); + + it("sample test", async function () { + assert.equal(1, 1); + }); +}); diff --git a/sdk/communication/communication-messages-rest/test/public/utils/env-browser.mts b/sdk/communication/communication-messages-rest/test/public/utils/env-browser.mts deleted file mode 100644 index fc36ab244fad..000000000000 --- a/sdk/communication/communication-messages-rest/test/public/utils/env-browser.mts +++ /dev/null @@ -1,2 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. diff --git a/sdk/communication/communication-messages-rest/test/public/utils/env.ts b/sdk/communication/communication-messages-rest/test/public/utils/env.ts deleted file mode 100644 index 866412f4082d..000000000000 --- a/sdk/communication/communication-messages-rest/test/public/utils/env.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import * as dotenv from "dotenv"; - -dotenv.config(); diff --git a/sdk/communication/communication-messages-rest/test/public/utils/recordedClient.ts b/sdk/communication/communication-messages-rest/test/public/utils/recordedClient.ts index 434976aa17c6..6e425fdcfdf9 100644 --- a/sdk/communication/communication-messages-rest/test/public/utils/recordedClient.ts +++ b/sdk/communication/communication-messages-rest/test/public/utils/recordedClient.ts @@ -1,53 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { RecorderStartOptions, SanitizerOptions, TestInfo } from "@azure-tools/test-recorder"; -import { Recorder, env } from "@azure-tools/test-recorder"; -import type { MessagesServiceClient } from "../../../src/index.js"; -import MessageClient from "../../../src/index.js"; -import { parseConnectionString } from "@azure/communication-common"; -import type { TokenCredential } from "@azure/core-auth"; -import { createTestCredential } from "@azure-tools/test-credential"; -export interface RecordedMessageClient { - client: MessagesServiceClient; - recorder: Recorder; -} - -const envSetupForPlayback: Record = { - COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING: - "endpoint=https://someEndpoint.unitedstates.communication.azure.com/;accesskey=someAccessKeyw==", - CHANNEL_ID: "test_channel_id", - RECIPIENT_PHONE_NUMBER: "+14255550123", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", -}; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const sanitizerOptions: SanitizerOptions = { - connectionStringSanitizers: [ - { - actualConnString: env.COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING, - fakeConnString: envSetupForPlayback["COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING"], - }, - ], - generalSanitizers: [ - { regex: true, target: `"access_token"\\s?:\\s?"[^"]*"`, value: `"access_token":"sanitized"` }, - { - regex: true, - target: `"repeatabilityRequestId"\\s?:\\s?"[^"]*"`, - value: `"repeatabilityRequestId":"sanitized"`, - }, - { - regex: true, - target: `"repeatabilityFirstSent"\\s?:\\s?"[^"]*"`, - value: `"repeatabilityFirstSent":"Thu, 01 Jan 1970 00:00:00 GMT"`, - }, - ], +const replaceableVariables: Record = { + SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, - sanitizerOptions: sanitizerOptions, + envSetupForPlayback: replaceableVariables, }; /** @@ -55,43 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: TestInfo | undefined): Promise { +export async function createRecorder( + context: VitestTestContext, +): Promise { const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); - await recorder.setMatcher("CustomDefaultMatcher", { - excludedHeaders: [ - "Accept-Language", // This is env-dependent - "x-ms-content-sha256", // This is dependent on the current datetime - "sec-ch-ua", // This is browser dependent - // https://developer.mozilla.org/docs/Web/HTTP/Headers/Sec-CH-UA - ], - }); return recorder; } - -export async function createRecorderWithToken(context: TestInfo): Promise { - const recorder = await createRecorder(context); - - const credential: TokenCredential = createTestCredential(); - const endpoint = parseConnectionString( - env.COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING ?? "", - ).endpoint; - - return { - client: MessageClient(endpoint, credential, recorder.configureClientOptions({})), - recorder, - }; -} - -export async function createRecorderWithConnectionString( - context: TestInfo, -): Promise { - const recorder = await createRecorder(context); - - const client = MessageClient( - env.COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING ?? "", - recorder.configureClientOptions({}), - ); - - return { client, recorder }; -} diff --git a/sdk/communication/communication-messages-rest/tests.yml b/sdk/communication/communication-messages-rest/tests.yml deleted file mode 100644 index 4f928a4fb866..000000000000 --- a/sdk/communication/communication-messages-rest/tests.yml +++ /dev/null @@ -1,16 +0,0 @@ -trigger: none - -extends: - template: /eng/pipelines/templates/stages/archetype-sdk-tests.yml - parameters: - PackageName: "@azure-rest/communication-messages" - ServiceDirectory: communication - MatrixFilters: - - DependencyVersion=^$ - CloudConfig: - Public: - SubscriptionConfigurations: - - $(sub-config-communication-services-cloud-test-resources-common) - - $(sub-config-communication-services-cloud-test-resources-js) - TestResourceDirectories: - - communication/communication-messages-rest/ diff --git a/sdk/communication/communication-messages-rest/tsconfig.browser.config.json b/sdk/communication/communication-messages-rest/tsconfig.browser.config.json index 75871518e3a0..091177fcb991 100644 --- a/sdk/communication/communication-messages-rest/tsconfig.browser.config.json +++ b/sdk/communication/communication-messages-rest/tsconfig.browser.config.json @@ -1,3 +1,10 @@ { - "extends": ["./tsconfig.test.json", "../../../tsconfig.browser.base.json"] + "extends": "./.tshy/build.json", + "include": ["src/**/*.ts", "src/**/*.mts", "test/**/*.spec.ts"], + "exclude": ["test/**/node/**/*.ts"], + "compilerOptions": { + "outDir": "./dist-test/browser", + "rootDir": ".", + "skipLibCheck": true + } } diff --git a/sdk/communication/communication-messages-rest/tsconfig.json b/sdk/communication/communication-messages-rest/tsconfig.json index 273d9078a24a..71858ab903e4 100644 --- a/sdk/communication/communication-messages-rest/tsconfig.json +++ b/sdk/communication/communication-messages-rest/tsconfig.json @@ -1,7 +1,16 @@ { - "references": [ - { "path": "./tsconfig.src.json" }, - { "path": "./tsconfig.samples.json" }, - { "path": "./tsconfig.test.json" } + "extends": "../../../tsconfig", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "rootDir": ".", + "skipLibCheck": true + }, + "include": [ + "src/**/*.ts", + "src/**/*.mts", + "src/**/*.cts", + "test/**/*.ts", + "test/**/*.ts" ] -} +} \ No newline at end of file diff --git a/sdk/communication/communication-messages-rest/tsconfig.samples.json b/sdk/communication/communication-messages-rest/tsconfig.samples.json deleted file mode 100644 index c820b8655660..000000000000 --- a/sdk/communication/communication-messages-rest/tsconfig.samples.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../../tsconfig.samples.base.json", - "compilerOptions": { - "paths": { - "@azure-rest/communication-messages": ["./dist/esm"] - } - } -} diff --git a/sdk/communication/communication-messages-rest/tsconfig.src.json b/sdk/communication/communication-messages-rest/tsconfig.src.json deleted file mode 100644 index bae70752dd38..000000000000 --- a/sdk/communication/communication-messages-rest/tsconfig.src.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "../../../tsconfig.lib.json" -} diff --git a/sdk/communication/communication-messages-rest/tsconfig.test.json b/sdk/communication/communication-messages-rest/tsconfig.test.json deleted file mode 100644 index 290ca214aebc..000000000000 --- a/sdk/communication/communication-messages-rest/tsconfig.test.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["./tsconfig.src.json", "../../../tsconfig.test.base.json"] -} diff --git a/sdk/communication/communication-messages-rest/tsp-location.yaml b/sdk/communication/communication-messages-rest/tsp-location.yaml index e27b6aa5b3c6..d8b85e6bcffe 100644 --- a/sdk/communication/communication-messages-rest/tsp-location.yaml +++ b/sdk/communication/communication-messages-rest/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/communication/Communication.Messages -commit: abe3209e7c6924a58ab560ebab2349bc8fde6aa7 -repo: Azure/azure-rest-api-specs -additionalDirectories: \ No newline at end of file +commit: cccad644da207722ddbb8474e1700b33b6e8a2e4 +repo: /mnt/vss/_work/1/s/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/communication/communication-messages-rest/vitest.browser.config.ts b/sdk/communication/communication-messages-rest/vitest.browser.config.ts index 50ec2d5489b0..da68c1d231aa 100644 --- a/sdk/communication/communication-messages-rest/vitest.browser.config.ts +++ b/sdk/communication/communication-messages-rest/vitest.browser.config.ts @@ -1,16 +1,38 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { defineConfig, mergeConfig } from "vitest/config"; -import viteConfig from "../../../vitest.browser.shared.config.ts"; +import { defineConfig } from "vitest/config"; +import { relativeRecordingsPath } from "@azure-tools/test-recorder"; -export default mergeConfig( - viteConfig, - defineConfig({ - test: { - include: ["dist-test/browser/test/**/*.spec.js"], - hookTimeout: 5000000, - testTimeout: 5000000, +process.env.RECORDINGS_RELATIVE_PATH = relativeRecordingsPath(); + +export default defineConfig({ + define: { + "process.env": process.env, + }, + test: { + reporters: ["basic", "junit"], + outputFile: { + junit: "test-results.browser.xml", + }, + browser: { + enabled: true, + headless: true, + name: "chromium", + provider: "playwright", + }, + fakeTimers: { + toFake: ["setTimeout", "Date"], + }, + watch: false, + include: ["dist-test/browser/**/*.spec.js"], + coverage: { + include: ["dist-test/browser/**/*.spec.js"], + provider: "istanbul", + reporter: ["text", "json", "html"], + reportsDirectory: "coverage-browser", }, - }), -); + testTimeout: 1200000, + hookTimeout: 1200000, + }, +}); diff --git a/sdk/communication/communication-messages-rest/vitest.config.ts b/sdk/communication/communication-messages-rest/vitest.config.ts index 8849d7428190..2cf5d0e02c2e 100644 --- a/sdk/communication/communication-messages-rest/vitest.config.ts +++ b/sdk/communication/communication-messages-rest/vitest.config.ts @@ -1,15 +1,34 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { defineConfig, mergeConfig } from "vitest/config"; -import viteConfig from "../../../vitest.shared.config.ts"; +import { defineConfig } from "vitest/config"; +import { relativeRecordingsPath } from "@azure-tools/test-recorder"; -export default mergeConfig( - viteConfig, - defineConfig({ - test: { - hookTimeout: 5000000, - testTimeout: 5000000, +export default defineConfig({ + test: { + reporters: ["basic", "junit"], + outputFile: { + junit: "test-results.browser.xml", }, - }), -); + fakeTimers: { + toFake: ["setTimeout", "Date"], + }, + watch: false, + include: ["test/**/*.spec.ts"], + exclude: ["test/**/browser/*.spec.ts"], + coverage: { + include: ["src/**/*.ts"], + exclude: [ + "src/**/*-browser.mts", + "src/**/*-react-native.mts", + "vitest*.config.ts", + "samples-dev/**/*.ts", + ], + provider: "istanbul", + reporter: ["text", "json", "html"], + reportsDirectory: "coverage", + }, + testTimeout: 1200000, + hookTimeout: 1200000, + }, +}); diff --git a/sdk/communication/communication-messages-rest/vitest.esm.config.ts b/sdk/communication/communication-messages-rest/vitest.esm.config.ts deleted file mode 100644 index 2f6e757a54f7..000000000000 --- a/sdk/communication/communication-messages-rest/vitest.esm.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { mergeConfig } from "vitest/config"; -import vitestConfig from "./vitest.config.ts"; -import vitestEsmConfig from "../../../vitest.esm.shared.config.ts"; - -export default mergeConfig( - vitestConfig, - vitestEsmConfig -); diff --git a/sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/baseline/review/index.ts b/sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/baseline/review/index.ts new file mode 100644 index 000000000000..c9bce80720cf --- /dev/null +++ b/sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/baseline/review/index.ts @@ -0,0 +1,443 @@ + +import { Client } from '@azure-rest/core-client'; +import { ClientOptions } from '@azure-rest/core-client'; +import { ErrorResponse } from '@azure-rest/core-client'; +import { HttpResponse } from '@azure-rest/core-client'; +import { KeyCredential } from '@azure/core-auth'; +import { Paged } from '@azure/core-paging'; +import { PagedAsyncIterableIterator } from '@azure/core-paging'; +import { PathUncheckedResponse } from '@azure-rest/core-client'; +import { RawHttpHeaders } from '@azure/core-rest-pipeline'; +import { RawHttpHeadersInput } from '@azure/core-rest-pipeline'; +import { RequestParameters } from '@azure-rest/core-client'; +import { StreamableMethod } from '@azure-rest/core-client'; +import { TokenCredential } from '@azure/core-auth'; + +// @public +export interface AudioNotificationContent extends NotificationContentParent { + kind: "audio"; + mediaUri: string; +} + +// @public +export type CommunicationMessageKind = string; + +// @public +export type CommunicationMessagesChannelOutput = string; + +// @public +function createClient(connectionString: string, options?: ClientOptions): MessagesServiceClient; + +// @public +function createClient(endpoint: string, credential: KeyCredential | TokenCredential, options?: ClientOptions): MessagesServiceClient; +export default createClient; + +// @public +export interface DocumentNotificationContent extends NotificationContentParent { + caption?: string; + fileName?: string; + kind: "document"; + mediaUri: string; +} + +// @public +export type GetArrayType = T extends Array ? TData : never; + +// @public (undocumented) +export interface GetMedia { + get(options?: GetMediaParameters): StreamableMethod; +} + +// @public (undocumented) +export interface GetMedia200Headers { + "content-type": "application/octet-stream"; + "x-ms-client-request-id"?: string; +} + +// @public +export interface GetMedia200Response extends HttpResponse { + body: Uint8Array; + // (undocumented) + headers: RawHttpHeaders & GetMedia200Headers; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface GetMediaDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface GetMediaDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & GetMediaDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export interface GetMediaHeaderParam { + // (undocumented) + headers?: RawHttpHeadersInput & GetMediaHeaders; +} + +// @public (undocumented) +export interface GetMediaHeaders { + "x-ms-client-request-id"?: string; +} + +// @public (undocumented) +export type GetMediaParameters = GetMediaHeaderParam & RequestParameters; + +// @public +export type GetPage = (pageLink: string, maxPageSize?: number) => Promise<{ + page: TPage; + nextPageLink?: string; +}>; + +// @public +export interface ImageNotificationContent extends NotificationContentParent { + caption?: string; + kind: "image"; + mediaUri: string; +} + +// @public (undocumented) +export function isUnexpected(response: GetMedia200Response | GetMediaDefaultResponse): response is GetMediaDefaultResponse; + +// @public (undocumented) +export function isUnexpected(response: Send202Response | SendDefaultResponse): response is SendDefaultResponse; + +// @public (undocumented) +export function isUnexpected(response: ListTemplates200Response | ListTemplatesDefaultResponse): response is ListTemplatesDefaultResponse; + +// @public (undocumented) +export interface ListTemplates { + get(options?: ListTemplatesParameters): StreamableMethod; +} + +// @public (undocumented) +export interface ListTemplates200Headers { + "x-ms-client-request-id"?: string; +} + +// @public +export interface ListTemplates200Response extends HttpResponse { + // (undocumented) + body: PagedMessageTemplateItemOutput; + // (undocumented) + headers: RawHttpHeaders & ListTemplates200Headers; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface ListTemplatesDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface ListTemplatesDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & ListTemplatesDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export interface ListTemplatesHeaderParam { + // (undocumented) + headers?: RawHttpHeadersInput & ListTemplatesHeaders; +} + +// @public (undocumented) +export interface ListTemplatesHeaders { + "x-ms-client-request-id"?: string; +} + +// @public (undocumented) +export type ListTemplatesParameters = ListTemplatesQueryParam & ListTemplatesHeaderParam & RequestParameters; + +// @public (undocumented) +export interface ListTemplatesQueryParam { + // (undocumented) + queryParameters?: ListTemplatesQueryParamProperties; +} + +// @public (undocumented) +export interface ListTemplatesQueryParamProperties { + maxpagesize?: number; +} + +// @public @deprecated (undocumented) +export interface MediaNotificationContent extends NotificationContentParent { + content?: string; + kind: "image_v0"; + mediaUri: string; +} + +// @public +export interface MessageReceiptOutput { + messageId: string; + to: string; +} + +// @public (undocumented) +export type MessagesServiceClient = Client & { + path: Routes; +}; + +// @public +export interface MessagesServiceClientOptions extends ClientOptions { + apiVersion?: string; +} + +// @public +export interface MessageTemplate { + bindings?: MessageTemplateBindings; + language: string; + name: string; + values?: Array; +} + +// @public +export type MessageTemplateBindings = MessageTemplateBindingsParent | WhatsAppMessageTemplateBindings; + +// @public +export type MessageTemplateBindingsKind = string; + +// @public +export interface MessageTemplateBindingsParent { + // (undocumented) + kind: MessageTemplateBindingsKind; +} + +// @public +export interface MessageTemplateDocument extends MessageTemplateValueParent { + caption?: string; + fileName?: string; + kind: "document"; + url: string; +} + +// @public +export interface MessageTemplateImage extends MessageTemplateValueParent { + caption?: string; + fileName?: string; + kind: "image"; + url: string; +} + +// @public +export type MessageTemplateItemOutput = MessageTemplateItemOutputParent | WhatsAppMessageTemplateItemOutput; + +// @public +export interface MessageTemplateItemOutputParent { + // (undocumented) + kind: CommunicationMessagesChannelOutput; + language: string; + readonly name: string; + status: MessageTemplateStatusOutput; +} + +// @public +export interface MessageTemplateLocation extends MessageTemplateValueParent { + address?: string; + kind: "location"; + latitude: number; + locationName?: string; + longitude: number; +} + +// @public +export interface MessageTemplateQuickAction extends MessageTemplateValueParent { + kind: "quickAction"; + payload?: string; + text?: string; +} + +// @public +export type MessageTemplateStatusOutput = string; + +// @public +export interface MessageTemplateText extends MessageTemplateValueParent { + kind: "text"; + text: string; +} + +// @public +export type MessageTemplateValue = MessageTemplateValueParent | MessageTemplateText | MessageTemplateImage | MessageTemplateDocument | MessageTemplateVideo | MessageTemplateLocation | MessageTemplateQuickAction; + +// @public +export type MessageTemplateValueKind = string; + +// @public +export interface MessageTemplateValueParent { + // (undocumented) + kind: MessageTemplateValueKind; + name: string; +} + +// @public +export interface MessageTemplateVideo extends MessageTemplateValueParent { + caption?: string; + fileName?: string; + kind: "video"; + url: string; +} + +// @public +export type NotificationContent = NotificationContentParent | TextNotificationContent | MediaNotificationContent | ImageNotificationContent | DocumentNotificationContent | VideoNotificationContent | AudioNotificationContent | TemplateNotificationContent; + +// @public +export interface NotificationContentParent { + channelRegistrationId: string; + // (undocumented) + kind: CommunicationMessageKind; + to: string[]; +} + +// @public +export type PagedMessageTemplateItemOutput = Paged; + +// @public +export function paginate(client: Client, initialResponse: TResponse, options?: PagingOptions): PagedAsyncIterableIterator>; + +// @public +export type PaginateReturn = TResult extends { + body: { + value?: infer TPage; + }; +} ? GetArrayType : Array; + +// @public +export interface PagingOptions { + customGetPage?: GetPage[]>; +} + +// @public +export type RepeatabilityResultOutput = "accepted" | "rejected"; + +// @public (undocumented) +export interface Routes { + (path: "/messages/streams/{id}", id: string): GetMedia; + (path: "/messages/notifications:send"): Send; + (path: "/messages/channels/{channelId}/templates", channelId: string): ListTemplates; +} + +// @public (undocumented) +export interface Send { + post(options: SendParameters): StreamableMethod; +} + +// @public (undocumented) +export interface Send202Headers { + "repeatability-result"?: RepeatabilityResultOutput; + "x-ms-client-request-id"?: string; +} + +// @public +export interface Send202Response extends HttpResponse { + // (undocumented) + body: SendMessageResultOutput; + // (undocumented) + headers: RawHttpHeaders & Send202Headers; + // (undocumented) + status: "202"; +} + +// @public (undocumented) +export interface SendBodyParam { + body: NotificationContent; +} + +// @public (undocumented) +export interface SendDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface SendDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & SendDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export interface SendHeaderParam { + // (undocumented) + headers?: RawHttpHeadersInput & SendHeaders; +} + +// @public (undocumented) +export interface SendHeaders { + "Repeatability-First-Sent"?: string; + "Repeatability-Request-ID"?: string; + "x-ms-client-request-id"?: string; +} + +// @public +export interface SendMessageResultOutput { + receipts: Array; +} + +// @public (undocumented) +export type SendParameters = SendHeaderParam & SendBodyParam & RequestParameters; + +// @public +export interface TemplateNotificationContent extends NotificationContentParent { + kind: "template"; + template: MessageTemplate; +} + +// @public +export interface TextNotificationContent extends NotificationContentParent { + content: string; + kind: "text"; +} + +// @public +export interface VideoNotificationContent extends NotificationContentParent { + caption?: string; + kind: "video"; + mediaUri: string; +} + +// @public +export type WhatsAppMessageButtonSubType = string; + +// @public +export interface WhatsAppMessageTemplateBindings extends MessageTemplateBindingsParent { + body?: Array; + buttons?: Array; + footer?: Array; + header?: Array; + kind: "whatsApp"; +} + +// @public +export interface WhatsAppMessageTemplateBindingsButton { + refValue: string; + subType: WhatsAppMessageButtonSubType; +} + +// @public +export interface WhatsAppMessageTemplateBindingsComponent { + refValue: string; +} + +// @public +export interface WhatsAppMessageTemplateItemOutput extends MessageTemplateItemOutputParent { + content?: any; + kind: "whatsApp"; +} + +// (No @packageDocumentation comment for this package) diff --git a/sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/current/review/index.ts b/sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/current/review/index.ts new file mode 100644 index 000000000000..00a81cb6d894 --- /dev/null +++ b/sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/current/review/index.ts @@ -0,0 +1,585 @@ + +import { Client } from '@azure-rest/core-client'; +import { ClientOptions } from '@azure-rest/core-client'; +import { ErrorResponse } from '@azure-rest/core-client'; +import { HttpResponse } from '@azure-rest/core-client'; +import { KeyCredential } from '@azure/core-auth'; +import { PathUncheckedResponse } from '@azure-rest/core-client'; +import { RawHttpHeaders } from '@azure/core-rest-pipeline'; +import { RawHttpHeadersInput } from '@azure/core-rest-pipeline'; +import { RequestParameters } from '@azure-rest/core-client'; +import { StreamableMethod } from '@azure-rest/core-client'; +import { TokenCredential } from '@azure/core-auth'; + +// @public +export type ActionBindings = ActionBindingsParent | WhatsAppListActionBindings | WhatsAppButtonActionBindings | WhatsAppUrlActionBindings; + +// @public +export interface ActionBindingsParent { + // (undocumented) + kind: MessageActionBindingKind; +} + +// @public +export interface ActionGroup { + items: Array; + title: string; +} + +// @public +export interface ActionGroupContent extends MessageContentParent { + groups: Array; + kind: "group"; + title: string; +} + +// @public +export interface ActionGroupItem { + description: string; + id: string; + title: string; +} + +// @public +export interface AudioNotificationContent extends NotificationContentParent { + kind: "audio"; + mediaUri: string; +} + +// @public +export interface ButtonContent { + id: string; + title: string; +} + +// @public +export interface ButtonSetContent extends MessageContentParent { + buttons: Array; + kind: "buttonSet"; +} + +// @public +export type CommunicationMessageKind = string; + +// @public +export type CommunicationMessagesChannelOutput = string; + +// @public +function createClient(endpointParam: string, credentials: TokenCredential | KeyCredential, { apiVersion, ...options }?: MessagesServiceClientOptions): MessagesServiceClient; +export default createClient; + +// @public +export interface DocumentMessageContent extends MessageContentParent { + kind: "document"; + mediaUri: string; +} + +// @public +export interface DocumentNotificationContent extends NotificationContentParent { + caption?: string; + fileName?: string; + kind: "document"; + mediaUri: string; +} + +// @public +export type GetArrayType = T extends Array ? TData : never; + +// @public (undocumented) +export interface GetMedia { + get(options?: GetMediaParameters): StreamableMethod; +} + +// @public (undocumented) +export interface GetMedia200Headers { + "content-type": "application/octet-stream"; + "x-ms-client-request-id"?: string; +} + +// @public +export interface GetMedia200Response extends HttpResponse { + body: Uint8Array; + // (undocumented) + headers: RawHttpHeaders & GetMedia200Headers; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface GetMediaDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface GetMediaDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & GetMediaDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export interface GetMediaHeaderParam { + // (undocumented) + headers?: RawHttpHeadersInput & GetMediaHeaders; +} + +// @public (undocumented) +export interface GetMediaHeaders { + "x-ms-client-request-id"?: string; +} + +// @public (undocumented) +export type GetMediaParameters = GetMediaHeaderParam & RequestParameters; + +// @public +export type GetPage = (pageLink: string) => Promise<{ + page: TPage; + nextPageLink?: string; +}>; + +// @public +export interface ImageMessageContent extends MessageContentParent { + kind: "image"; + mediaUri: string; +} + +// @public +export interface ImageNotificationContent extends NotificationContentParent { + caption?: string; + kind: "image"; + mediaUri: string; +} + +// @public +export interface InteractiveMessage { + action: ActionBindings; + body: TextMessageContent; + footer?: TextMessageContent; + header?: MessageContent; +} + +// @public +export interface InteractiveNotificationContent extends NotificationContentParent { + interactiveMessage: InteractiveMessage; + kind: "interactive"; +} + +// @public (undocumented) +export function isUnexpected(response: GetMedia200Response | GetMediaDefaultResponse): response is GetMediaDefaultResponse; + +// @public (undocumented) +export function isUnexpected(response: Send202Response | SendDefaultResponse): response is SendDefaultResponse; + +// @public (undocumented) +export function isUnexpected(response: ListTemplates200Response | ListTemplatesDefaultResponse): response is ListTemplatesDefaultResponse; + +// @public +export interface LinkContent extends MessageContentParent { + kind: "url"; + title: string; + url: string; +} + +// @public (undocumented) +export interface ListTemplates { + get(options?: ListTemplatesParameters): StreamableMethod; +} + +// @public (undocumented) +export interface ListTemplates200Headers { + "x-ms-client-request-id"?: string; +} + +// @public +export interface ListTemplates200Response extends HttpResponse { + // (undocumented) + body: PagedMessageTemplateItemOutput; + // (undocumented) + headers: RawHttpHeaders & ListTemplates200Headers; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface ListTemplatesDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface ListTemplatesDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & ListTemplatesDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export interface ListTemplatesHeaderParam { + // (undocumented) + headers?: RawHttpHeadersInput & ListTemplatesHeaders; +} + +// @public (undocumented) +export interface ListTemplatesHeaders { + "x-ms-client-request-id"?: string; +} + +// @public (undocumented) +export type ListTemplatesParameters = ListTemplatesQueryParam & ListTemplatesHeaderParam & RequestParameters; + +// @public (undocumented) +export interface ListTemplatesQueryParam { + // (undocumented) + queryParameters?: ListTemplatesQueryParamProperties; +} + +// @public (undocumented) +export interface ListTemplatesQueryParamProperties { + maxpagesize?: number; +} + +// @public @deprecated (undocumented) +export interface MediaNotificationContent extends NotificationContentParent { + content?: string; + kind: "image_v0"; + mediaUri: string; +} + +// @public +export type MessageActionBindingKind = string; + +// @public +export type MessageContent = MessageContentParent | TextMessageContent | DocumentMessageContent | ImageMessageContent | VideoMessageContent | ButtonSetContent | LinkContent | ActionGroupContent; + +// @public +export type MessageContentKind = string; + +// @public +export interface MessageContentParent { + // (undocumented) + kind: MessageContentKind; +} + +// @public +export interface MessageReceiptOutput { + messageId: string; + to: string; +} + +// @public (undocumented) +export type MessagesServiceClient = Client & { + path: Routes; +}; + +// @public +export interface MessagesServiceClientOptions extends ClientOptions { + apiVersion?: string; +} + +// @public +export interface MessageTemplate { + bindings?: MessageTemplateBindings; + language: string; + name: string; + values?: Array; +} + +// @public +export type MessageTemplateBindings = MessageTemplateBindingsParent | WhatsAppMessageTemplateBindings; + +// @public +export type MessageTemplateBindingsKind = string; + +// @public +export interface MessageTemplateBindingsParent { + // (undocumented) + kind: MessageTemplateBindingsKind; +} + +// @public +export interface MessageTemplateDocument extends MessageTemplateValueParent { + caption?: string; + fileName?: string; + kind: "document"; + url: string; +} + +// @public +export interface MessageTemplateImage extends MessageTemplateValueParent { + caption?: string; + fileName?: string; + kind: "image"; + url: string; +} + +// @public +export type MessageTemplateItemOutput = MessageTemplateItemOutputParent | WhatsAppMessageTemplateItemOutput; + +// @public +export interface MessageTemplateItemOutputParent { + // (undocumented) + kind: CommunicationMessagesChannelOutput; + language: string; + readonly name: string; + status: MessageTemplateStatusOutput; +} + +// @public +export interface MessageTemplateLocation extends MessageTemplateValueParent { + address?: string; + kind: "location"; + latitude: number; + locationName?: string; + longitude: number; +} + +// @public +export interface MessageTemplateQuickAction extends MessageTemplateValueParent { + kind: "quickAction"; + payload?: string; + text?: string; +} + +// @public +export type MessageTemplateStatusOutput = string; + +// @public +export interface MessageTemplateText extends MessageTemplateValueParent { + kind: "text"; + text: string; +} + +// @public +export type MessageTemplateValue = MessageTemplateValueParent | MessageTemplateText | MessageTemplateImage | MessageTemplateDocument | MessageTemplateVideo | MessageTemplateLocation | MessageTemplateQuickAction; + +// @public +export type MessageTemplateValueKind = string; + +// @public +export interface MessageTemplateValueParent { + // (undocumented) + kind: MessageTemplateValueKind; + name: string; +} + +// @public +export interface MessageTemplateVideo extends MessageTemplateValueParent { + caption?: string; + fileName?: string; + kind: "video"; + url: string; +} + +// @public +export type NotificationContent = NotificationContentParent | TextNotificationContent | MediaNotificationContent | ImageNotificationContent | DocumentNotificationContent | VideoNotificationContent | AudioNotificationContent | ReactionNotificationContent | StickerNotificationContent | InteractiveNotificationContent | TemplateNotificationContent; + +// @public +export interface NotificationContentParent { + channelRegistrationId: string; + // (undocumented) + kind: CommunicationMessageKind; + to: string[]; +} + +// @public +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator; + next(): Promise>; +} + +// @public +export interface PagedMessageTemplateItemOutput { + nextLink?: string; + value: Array; +} + +// @public +export interface PageSettings { + continuationToken?: string; +} + +// @public +export function paginate(client: Client, initialResponse: TResponse, options?: PagingOptions): PagedAsyncIterableIterator>; + +// @public +export type PaginateReturn = TResult extends { + body: { + value?: infer TPage; + }; +} ? GetArrayType : Array; + +// @public +export interface PagingOptions { + customGetPage?: GetPage[]>; +} + +// @public +export interface ReactionNotificationContent extends NotificationContentParent { + emoji: string; + kind: "reaction"; + messageId: string; +} + +// @public +export type RepeatabilityResultOutput = "accepted" | "rejected"; + +// @public (undocumented) +export interface Routes { + (path: "/messages/streams/{id}", id: string): GetMedia; + (path: "/messages/notifications:send"): Send; + (path: "/messages/channels/{channelId}/templates", channelId: string): ListTemplates; +} + +// @public (undocumented) +export interface Send { + post(options: SendParameters): StreamableMethod; +} + +// @public (undocumented) +export interface Send202Headers { + "repeatability-result"?: RepeatabilityResultOutput; + "x-ms-client-request-id"?: string; +} + +// @public +export interface Send202Response extends HttpResponse { + // (undocumented) + body: SendMessageResultOutput; + // (undocumented) + headers: RawHttpHeaders & Send202Headers; + // (undocumented) + status: "202"; +} + +// @public (undocumented) +export interface SendBodyParam { + body: NotificationContent; +} + +// @public (undocumented) +export interface SendDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface SendDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & SendDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export interface SendHeaderParam { + // (undocumented) + headers?: RawHttpHeadersInput & SendHeaders; +} + +// @public (undocumented) +export interface SendHeaders { + "Repeatability-First-Sent"?: string; + "Repeatability-Request-ID"?: string; + "x-ms-client-request-id"?: string; +} + +// @public +export interface SendMessageResultOutput { + receipts: Array; +} + +// @public (undocumented) +export type SendParameters = SendHeaderParam & SendBodyParam & RequestParameters; + +// @public +export interface StickerNotificationContent extends NotificationContentParent { + kind: "sticker"; + mediaUri: string; +} + +// @public +export interface TemplateNotificationContent extends NotificationContentParent { + kind: "template"; + template: MessageTemplate; +} + +// @public +export interface TextMessageContent extends MessageContentParent { + kind: "text"; + text: string; +} + +// @public +export interface TextNotificationContent extends NotificationContentParent { + content: string; + kind: "text"; +} + +// @public +export interface VideoMessageContent extends MessageContentParent { + kind: "video"; + mediaUri: string; +} + +// @public +export interface VideoNotificationContent extends NotificationContentParent { + caption?: string; + kind: "video"; + mediaUri: string; +} + +// @public +export interface WhatsAppButtonActionBindings extends ActionBindingsParent { + content: ButtonSetContent; + kind: "whatsAppButtonAction"; +} + +// @public +export interface WhatsAppListActionBindings extends ActionBindingsParent { + content: ActionGroupContent; + kind: "whatsAppListAction"; +} + +// @public +export type WhatsAppMessageButtonSubType = string; + +// @public +export interface WhatsAppMessageTemplateBindings extends MessageTemplateBindingsParent { + body?: Array; + buttons?: Array; + footer?: Array; + header?: Array; + kind: "whatsApp"; +} + +// @public +export interface WhatsAppMessageTemplateBindingsButton { + refValue: string; + subType: WhatsAppMessageButtonSubType; +} + +// @public +export interface WhatsAppMessageTemplateBindingsComponent { + refValue: string; +} + +// @public +export interface WhatsAppMessageTemplateItemOutput extends MessageTemplateItemOutputParent { + content?: any; + kind: "whatsApp"; +} + +// @public +export interface WhatsAppUrlActionBindings extends ActionBindingsParent { + content: LinkContent; + kind: "whatsAppUrlAction"; +} + +// (No @packageDocumentation comment for this package) diff --git a/sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/tsconfig.json b/sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/tsconfig.json new file mode 100644 index 000000000000..26e6a4e090b4 --- /dev/null +++ b/sdk/communication/communication-messages-rest/~/.tmp-breaking-change-detect/tsconfig.json @@ -0,0 +1,17 @@ + +{ + "compilerOptions": { + "jsx": "preserve", + "target": "es5", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "lib": ["es2015", "es2017", "esnext"], + "experimentalDecorators": true, + "rootDir": "." + }, + "include": [ + "**/*.ts", + ], + "exclude": ["**/node_modules/**/*.*"] +}