diff --git a/sdk/communication/communication-job-router-rest/CHANGELOG.md b/sdk/communication/communication-job-router-rest/CHANGELOG.md deleted file mode 100644 index e233bd3ccff2..000000000000 --- a/sdk/communication/communication-job-router-rest/CHANGELOG.md +++ /dev/null @@ -1,51 +0,0 @@ -# Release History - -## 1.1.0-beta.3 (Unreleased) - -### Features Added - -### Breaking Changes - -### Bugs Fixed - -### Other Changes - -## 1.1.0-beta.2 (2025-02-10) - -### Features Added - -- refresh @azure-rest/communication-job-router sdk - -## 1.1.0-beta.1 (2024-04-12) - -### Features Added - -#### RouterWorker - -- Added `MaxConcurrentOffers` - -## 1.0.0 (2023-11-01) - -### Features Added - -This is the initial release of the @azure-rest version of Job Router SDK. -There was a previous preview SDK under a different package named @azure/communication-job-router which will be deprecated. - -Using AzureCommunicationRoutingServiceClient: - -- Upsert, get, list and delete DistributionPolicy. -- Upsert, get, list and delete RouterQueue. -- Upsert, get, list and delete ClassificationPolicy. -- Upsert, get, list and delete ExceptionPolicy. -- Upsert, get, list and delete RouterJob. -- RouterJob can be created and updated with different matching modes: QueueAndMatchMode, ScheduleAndSuspendMode and SuspendMode. -- Reclassify a RouterJob. -- Close a RouterJob. -- Complete a RouterJob. -- Cancel a RouterJob. -- Unassign a RouterJob. -- Get the position of a RouterJob in a queue. -- Upsert, get, list and delete RouterWorker. -- Accept an offer. -- Decline an offer. -- Get queue statistics. diff --git a/sdk/communication/communication-job-router-rest/LICENSE b/sdk/communication/communication-job-router-rest/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/communication/communication-job-router-rest/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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-job-router-rest/README.md b/sdk/communication/communication-job-router-rest/README.md index 1501fa9f38bc..491d94763c2f 100644 --- a/sdk/communication/communication-job-router-rest/README.md +++ b/sdk/communication/communication-job-router-rest/README.md @@ -1,7 +1,6 @@ -# Azure Communication Services Job Router REST client library for JavaScript +# AzureCommunicationRoutingService REST client library for JavaScript -This package contains a JavaScript SDK for Azure Communication Services Job Router. -Read more about Azure Communication Services [here](https://learn.microsoft.com/azure/communication-services/overview) +Azure Communication Routing 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** @@ -9,7 +8,7 @@ Key links: - [Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-job-router-rest) - [Package (NPM)](https://www.npmjs.com/package/@azure-rest/communication-job-router) -- [Samples](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-job-router-rest/samples) +- [API reference documentation](https://learn.microsoft.com/javascript/api/@azure-rest/communication-job-router?view=azure-node-preview) ## Getting started @@ -21,407 +20,26 @@ Key links: - You must have an [Azure subscription](https://azure.microsoft.com/free/) to use this package. -### Have an ACS Resource - -Create an ACS resource in the [Azure Portal](https://ms.portal.azure.com/#home) or use an existing resource. - ### Install the `@azure-rest/communication-job-router` package -Install the Job Router REST client library for JavaScript with `npm`: +Install the AzureCommunicationRoutingService REST client REST client library for JavaScript with `npm`: ```bash npm install @azure-rest/communication-job-router ``` -### Create and authenticate an `AzureCommunicationRoutingServiceClient` +### Create and authenticate a `AzureCommunicationRoutingServiceClient` 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. -To authenticate with AAD, you must first `npm` install [`@azure/identity`](https://www.npmjs.com/package/@azure/identity) +To authenticate with AAD, you must first `npm` install [`@azure/identity`](https://www.npmjs.com/package/@azure/identity) 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. -Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: -AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET - -## Tutorial: Route jobs to workers using the Azure Communication Services Job Router SDK - -In this tutorial, you will learn: - -- How to create a queue. -- How to create workers and assign them to a queue. -- How to route jobs to workers. -- How to subscribe to and handle Job Router events. -- How to complete and close jobs. - -### Start a NodeJS Express server - -In a shell (cmd, PowerShell, Bash, etc.) create a folder called `RouterQuickStart` and inside this folder execute `npx express-generator`. This will generate a simple Express project that will listen on `port 3000`. - -#### Example - -```sh -mkdir RouterQuickStart -cd RouterQuickStart -npx express-generator -npm install -DEBUG=routerquickstart:* npm start -``` - -### Install the Azure ACS Job Router SDK - -In the `RouterQuickStart` folder, install the ACS Job Router SDK by executing `npm install @azure-rest/communication-job-router --save`. - -## Routing Jobs - -### Construct an AzureCommunicationRoutingServiceClient - -First we need to construct an `AzureCommunicationRoutingServiceClient`. - -```ts snippet:ReadmeSampleCreateClient -import JobRouterClient from "@azure-rest/communication-job-router"; - -const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; -const routerClient = JobRouterClient(connectionString); -``` - -### Create a Distribution Policy - -This policy determines which workers will receive job offers as jobs are distributed off their queues. - -```ts snippet:ReadmeSampleCreateDistributionPolicy -import JobRouterClient from "@azure-rest/communication-job-router"; - -const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; -const routerClient = JobRouterClient(connectionString); - -const id = "distribution-policy-123"; -const result = await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", id) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longestIdle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); -``` - -### Create a Queue - -This queue offers jobs to workers according to our previously created distribution policy. - -```ts snippet:ReadmeSampleCreateQueue -import JobRouterClient from "@azure-rest/communication-job-router"; - -const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; -const routerClient = JobRouterClient(connectionString); - -const distributionPolicyId = "distribution-policy-123"; -const queueId = "queue-123"; -const result = await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: distributionPolicyId, - name: "Main", - }, -}); -``` - -### Create Workers - -These workers are assigned to our previously created "Sales" queue and have some labels. - -- setting `availableForOffers` to `true` means these workers are ready to accept job offers. -- refer to our [labels documentation](https://learn.microsoft.com/azure/communication-services/concepts/router/concepts#labels) to better understand labels and label selectors. - -```ts snippet:ReadmeSampleCreateWorkers -import JobRouterClient from "@azure-rest/communication-job-router"; - -const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; -const routerClient = JobRouterClient(connectionString); - -const id = "router-worker-123"; -const result = await routerClient.path("/routing/workers/{workerId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - capacity: 100, - queues: ["MainQueue", "SecondaryQueue"], - labels: {}, - channels: [ - { - channelId: "CustomChatChannel", - capacityCostPerJob: 10, - }, - { - channelId: "CustomVoiceChannel", - capacityCostPerJob: 100, - }, - ], - }, -}); -``` - -### Job Lifecycle - -Refer to our [job lifecycle documentation](https://learn.microsoft.com/azure/communication-services/concepts/router/concepts#job-lifecycle) to better understand the lifecycle of a job. - -### Create a Job - -We can create a job with the following: - -```ts snippet:ReadmeSampleCreateJob -import JobRouterClient from "@azure-rest/communication-job-router"; - -const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; -const routerClient = JobRouterClient(connectionString); - -const queueId = "queue-123"; -const jobId = "router-job-123"; -const result = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelId: "ChatChannel", - queueId: queueId, - channelReference: "abc", - priority: 2, - labels: {}, - }, -}); -``` - -### (Optional) Create a Job With a Classification Policy - -#### Create a Classification Policy - -This policy classifies jobs upon creation. - -```ts snippet:ReadmeSampleCreateClassificationPolicy -import JobRouterClient from "@azure-rest/communication-job-router"; - -const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; -const routerClient = JobRouterClient(connectionString); - -const classificationPolicyId = "classification-policy-123"; - -const result = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - fallbackQueueId: "queue-123", - queueSelectorAttachments: [ - { - kind: "conditional", - queueSelectors: [ - { - key: "foo", - labelOperator: "equal", - value: { default: 10 }, - }, - ], - condition: { - kind: "direct-map-rule", - }, - }, - ], - prioritizationRule: { - kind: "static", - value: { default: 2 }, - }, - }, - }); -``` - -- Refer to our [classification concepts documentation](https://learn.microsoft.com/azure/communication-services/concepts/router/classification-concepts) to better understand queue selectors and worker selectors. -- Refer to our [rules documentation](https://learn.microsoft.com/azure/communication-services/concepts/router/router-rule-concepts?pivots=programming-language-javascript) to better understand prioritization rules. - -#### Create and classify a job - -This job will be classified with our previously created classification policy. It also has a label. - -```ts snippet:ReadmeSampleCreateJobWithClassificationPolicy -import JobRouterClient from "@azure-rest/communication-job-router"; - -const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; -const routerClient = JobRouterClient(connectionString); - -const jobId = "router-job-123"; -const classificationPolicyId = "classification-policy-123"; -const job = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelReference: "66e4362e-aad5-4d71-bb51-448672ebf492", - channelId: "voice", - classificationPolicyId: classificationPolicyId, - labels: { - department: "xbox", - }, - }, -}); -``` - -## Events - -Job Router events are delivered via Azure Event Grid. Refer to our [Azure Event Grid documentation](https://learn.microsoft.com/azure/event-grid/overview) to better understand Azure Event Grid. - -In the previous example: - -- The job gets enqueued to the “Sales" queue. -- A worker is selected to handle the job, a job offer is issued to that worker, and a `RouterWorkerOfferIssued` event is sent via Azure Event Grid. - -Example `RouterWorkerOfferIssued` JSON shape: - -```json -{ - "id": "1027db4a-17fe-4a7f-ae67-276c3120a29f", - "topic": "/subscriptions/{subscription-id}/resourceGroups/{group-name}/providers/Microsoft.Communication/communicationServices/{communication-services-resource-name}", - "subject": "worker/{worker-id}/job/{job-id}", - "data": { - "workerId": "w100", - "jobId": "7f1df17b-570b-4ae5-9cf5-fe6ff64cc712", - "channelReference": "test-abc", - "channelId": "FooVoiceChannelId", - "queueId": "625fec06-ab81-4e60-b780-f364ed96ade1", - "offerId": "525fec06-ab81-4e60-b780-f364ed96ade1", - "offerTimeUtc": "2023-08-17T02:43:30.3847144Z", - "expiryTimeUtc": "2023-08-17T02:44:30.3847674Z", - "jobPriority": 5, - "jobLabels": { - "Locale": "en-us", - "Segment": "Enterprise", - "Token": "FooToken" - }, - "jobTags": { - "Locale": "en-us", - "Segment": "Enterprise", - "Token": "FooToken" - } - }, - "eventType": "Microsoft.Communication.RouterWorkerOfferIssued", - "dataVersion": "1.0", - "metadataVersion": "1", - "eventTime": "2023-08-17T00:55:25.1736293Z" -} -``` - -### Subscribing to Events - -One way to subscribe to ACS Job Router events is through the Azure Portal. - -1. Navigate to your ACS resource in the Azure Portal and open the “Events” blade. -2. Add an event subscription for the “RouterWorkerOfferIssued” event. -3. Select an appropriate means to receive the event (e.g. Webhook, Azure Functions, Service Bus). - -Refer to our ["subscribe to Job Router events" documentation](https://learn.microsoft.com/azure/communication-services/how-tos/router-sdk/subscribe-events) to better understand subscribing to Job Router events. - -```ts snippet:ignore -app.post('/event', (req, res) => { - req.body.forEach(eventGridEvent => { - // Deserialize the event data into the appropriate type - if (eventGridEvent.eventType === "Microsoft.EventGrid.SubscriptionValidationEvent") { - res.send({ validationResponse: eventGridEvent.data.validationCode }); - } else if (eventGridEvent.eventType === "Microsoft.Azure.CommunicationServices.RouterWorkerOfferIssued") { - // RouterWorkerOfferIssued handling logic; - } else if ... - }); - ... -}); -``` - -### Accept or Decline the Job Offer - -Once you receive a `RouterWorkerOfferIssued` event you can accept or decline the job offer. - -- `workerId` - Id of the worker accepting or declining the job offer. -- `offerId` - Id of the offer being accepted or declined. - -```ts snippet:ReadmeSampleAcceptOrDeclineOffer -import JobRouterClient from "@azure-rest/communication-job-router"; - -const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; -const routerClient = JobRouterClient(connectionString); - -const workerId = "router-worker-123"; -const offerId = "offer-id"; - -// Accept the job offer -const acceptResponse = await routerClient - .path("/routing/workers/{workerId}/offers/{offerId}:accept", workerId, offerId) - .post(); -// or decline the job offer -const declineResponse = await routerClient - .path("/routing/workers/{workerId}/offers/{offerId}:decline", workerId, offerId) - .post(); -``` - -### Complete the Job - -The `assignmentId` received from the previous step's response is required to complete the job. Completing the job puts it in the wrap-up phase of its lifecycle. - -```ts snippet:ReadmeSampleCompleteJob -import JobRouterClient from "@azure-rest/communication-job-router"; - -const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; -const routerClient = JobRouterClient(connectionString); - -const workerId = "router-worker-123"; -const jobId = "job-id"; -const assignmentId = "assignment-id"; - -const completeJob = await routerClient - .path("/routing/jobs/{jobId}/assignments/{assignmentId}:complete", jobId, assignmentId) - .post({ - body: { - note: `Job has been completed by ${workerId} at ${new Date()}`, - }, - }); -``` - -### Close the Job - -Once the worker has completed the wrap-up phase of the job we can close the job and attach a note to it for future reference. - -```ts snippet:ReadmeSampleCloseJob -import JobRouterClient from "@azure-rest/communication-job-router"; - -const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; -const routerClient = JobRouterClient(connectionString); - -const workerId = "router-worker-123"; -const jobId = "job-id"; -const assignmentId = "assignment-id"; - -const closeJob = await routerClient - .path("/routing/jobs/{jobId}/assignments/{assignmentId}:close", jobId, assignmentId) - .post({ - body: { - note: `Job has been closed by ${workerId} at ${new Date()}`, - }, - }); -``` - ## Troubleshooting ### Logging diff --git a/sdk/communication/communication-job-router-rest/api-extractor.json b/sdk/communication/communication-job-router-rest/api-extractor.json index 36ac0211cff7..04845dd783d2 100644 --- a/sdk/communication/communication-job-router-rest/api-extractor.json +++ b/sdk/communication/communication-job-router-rest/api-extractor.json @@ -28,4 +28,4 @@ } } } -} +} \ No newline at end of file diff --git a/sdk/communication/communication-job-router-rest/assets.json b/sdk/communication/communication-job-router-rest/assets.json deleted file mode 100644 index 2d69a8e4145c..000000000000 --- a/sdk/communication/communication-job-router-rest/assets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "AssetsRepo": "Azure/azure-sdk-assets", - "AssetsRepoPrefixPath": "js", - "TagPrefix": "js/communication/communication-job-router-rest", - "Tag": "js/communication/communication-job-router-rest_a40be4dbdd" -} diff --git a/sdk/communication/communication-job-router-rest/eslint.config.mjs b/sdk/communication/communication-job-router-rest/eslint.config.mjs index 93359ab21816..6d2f8a5914c3 100644 --- a/sdk/communication/communication-job-router-rest/eslint.config.mjs +++ b/sdk/communication/communication-job-router-rest/eslint.config.mjs @@ -3,7 +3,12 @@ import azsdkEslint from "@azure/eslint-plugin-azure-sdk"; export default azsdkEslint.config([ { rules: { - "@azure/azure-sdk/ts-modules-only-named": "warn" - } + "@azure/azure-sdk/ts-modules-only-named": "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-files-required": "off", + "@azure/azure-sdk/ts-package-json-main-is-cjs": "off", + "tsdoc/syntax": "warn", + }, }, ]); diff --git a/sdk/communication/communication-job-router-rest/generated/azureCommunicationRoutingServiceClient.ts b/sdk/communication/communication-job-router-rest/generated/azureCommunicationRoutingServiceClient.ts deleted file mode 100644 index a518300f3123..000000000000 --- a/sdk/communication/communication-job-router-rest/generated/azureCommunicationRoutingServiceClient.ts +++ /dev/null @@ -1,63 +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 { AzureCommunicationRoutingServiceClient } from "./clientDefinitions.js"; - -/** The optional parameters for the client */ -export interface AzureCommunicationRoutingServiceClientOptions - extends ClientOptions { - /** The api version option of the client */ - apiVersion?: string; -} - -/** - * Initialize a new instance of `AzureCommunicationRoutingServiceClient` - * @param endpointParam - Uri of your Communication resource - * @param options - the parameter for all optional parameters - */ -export default function createClient( - endpointParam: string, - { - apiVersion = "2024-01-18-preview", - ...options - }: AzureCommunicationRoutingServiceClientOptions = {}, -): AzureCommunicationRoutingServiceClient { - const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; - const userAgentInfo = `azsdk-js-communication-job-router-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, - }, - }; - const client = getClient( - endpointUrl, - options, - ) as AzureCommunicationRoutingServiceClient; - - 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-job-router-rest/generated/clientDefinitions.ts b/sdk/communication/communication-job-router-rest/generated/clientDefinitions.ts deleted file mode 100644 index 2a68137400e3..000000000000 --- a/sdk/communication/communication-job-router-rest/generated/clientDefinitions.ts +++ /dev/null @@ -1,436 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - - -import { - UpsertClassificationPolicyParameters, - GetClassificationPolicyParameters, - DeleteClassificationPolicyParameters, - ListClassificationPoliciesParameters, - UpsertDistributionPolicyParameters, - GetDistributionPolicyParameters, - DeleteDistributionPolicyParameters, - ListDistributionPoliciesParameters, - UpsertExceptionPolicyParameters, - GetExceptionPolicyParameters, - DeleteExceptionPolicyParameters, - ListExceptionPoliciesParameters, - UpsertQueueParameters, - GetQueueParameters, - DeleteQueueParameters, - ListQueuesParameters, - UpsertJobParameters, - GetJobParameters, - DeleteJobParameters, - ReclassifyParameters, - CancelParameters, - CompleteParameters, - CloseParameters, - ListJobsParameters, - GetInQueuePositionParameters, - UnassignParameters, - AcceptParameters, - DeclineParameters, - GetQueueStatisticsParameters, - UpsertWorkerParameters, - GetWorkerParameters, - DeleteWorkerParameters, - ListWorkersParameters, -} from "./parameters.js"; -import type { - UpsertClassificationPolicy200Response, - UpsertClassificationPolicy201Response, - UpsertClassificationPolicyDefaultResponse, - GetClassificationPolicy200Response, - GetClassificationPolicyDefaultResponse, - DeleteClassificationPolicy204Response, - DeleteClassificationPolicyDefaultResponse, - ListClassificationPolicies200Response, - ListClassificationPoliciesDefaultResponse, - UpsertDistributionPolicy200Response, - UpsertDistributionPolicy201Response, - UpsertDistributionPolicyDefaultResponse, - GetDistributionPolicy200Response, - GetDistributionPolicyDefaultResponse, - DeleteDistributionPolicy204Response, - DeleteDistributionPolicyDefaultResponse, - ListDistributionPolicies200Response, - ListDistributionPoliciesDefaultResponse, - UpsertExceptionPolicy200Response, - UpsertExceptionPolicy201Response, - UpsertExceptionPolicyDefaultResponse, - GetExceptionPolicy200Response, - GetExceptionPolicyDefaultResponse, - DeleteExceptionPolicy204Response, - DeleteExceptionPolicyDefaultResponse, - ListExceptionPolicies200Response, - ListExceptionPoliciesDefaultResponse, - UpsertQueue200Response, - UpsertQueue201Response, - UpsertQueueDefaultResponse, - GetQueue200Response, - GetQueueDefaultResponse, - DeleteQueue204Response, - DeleteQueueDefaultResponse, - ListQueues200Response, - ListQueuesDefaultResponse, - UpsertJob200Response, - UpsertJob201Response, - UpsertJobDefaultResponse, - GetJob200Response, - GetJobDefaultResponse, - DeleteJob204Response, - DeleteJobDefaultResponse, - Reclassify200Response, - ReclassifyDefaultResponse, - Cancel200Response, - CancelDefaultResponse, - Complete200Response, - CompleteDefaultResponse, - Close200Response, - CloseDefaultResponse, - ListJobs200Response, - ListJobsDefaultResponse, - GetInQueuePosition200Response, - GetInQueuePositionDefaultResponse, - Unassign200Response, - UnassignDefaultResponse, - Accept200Response, - AcceptDefaultResponse, - Decline200Response, - DeclineDefaultResponse, - GetQueueStatistics200Response, - GetQueueStatisticsDefaultResponse, - UpsertWorker200Response, - UpsertWorker201Response, - UpsertWorkerDefaultResponse, - GetWorker200Response, - GetWorkerDefaultResponse, - DeleteWorker204Response, - DeleteWorkerDefaultResponse, - ListWorkers200Response, - ListWorkersDefaultResponse, -} from "./responses.js"; -import type { Client, StreamableMethod } from "@azure-rest/core-client"; - -export interface UpsertClassificationPolicy { - /** Creates or updates a classification policy. */ - patch( - options: UpsertClassificationPolicyParameters, - ): StreamableMethod< - | UpsertClassificationPolicy200Response - | UpsertClassificationPolicy201Response - | UpsertClassificationPolicyDefaultResponse - >; - /** Retrieves an existing classification policy by Id. */ - get( - options?: GetClassificationPolicyParameters, - ): StreamableMethod< - GetClassificationPolicy200Response | GetClassificationPolicyDefaultResponse - >; - /** Delete a classification policy by Id. */ - delete( - options?: DeleteClassificationPolicyParameters, - ): StreamableMethod< - | DeleteClassificationPolicy204Response - | DeleteClassificationPolicyDefaultResponse - >; -} - -export interface ListClassificationPolicies { - /** Retrieves existing classification policies. */ - get( - options?: ListClassificationPoliciesParameters, - ): StreamableMethod< - | ListClassificationPolicies200Response - | ListClassificationPoliciesDefaultResponse - >; -} - -export interface UpsertDistributionPolicy { - /** Creates or updates a distribution policy. */ - patch( - options: UpsertDistributionPolicyParameters, - ): StreamableMethod< - | UpsertDistributionPolicy200Response - | UpsertDistributionPolicy201Response - | UpsertDistributionPolicyDefaultResponse - >; - /** Retrieves an existing distribution policy by Id. */ - get( - options?: GetDistributionPolicyParameters, - ): StreamableMethod< - GetDistributionPolicy200Response | GetDistributionPolicyDefaultResponse - >; - /** Delete a distribution policy by Id. */ - delete( - options?: DeleteDistributionPolicyParameters, - ): StreamableMethod< - | DeleteDistributionPolicy204Response - | DeleteDistributionPolicyDefaultResponse - >; -} - -export interface ListDistributionPolicies { - /** Retrieves existing distribution policies. */ - get( - options?: ListDistributionPoliciesParameters, - ): StreamableMethod< - | ListDistributionPolicies200Response - | ListDistributionPoliciesDefaultResponse - >; -} - -export interface UpsertExceptionPolicy { - /** Creates or updates a exception policy. */ - patch( - options: UpsertExceptionPolicyParameters, - ): StreamableMethod< - | UpsertExceptionPolicy200Response - | UpsertExceptionPolicy201Response - | UpsertExceptionPolicyDefaultResponse - >; - /** Retrieves an existing exception policy by Id. */ - get( - options?: GetExceptionPolicyParameters, - ): StreamableMethod< - GetExceptionPolicy200Response | GetExceptionPolicyDefaultResponse - >; - /** Deletes a exception policy by Id. */ - delete( - options?: DeleteExceptionPolicyParameters, - ): StreamableMethod< - DeleteExceptionPolicy204Response | DeleteExceptionPolicyDefaultResponse - >; -} - -export interface ListExceptionPolicies { - /** Retrieves existing exception policies. */ - get( - options?: ListExceptionPoliciesParameters, - ): StreamableMethod< - ListExceptionPolicies200Response | ListExceptionPoliciesDefaultResponse - >; -} - -export interface UpsertQueue { - /** Creates or updates a queue. */ - patch( - options: UpsertQueueParameters, - ): StreamableMethod< - UpsertQueue200Response | UpsertQueue201Response | UpsertQueueDefaultResponse - >; - /** Retrieves an existing queue by Id. */ - get( - options?: GetQueueParameters, - ): StreamableMethod; - /** Deletes a queue by Id. */ - delete( - options?: DeleteQueueParameters, - ): StreamableMethod; -} - -export interface ListQueues { - /** Retrieves existing queues. */ - get( - options?: ListQueuesParameters, - ): StreamableMethod; -} - -export interface UpsertJob { - /** Creates or updates a router job. */ - patch( - options: UpsertJobParameters, - ): StreamableMethod< - UpsertJob200Response | UpsertJob201Response | UpsertJobDefaultResponse - >; - /** Retrieves an existing job by Id. */ - get( - options?: GetJobParameters, - ): StreamableMethod; - /** Deletes a job and all of its traces. */ - delete( - options?: DeleteJobParameters, - ): StreamableMethod; -} - -export interface Reclassify { - /** Reclassify a job. */ - post( - options?: ReclassifyParameters, - ): StreamableMethod; -} - -export interface Cancel { - /** Submits request to cancel an existing job by Id while supplying free-form cancellation reason. */ - post( - options?: CancelParameters, - ): StreamableMethod; -} - -export interface Complete { - /** Completes an assigned job. */ - post( - options?: CompleteParameters, - ): StreamableMethod; -} - -export interface Close { - /** Closes a completed job. */ - post( - options?: CloseParameters, - ): StreamableMethod; -} - -export interface ListJobs { - /** Retrieves list of jobs based on filter parameters. */ - get( - options?: ListJobsParameters, - ): StreamableMethod; -} - -export interface GetInQueuePosition { - /** Gets a job's position details. */ - get( - options?: GetInQueuePositionParameters, - ): StreamableMethod< - GetInQueuePosition200Response | GetInQueuePositionDefaultResponse - >; -} - -export interface Unassign { - /** Unassign a job. */ - post( - options?: UnassignParameters, - ): StreamableMethod; -} - -export interface Accept { - /** Accepts an offer to work on a job and returns a 409/Conflict if another agent accepted the job already. */ - post( - options?: AcceptParameters, - ): StreamableMethod; -} - -export interface Decline { - /** Declines an offer to work on a job. */ - post( - options?: DeclineParameters, - ): StreamableMethod; -} - -export interface GetQueueStatistics { - /** Retrieves a queue's statistics. */ - get( - options?: GetQueueStatisticsParameters, - ): StreamableMethod< - GetQueueStatistics200Response | GetQueueStatisticsDefaultResponse - >; -} - -export interface UpsertWorker { - /** Creates or updates a worker. */ - patch( - options: UpsertWorkerParameters, - ): StreamableMethod< - | UpsertWorker200Response - | UpsertWorker201Response - | UpsertWorkerDefaultResponse - >; - /** Retrieves an existing worker by Id. */ - get( - options?: GetWorkerParameters, - ): StreamableMethod; - /** Deletes a worker and all of its traces. */ - delete( - options?: DeleteWorkerParameters, - ): StreamableMethod; -} - -export interface ListWorkers { - /** Retrieves existing workers. */ - get( - options?: ListWorkersParameters, - ): StreamableMethod; -} - -export interface Routes { - /** Resource for '/routing/classificationPolicies/\{classificationPolicyId\}' has methods for the following verbs: patch, get, delete */ - ( - path: "/routing/classificationPolicies/{classificationPolicyId}", - classificationPolicyId: string, - ): UpsertClassificationPolicy; - /** Resource for '/routing/classificationPolicies' has methods for the following verbs: get */ - (path: "/routing/classificationPolicies"): ListClassificationPolicies; - /** Resource for '/routing/distributionPolicies/\{distributionPolicyId\}' has methods for the following verbs: patch, get, delete */ - ( - path: "/routing/distributionPolicies/{distributionPolicyId}", - distributionPolicyId: string, - ): UpsertDistributionPolicy; - /** Resource for '/routing/distributionPolicies' has methods for the following verbs: get */ - (path: "/routing/distributionPolicies"): ListDistributionPolicies; - /** Resource for '/routing/exceptionPolicies/\{exceptionPolicyId\}' has methods for the following verbs: patch, get, delete */ - ( - path: "/routing/exceptionPolicies/{exceptionPolicyId}", - exceptionPolicyId: string, - ): UpsertExceptionPolicy; - /** Resource for '/routing/exceptionPolicies' has methods for the following verbs: get */ - (path: "/routing/exceptionPolicies"): ListExceptionPolicies; - /** Resource for '/routing/queues/\{queueId\}' has methods for the following verbs: patch, get, delete */ - (path: "/routing/queues/{queueId}", queueId: string): UpsertQueue; - /** Resource for '/routing/queues' has methods for the following verbs: get */ - (path: "/routing/queues"): ListQueues; - /** Resource for '/routing/jobs/\{jobId\}' has methods for the following verbs: patch, get, delete */ - (path: "/routing/jobs/{jobId}", jobId: string): UpsertJob; - /** Resource for '/routing/jobs/\{jobId\}:reclassify' has methods for the following verbs: post */ - (path: "/routing/jobs/{jobId}:reclassify", jobId: string): Reclassify; - /** Resource for '/routing/jobs/\{jobId\}:cancel' has methods for the following verbs: post */ - (path: "/routing/jobs/{jobId}:cancel", jobId: string): Cancel; - /** Resource for '/routing/jobs/\{jobId\}/assignments/\{assignmentId\}:complete' has methods for the following verbs: post */ - ( - path: "/routing/jobs/{jobId}/assignments/{assignmentId}:complete", - jobId: string, - assignmentId: string, - ): Complete; - /** Resource for '/routing/jobs/\{jobId\}/assignments/\{assignmentId\}:close' has methods for the following verbs: post */ - ( - path: "/routing/jobs/{jobId}/assignments/{assignmentId}:close", - jobId: string, - assignmentId: string, - ): Close; - /** Resource for '/routing/jobs' has methods for the following verbs: get */ - (path: "/routing/jobs"): ListJobs; - /** Resource for '/routing/jobs/\{jobId\}/position' has methods for the following verbs: get */ - (path: "/routing/jobs/{jobId}/position", jobId: string): GetInQueuePosition; - /** Resource for '/routing/jobs/\{jobId\}/assignments/\{assignmentId\}:unassign' has methods for the following verbs: post */ - ( - path: "/routing/jobs/{jobId}/assignments/{assignmentId}:unassign", - jobId: string, - assignmentId: string, - ): Unassign; - /** Resource for '/routing/workers/\{workerId\}/offers/\{offerId\}:accept' has methods for the following verbs: post */ - ( - path: "/routing/workers/{workerId}/offers/{offerId}:accept", - workerId: string, - offerId: string, - ): Accept; - /** Resource for '/routing/workers/\{workerId\}/offers/\{offerId\}:decline' has methods for the following verbs: post */ - ( - path: "/routing/workers/{workerId}/offers/{offerId}:decline", - workerId: string, - offerId: string, - ): Decline; - /** Resource for '/routing/queues/\{queueId\}/statistics' has methods for the following verbs: get */ - ( - path: "/routing/queues/{queueId}/statistics", - queueId: string, - ): GetQueueStatistics; - /** Resource for '/routing/workers/\{workerId\}' has methods for the following verbs: patch, get, delete */ - (path: "/routing/workers/{workerId}", workerId: string): UpsertWorker; - /** Resource for '/routing/workers' has methods for the following verbs: get */ - (path: "/routing/workers"): ListWorkers; -} - -export type AzureCommunicationRoutingServiceClient = Client & { - path: Routes; -}; diff --git a/sdk/communication/communication-job-router-rest/generated/index.ts b/sdk/communication/communication-job-router-rest/generated/index.ts deleted file mode 100644 index 1c1e0181dcda..000000000000 --- a/sdk/communication/communication-job-router-rest/generated/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import AzureCommunicationRoutingServiceClient from "./azureCommunicationRoutingServiceClient.js"; - -export * from "./azureCommunicationRoutingServiceClient.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 AzureCommunicationRoutingServiceClient; diff --git a/sdk/communication/communication-job-router-rest/generated/isUnexpected.ts b/sdk/communication/communication-job-router-rest/generated/isUnexpected.ts deleted file mode 100644 index db118337e18e..000000000000 --- a/sdk/communication/communication-job-router-rest/generated/isUnexpected.ts +++ /dev/null @@ -1,439 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { - UpsertClassificationPolicy200Response, - UpsertClassificationPolicy201Response, - UpsertClassificationPolicyDefaultResponse, - GetClassificationPolicy200Response, - GetClassificationPolicyDefaultResponse, - DeleteClassificationPolicy204Response, - DeleteClassificationPolicyDefaultResponse, - ListClassificationPolicies200Response, - ListClassificationPoliciesDefaultResponse, - UpsertDistributionPolicy200Response, - UpsertDistributionPolicy201Response, - UpsertDistributionPolicyDefaultResponse, - GetDistributionPolicy200Response, - GetDistributionPolicyDefaultResponse, - DeleteDistributionPolicy204Response, - DeleteDistributionPolicyDefaultResponse, - ListDistributionPolicies200Response, - ListDistributionPoliciesDefaultResponse, - UpsertExceptionPolicy200Response, - UpsertExceptionPolicy201Response, - UpsertExceptionPolicyDefaultResponse, - GetExceptionPolicy200Response, - GetExceptionPolicyDefaultResponse, - DeleteExceptionPolicy204Response, - DeleteExceptionPolicyDefaultResponse, - ListExceptionPolicies200Response, - ListExceptionPoliciesDefaultResponse, - UpsertQueue200Response, - UpsertQueue201Response, - UpsertQueueDefaultResponse, - GetQueue200Response, - GetQueueDefaultResponse, - DeleteQueue204Response, - DeleteQueueDefaultResponse, - ListQueues200Response, - ListQueuesDefaultResponse, - UpsertJob200Response, - UpsertJob201Response, - UpsertJobDefaultResponse, - GetJob200Response, - GetJobDefaultResponse, - DeleteJob204Response, - DeleteJobDefaultResponse, - Reclassify200Response, - ReclassifyDefaultResponse, - Cancel200Response, - CancelDefaultResponse, - Complete200Response, - CompleteDefaultResponse, - Close200Response, - CloseDefaultResponse, - ListJobs200Response, - ListJobsDefaultResponse, - GetInQueuePosition200Response, - GetInQueuePositionDefaultResponse, - Unassign200Response, - UnassignDefaultResponse, - Accept200Response, - AcceptDefaultResponse, - Decline200Response, - DeclineDefaultResponse, - GetQueueStatistics200Response, - GetQueueStatisticsDefaultResponse, - UpsertWorker200Response, - UpsertWorker201Response, - UpsertWorkerDefaultResponse, - GetWorker200Response, - GetWorkerDefaultResponse, - DeleteWorker204Response, - DeleteWorkerDefaultResponse, - ListWorkers200Response, - ListWorkersDefaultResponse, -} from "./responses.js"; - -const responseMap: Record = { - "PATCH /routing/classificationPolicies/{classificationPolicyId}": [ - "200", - "201", - ], - "GET /routing/classificationPolicies/{classificationPolicyId}": ["200"], - "DELETE /routing/classificationPolicies/{classificationPolicyId}": ["204"], - "GET /routing/classificationPolicies": ["200"], - "PATCH /routing/distributionPolicies/{distributionPolicyId}": ["200", "201"], - "GET /routing/distributionPolicies/{distributionPolicyId}": ["200"], - "DELETE /routing/distributionPolicies/{distributionPolicyId}": ["204"], - "GET /routing/distributionPolicies": ["200"], - "PATCH /routing/exceptionPolicies/{exceptionPolicyId}": ["200", "201"], - "GET /routing/exceptionPolicies/{exceptionPolicyId}": ["200"], - "DELETE /routing/exceptionPolicies/{exceptionPolicyId}": ["204"], - "GET /routing/exceptionPolicies": ["200"], - "PATCH /routing/queues/{queueId}": ["200", "201"], - "GET /routing/queues/{queueId}": ["200"], - "DELETE /routing/queues/{queueId}": ["204"], - "GET /routing/queues": ["200"], - "PATCH /routing/jobs/{jobId}": ["200", "201"], - "GET /routing/jobs/{jobId}": ["200"], - "DELETE /routing/jobs/{jobId}": ["204"], - "POST /routing/jobs/{jobId}:reclassify": ["200"], - "POST /routing/jobs/{jobId}:cancel": ["200"], - "POST /routing/jobs/{jobId}/assignments/{assignmentId}:complete": ["200"], - "POST /routing/jobs/{jobId}/assignments/{assignmentId}:close": ["200"], - "GET /routing/jobs": ["200"], - "GET /routing/jobs/{jobId}/position": ["200"], - "POST /routing/jobs/{jobId}/assignments/{assignmentId}:unassign": ["200"], - "POST /routing/workers/{workerId}/offers/{offerId}:accept": ["200"], - "POST /routing/workers/{workerId}/offers/{offerId}:decline": ["200"], - "GET /routing/queues/{queueId}/statistics": ["200"], - "PATCH /routing/workers/{workerId}": ["200", "201"], - "GET /routing/workers/{workerId}": ["200"], - "DELETE /routing/workers/{workerId}": ["204"], - "GET /routing/workers": ["200"], -}; - -export function isUnexpected( - response: - | UpsertClassificationPolicy200Response - | UpsertClassificationPolicy201Response - | UpsertClassificationPolicyDefaultResponse, -): response is UpsertClassificationPolicyDefaultResponse; -export function isUnexpected( - response: - | GetClassificationPolicy200Response - | GetClassificationPolicyDefaultResponse, -): response is GetClassificationPolicyDefaultResponse; -export function isUnexpected( - response: - | DeleteClassificationPolicy204Response - | DeleteClassificationPolicyDefaultResponse, -): response is DeleteClassificationPolicyDefaultResponse; -export function isUnexpected( - response: - | ListClassificationPolicies200Response - | ListClassificationPoliciesDefaultResponse, -): response is ListClassificationPoliciesDefaultResponse; -export function isUnexpected( - response: - | UpsertDistributionPolicy200Response - | UpsertDistributionPolicy201Response - | UpsertDistributionPolicyDefaultResponse, -): response is UpsertDistributionPolicyDefaultResponse; -export function isUnexpected( - response: - | GetDistributionPolicy200Response - | GetDistributionPolicyDefaultResponse, -): response is GetDistributionPolicyDefaultResponse; -export function isUnexpected( - response: - | DeleteDistributionPolicy204Response - | DeleteDistributionPolicyDefaultResponse, -): response is DeleteDistributionPolicyDefaultResponse; -export function isUnexpected( - response: - | ListDistributionPolicies200Response - | ListDistributionPoliciesDefaultResponse, -): response is ListDistributionPoliciesDefaultResponse; -export function isUnexpected( - response: - | UpsertExceptionPolicy200Response - | UpsertExceptionPolicy201Response - | UpsertExceptionPolicyDefaultResponse, -): response is UpsertExceptionPolicyDefaultResponse; -export function isUnexpected( - response: GetExceptionPolicy200Response | GetExceptionPolicyDefaultResponse, -): response is GetExceptionPolicyDefaultResponse; -export function isUnexpected( - response: - | DeleteExceptionPolicy204Response - | DeleteExceptionPolicyDefaultResponse, -): response is DeleteExceptionPolicyDefaultResponse; -export function isUnexpected( - response: - | ListExceptionPolicies200Response - | ListExceptionPoliciesDefaultResponse, -): response is ListExceptionPoliciesDefaultResponse; -export function isUnexpected( - response: - | UpsertQueue200Response - | UpsertQueue201Response - | UpsertQueueDefaultResponse, -): response is UpsertQueueDefaultResponse; -export function isUnexpected( - response: GetQueue200Response | GetQueueDefaultResponse, -): response is GetQueueDefaultResponse; -export function isUnexpected( - response: DeleteQueue204Response | DeleteQueueDefaultResponse, -): response is DeleteQueueDefaultResponse; -export function isUnexpected( - response: ListQueues200Response | ListQueuesDefaultResponse, -): response is ListQueuesDefaultResponse; -export function isUnexpected( - response: - | UpsertJob200Response - | UpsertJob201Response - | UpsertJobDefaultResponse, -): response is UpsertJobDefaultResponse; -export function isUnexpected( - response: GetJob200Response | GetJobDefaultResponse, -): response is GetJobDefaultResponse; -export function isUnexpected( - response: DeleteJob204Response | DeleteJobDefaultResponse, -): response is DeleteJobDefaultResponse; -export function isUnexpected( - response: Reclassify200Response | ReclassifyDefaultResponse, -): response is ReclassifyDefaultResponse; -export function isUnexpected( - response: Cancel200Response | CancelDefaultResponse, -): response is CancelDefaultResponse; -export function isUnexpected( - response: Complete200Response | CompleteDefaultResponse, -): response is CompleteDefaultResponse; -export function isUnexpected( - response: Close200Response | CloseDefaultResponse, -): response is CloseDefaultResponse; -export function isUnexpected( - response: ListJobs200Response | ListJobsDefaultResponse, -): response is ListJobsDefaultResponse; -export function isUnexpected( - response: GetInQueuePosition200Response | GetInQueuePositionDefaultResponse, -): response is GetInQueuePositionDefaultResponse; -export function isUnexpected( - response: Unassign200Response | UnassignDefaultResponse, -): response is UnassignDefaultResponse; -export function isUnexpected( - response: Accept200Response | AcceptDefaultResponse, -): response is AcceptDefaultResponse; -export function isUnexpected( - response: Decline200Response | DeclineDefaultResponse, -): response is DeclineDefaultResponse; -export function isUnexpected( - response: GetQueueStatistics200Response | GetQueueStatisticsDefaultResponse, -): response is GetQueueStatisticsDefaultResponse; -export function isUnexpected( - response: - | UpsertWorker200Response - | UpsertWorker201Response - | UpsertWorkerDefaultResponse, -): response is UpsertWorkerDefaultResponse; -export function isUnexpected( - response: GetWorker200Response | GetWorkerDefaultResponse, -): response is GetWorkerDefaultResponse; -export function isUnexpected( - response: DeleteWorker204Response | DeleteWorkerDefaultResponse, -): response is DeleteWorkerDefaultResponse; -export function isUnexpected( - response: ListWorkers200Response | ListWorkersDefaultResponse, -): response is ListWorkersDefaultResponse; -export function isUnexpected( - response: - | UpsertClassificationPolicy200Response - | UpsertClassificationPolicy201Response - | UpsertClassificationPolicyDefaultResponse - | GetClassificationPolicy200Response - | GetClassificationPolicyDefaultResponse - | DeleteClassificationPolicy204Response - | DeleteClassificationPolicyDefaultResponse - | ListClassificationPolicies200Response - | ListClassificationPoliciesDefaultResponse - | UpsertDistributionPolicy200Response - | UpsertDistributionPolicy201Response - | UpsertDistributionPolicyDefaultResponse - | GetDistributionPolicy200Response - | GetDistributionPolicyDefaultResponse - | DeleteDistributionPolicy204Response - | DeleteDistributionPolicyDefaultResponse - | ListDistributionPolicies200Response - | ListDistributionPoliciesDefaultResponse - | UpsertExceptionPolicy200Response - | UpsertExceptionPolicy201Response - | UpsertExceptionPolicyDefaultResponse - | GetExceptionPolicy200Response - | GetExceptionPolicyDefaultResponse - | DeleteExceptionPolicy204Response - | DeleteExceptionPolicyDefaultResponse - | ListExceptionPolicies200Response - | ListExceptionPoliciesDefaultResponse - | UpsertQueue200Response - | UpsertQueue201Response - | UpsertQueueDefaultResponse - | GetQueue200Response - | GetQueueDefaultResponse - | DeleteQueue204Response - | DeleteQueueDefaultResponse - | ListQueues200Response - | ListQueuesDefaultResponse - | UpsertJob200Response - | UpsertJob201Response - | UpsertJobDefaultResponse - | GetJob200Response - | GetJobDefaultResponse - | DeleteJob204Response - | DeleteJobDefaultResponse - | Reclassify200Response - | ReclassifyDefaultResponse - | Cancel200Response - | CancelDefaultResponse - | Complete200Response - | CompleteDefaultResponse - | Close200Response - | CloseDefaultResponse - | ListJobs200Response - | ListJobsDefaultResponse - | GetInQueuePosition200Response - | GetInQueuePositionDefaultResponse - | Unassign200Response - | UnassignDefaultResponse - | Accept200Response - | AcceptDefaultResponse - | Decline200Response - | DeclineDefaultResponse - | GetQueueStatistics200Response - | GetQueueStatisticsDefaultResponse - | UpsertWorker200Response - | UpsertWorker201Response - | UpsertWorkerDefaultResponse - | GetWorker200Response - | GetWorkerDefaultResponse - | DeleteWorker204Response - | DeleteWorkerDefaultResponse - | ListWorkers200Response - | ListWorkersDefaultResponse, -): response is - | UpsertClassificationPolicyDefaultResponse - | GetClassificationPolicyDefaultResponse - | DeleteClassificationPolicyDefaultResponse - | ListClassificationPoliciesDefaultResponse - | UpsertDistributionPolicyDefaultResponse - | GetDistributionPolicyDefaultResponse - | DeleteDistributionPolicyDefaultResponse - | ListDistributionPoliciesDefaultResponse - | UpsertExceptionPolicyDefaultResponse - | GetExceptionPolicyDefaultResponse - | DeleteExceptionPolicyDefaultResponse - | ListExceptionPoliciesDefaultResponse - | UpsertQueueDefaultResponse - | GetQueueDefaultResponse - | DeleteQueueDefaultResponse - | ListQueuesDefaultResponse - | UpsertJobDefaultResponse - | GetJobDefaultResponse - | DeleteJobDefaultResponse - | ReclassifyDefaultResponse - | CancelDefaultResponse - | CompleteDefaultResponse - | CloseDefaultResponse - | ListJobsDefaultResponse - | GetInQueuePositionDefaultResponse - | UnassignDefaultResponse - | AcceptDefaultResponse - | DeclineDefaultResponse - | GetQueueStatisticsDefaultResponse - | UpsertWorkerDefaultResponse - | GetWorkerDefaultResponse - | DeleteWorkerDefaultResponse - | ListWorkersDefaultResponse { - const lroOriginal = response.headers["x-ms-original-url"]; - const url = new URL(lroOriginal ?? response.request.url); - const method = response.request.method; - let pathDetails = responseMap[`${method} ${url.pathname}`]; - if (!pathDetails) { - pathDetails = getParametrizedPathSuccess(method, url.pathname); - } - return !pathDetails.includes(response.status); -} - -function getParametrizedPathSuccess(method: string, path: string): string[] { - const pathParts = path.split("/"); - - // Traverse list to match the longest candidate - // matchedLen: the length of candidate path - // matchedValue: the matched status code array - let matchedLen = -1, - matchedValue: string[] = []; - - // Iterate the responseMap to find a match - for (const [key, value] of Object.entries(responseMap)) { - // Extracting the path from the map key which is in format - // GET /path/foo - if (!key.startsWith(method)) { - continue; - } - const candidatePath = getPathFromMapKey(key); - // Get each part of the url path - const candidateParts = candidatePath.split("/"); - - // track if we have found a match to return the values found. - let found = true; - for ( - let i = candidateParts.length - 1, j = pathParts.length - 1; - i >= 1 && j >= 1; - i--, j-- - ) { - if ( - candidateParts[i]?.startsWith("{") && - candidateParts[i]?.indexOf("}") !== -1 - ) { - const start = candidateParts[i]!.indexOf("}") + 1, - end = candidateParts[i]?.length; - // If the current part of the candidate is a "template" part - // Try to use the suffix of pattern to match the path - // {guid} ==> $ - // {guid}:export ==> :export$ - const isMatched = new RegExp( - `${candidateParts[i]?.slice(start, end)}`, - ).test(pathParts[j] || ""); - - if (!isMatched) { - found = false; - break; - } - continue; - } - - // If the candidate part is not a template and - // the parts don't match mark the candidate as not found - // to move on with the next candidate path. - if (candidateParts[i] !== pathParts[j]) { - found = false; - break; - } - } - - // We finished evaluating the current candidate parts - // Update the matched value if and only if we found the longer pattern - if (found && candidatePath.length > matchedLen) { - matchedLen = candidatePath.length; - matchedValue = value; - } - } - return matchedValue; -} - -function getPathFromMapKey(mapKey: string): string { - const pathStart = mapKey.indexOf("/"); - return mapKey.slice(pathStart); -} diff --git a/sdk/communication/communication-job-router-rest/generated/logger.ts b/sdk/communication/communication-job-router-rest/generated/logger.ts deleted file mode 100644 index b6132440690f..000000000000 --- a/sdk/communication/communication-job-router-rest/generated/logger.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - - -import { createClientLogger } from "@azure/logger"; -export const logger = createClientLogger("communication-job-router"); diff --git a/sdk/communication/communication-job-router-rest/generated/models.ts b/sdk/communication/communication-job-router-rest/generated/models.ts deleted file mode 100644 index 45c45224ec50..000000000000 --- a/sdk/communication/communication-job-router-rest/generated/models.ts +++ /dev/null @@ -1,665 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - - -/** A container for the rules that govern how jobs are classified. */ -export interface ClassificationPolicy { - /** Friendly name of this policy. */ - name?: string; - /** Id of a fallback queue to select if queue selector attachments doesn't find a match. */ - fallbackQueueId?: string; - /** Queue selector attachments used to resolve a queue for a job. */ - queueSelectorAttachments?: Array; - /** A rule to determine a priority score for a job. */ - prioritizationRule?: RouterRule; - /** Worker selector attachments used to attach worker selectors to a job. */ - workerSelectorAttachments?: Array; -} - -/** An attachment of queue selectors to resolve a queue to a job from a classification policy. */ -export interface QueueSelectorAttachmentParent { - kind: QueueSelectorAttachmentKind; -} - -/** Describes a set of queue selectors that will be attached if the given condition resolves to true. */ -export interface ConditionalQueueSelectorAttachment - extends QueueSelectorAttachmentParent { - /** The condition that must be true for the queue selectors to be attached. */ - condition: RouterRule; - /** The queue selectors to attach. */ - queueSelectors: Array; - /** The type discriminator describing the type of queue selector attachment. */ - kind: "conditional"; -} - -/** - * A rule of one of the following types: - * StaticRule: A rule providing static rules that always return the same result, regardless of input. - * DirectMapRule: A rule that return the same labels as the input labels. - * ExpressionRule: A rule providing inline expression rules. - * FunctionRule: A rule providing a binding to an HTTP Triggered Azure Function. - * WebhookRule: A rule providing a binding to a webserver following OAuth2.0 authentication protocol. - */ -export interface RouterRuleParent { - kind: RouterRuleKind; -} - -/** A rule that return the same labels as the input labels. */ -export interface DirectMapRouterRule extends RouterRuleParent { - /** The type discriminator describing a sub-type of Rule. */ - kind: "directMap"; -} - -/** A rule providing inline expression rules. */ -export interface ExpressionRouterRule extends RouterRuleParent { - /** - * The expression language to compile to and execute. - * - * Possible values: "powerFx" - */ - language?: ExpressionRouterRuleLanguage; - /** An expression to evaluate. Should contain return statement with calculated values. */ - expression: string; - /** The type discriminator describing a sub-type of Rule. */ - kind: "expression"; -} - -/** A rule providing a binding to an HTTP Triggered Azure Function. */ -export interface FunctionRouterRule extends RouterRuleParent { - /** URL for Azure Function. */ - functionUri: string; - /** Credentials used to access Azure function rule. */ - credential?: FunctionRouterRuleCredential; - /** The type discriminator describing a sub-type of Rule. */ - kind: "function"; -} - -/** Credentials used to access Azure function rule. */ -export interface FunctionRouterRuleCredential { - /** Access key scoped to a particular function. */ - functionKey?: string; - /** Access key scoped to a Azure Function app. This key grants access to all functions under the app. */ - appKey?: string; - /** Client id, when AppKey is provided In context of Azure function, this is usually the name of the key. */ - clientId?: string; -} - -/** A rule providing static rules that always return the same result, regardless of input. */ -export interface StaticRouterRule extends RouterRuleParent { - /** The static value this rule always returns. Values must be primitive values - number, string, boolean. */ - value?: unknown; - /** The type discriminator describing a sub-type of Rule. */ - kind: "static"; -} - -/** A rule providing a binding to an external web server. */ -export interface WebhookRouterRule extends RouterRuleParent { - /** Uri for Authorization Server. */ - authorizationServerUri?: string; - /** OAuth2.0 Credentials used to Contoso's Authorization server. Reference: https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ */ - clientCredential?: OAuth2WebhookClientCredential; - /** Uri for Contoso's Web Server. */ - webhookUri?: string; - /** The type discriminator describing a sub-type of Rule. */ - kind: "webhook"; -} - -/** OAuth2.0 Credentials used to Contoso's Authorization server. Reference: https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ */ -export interface OAuth2WebhookClientCredential { - /** ClientId for Contoso Authorization server. */ - clientId?: string; - /** Client secret for Contoso Authorization server. */ - clientSecret?: string; -} - -/** Describes a condition that must be met against a set of labels for queue selection. */ -export interface RouterQueueSelector { - /** The label key to query against. */ - key: string; - /** - * Describes how the value of the label is compared to the value defined on the label selector. - * - * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" - */ - labelOperator: LabelOperator; - /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ - value?: unknown; -} - -/** Attaches a queue selector where the value is passed through from a job's label with the same key. */ -export interface PassThroughQueueSelectorAttachment - extends QueueSelectorAttachmentParent { - /** The label key to query against. */ - key: string; - /** - * Describes how the value of the label is compared to the value pass through. - * - * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" - */ - labelOperator: LabelOperator; - /** The type discriminator describing the type of queue selector attachment. */ - kind: "passThrough"; -} - -/** Attaches queue selectors to a job when the RouterRule is resolved. */ -export interface RuleEngineQueueSelectorAttachment - extends QueueSelectorAttachmentParent { - /** A RouterRule that resolves a collection of queue selectors to attach. */ - rule: RouterRule; - /** The type discriminator describing the type of queue selector attachment. */ - kind: "ruleEngine"; -} - -/** Describes a queue selector that will be attached to a job. */ -export interface StaticQueueSelectorAttachment - extends QueueSelectorAttachmentParent { - /** The queue selector to attach. */ - queueSelector: RouterQueueSelector; - /** The type discriminator describing the type of queue selector attachment. */ - kind: "static"; -} - -/** Describes multiple sets of queue selectors, of which one will be selected and attached according to a weighting. */ -export interface WeightedAllocationQueueSelectorAttachment - extends QueueSelectorAttachmentParent { - /** A collection of percentage based weighted allocations. */ - allocations: Array; - /** The type discriminator describing the type of queue selector attachment. */ - kind: "weightedAllocation"; -} - -/** Contains the weight percentage and queue selectors to be applied if selected for weighted distributions. */ -export interface QueueWeightedAllocation { - /** The percentage of this weight, expressed as a fraction of 1. */ - weight: number; - /** A collection of queue selectors that will be applied if this allocation is selected. */ - queueSelectors: Array; -} - -/** An attachment which attaches worker selectors to a job. */ -export interface WorkerSelectorAttachmentParent { - kind: WorkerSelectorAttachmentKind; -} - -/** Describes a set of worker selectors that will be attached if the given condition resolves to true. */ -export interface ConditionalWorkerSelectorAttachment - extends WorkerSelectorAttachmentParent { - /** The condition that must be true for the worker selectors to be attached. */ - condition: RouterRule; - /** The worker selectors to attach. */ - workerSelectors: Array; - /** The type discriminator describing the type of worker selector attachment. */ - kind: "conditional"; -} - -/** Describes a condition that must be met against a set of labels for worker selection. */ -export interface RouterWorkerSelector { - /** The label key to query against. */ - key: string; - /** - * Describes how the value of the label is compared to the value defined on the worker selector. - * - * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" - */ - labelOperator: LabelOperator; - /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ - value?: unknown; - /** Describes how long this label selector is valid in seconds. */ - expiresAfterSeconds?: number; - /** Pushes a job to the front of the queue as long as this selector is active. */ - expedite?: boolean; -} - -/** Attaches a worker selector where the value is passed through from a job's label with the same key. */ -export interface PassThroughWorkerSelectorAttachment - extends WorkerSelectorAttachmentParent { - /** The label key to query against. */ - key: string; - /** - * Describes how the value of the label is compared to the value pass through. - * - * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" - */ - labelOperator: LabelOperator; - /** Describes how long the attached label selector is valid in seconds. */ - expiresAfterSeconds?: number; - /** The type discriminator describing the type of worker selector attachment. */ - kind: "passThrough"; -} - -/** Attaches worker selectors to a job when a RouterRule is resolved. */ -export interface RuleEngineWorkerSelectorAttachment - extends WorkerSelectorAttachmentParent { - /** A RouterRule that resolves a collection of worker selectors to attach. */ - rule: RouterRule; - /** The type discriminator describing the type of worker selector attachment. */ - kind: "ruleEngine"; -} - -/** Describes a worker selector that will be attached to a job. */ -export interface StaticWorkerSelectorAttachment - extends WorkerSelectorAttachmentParent { - /** The worker selector to attach. */ - workerSelector: RouterWorkerSelector; - /** The type discriminator describing the type of worker selector attachment. */ - kind: "static"; -} - -/** Describes multiple sets of worker selectors, of which one will be selected and attached according to a weighting. */ -export interface WeightedAllocationWorkerSelectorAttachment - extends WorkerSelectorAttachmentParent { - /** A collection of percentage based weighted allocations. */ - allocations: Array; - /** The type discriminator describing the type of worker selector attachment. */ - kind: "weightedAllocation"; -} - -/** Contains the weight percentage and worker selectors to be applied if selected for weighted distributions. */ -export interface WorkerWeightedAllocation { - /** The percentage of this weight, expressed as a fraction of 1. */ - weight: number; - /** A collection of worker selectors that will be applied if this allocation is selected. */ - workerSelectors: Array; -} - -/** Policy governing how jobs are distributed to workers */ -export interface DistributionPolicy { - /** Friendly name of this policy. */ - name?: string; - /** Number of seconds after which any offers created under this policy will be expired. */ - offerExpiresAfterSeconds?: number; - /** Mode governing the specific distribution method. */ - mode?: DistributionMode; -} - -/** Abstract base class for defining a distribution mode. */ -export interface DistributionModeParent { - /** Governs the minimum desired number of active concurrent offers a job can have. */ - minConcurrentOffers?: number; - /** Governs the maximum number of active concurrent offers a job can have. */ - maxConcurrentOffers?: number; - /** If set to true, then router will match workers to jobs even if they don't match label selectors. Warning: You may get workers that are not qualified for a job they are matched with if you set this variable to true. This flag is intended more for temporary usage. By default, set to false. */ - bypassSelectors?: boolean; - kind: DistributionModeKind; -} - -/** Jobs are distributed to the worker with the strongest abilities available. */ -export interface BestWorkerMode extends DistributionModeParent { - /** Define a scoring rule to use, when calculating a score to determine the best worker. If not set, will use a default scoring formula that uses the number of job labels that the worker labels match, as well as the number of label selectors the worker labels match and/or exceed using a logistic function (https://en.wikipedia.org/wiki/Logistic_function). */ - scoringRule?: RouterRule; - /** Options to configure 'scoringRule'. If not set, default values are used. */ - scoringRuleOptions?: ScoringRuleOptions; - /** The type discriminator describing a sub-type of Mode */ - kind: "bestWorker"; -} - -/** Encapsulates all options that can be passed as parameters for scoring rule with BestWorkerMode. */ -export interface ScoringRuleOptions { - /** Set batch size when 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. */ - batchSize?: number; - /** List of extra parameters from a job that will be sent as part of the payload to scoring rule. If not set, a job's labels (sent in the payload as `job`) and a job's worker selectors (sent in the payload as `selectors`) are added to the payload of the scoring rule by default. Note: Worker labels are always sent with scoring payload. */ - scoringParameters?: ScoringRuleParameterSelector[]; - /** If set to true, will score workers in batches, and the parameter name of the worker labels will be sent as `workers`. By default, set to false and the parameter name for the worker labels will be sent as `worker`. Note: If enabled, use 'batchSize' to set batch size. */ - isBatchScoringEnabled?: boolean; - /** If false, will sort scores by ascending order. By default, set to true. */ - descendingOrder?: boolean; -} - -/** Jobs are directed to the worker who has been idle longest. */ -export interface LongestIdleMode extends DistributionModeParent { - /** The type discriminator describing a sub-type of Mode. */ - kind: "longestIdle"; -} - -/** Jobs are distributed in order to workers, starting with the worker that is after the last worker to receive a job. */ -export interface RoundRobinMode extends DistributionModeParent { - /** The type discriminator describing a sub-type of Mode. */ - kind: "roundRobin"; -} - -/** A policy that defines actions to execute when exception are triggered. */ -export interface ExceptionPolicy { - /** Friendly name of this policy. */ - name?: string; - /** A collection of exception rules on the exception policy. */ - exceptionRules?: Array; -} - -/** A rule that defines actions to execute upon a specific trigger. */ -export interface ExceptionRule { - /** Id of an exception rule. */ - id: string; - /** The trigger for this exception rule. */ - trigger: ExceptionTrigger; - /** A collection of actions to perform once the exception is triggered. */ - actions: Array; -} - -/** Abstract base class for defining a trigger for exception rules. */ -export interface ExceptionTriggerParent { - kind: ExceptionTriggerKind; -} - -/** Trigger for an exception action on exceeding queue length. */ -export interface QueueLengthExceptionTrigger extends ExceptionTriggerParent { - /** Threshold of number of jobs ahead in the queue to for this trigger to fire. */ - threshold: number; - /** The type discriminator describing a sub-type of ExceptionTrigger. */ - kind: "queueLength"; -} - -/** Trigger for an exception action on exceeding wait time. */ -export interface WaitTimeExceptionTrigger extends ExceptionTriggerParent { - /** Threshold for wait time for this trigger. */ - thresholdSeconds: number; - /** The type discriminator describing a sub-type of ExceptionTrigger. */ - kind: "waitTime"; -} - -/** The action to take when the exception is triggered. */ -export interface ExceptionActionParent { - /** Unique Id of the exception action. */ - id?: string; - kind: ExceptionActionKind; -} - -/** An action that marks a job as cancelled. */ -export interface CancelExceptionAction extends ExceptionActionParent { - /** A note that will be appended to a job's notes collection with the current timestamp. */ - note?: string; - /** Indicates the outcome of a job, populate this field with your own custom values. */ - dispositionCode?: string; - /** The type discriminator describing a sub-type of ExceptionAction. */ - kind: "cancel"; -} - -/** An action that manually reclassifies a job by providing the queue, priority and worker selectors. */ -export interface ManualReclassifyExceptionAction extends ExceptionActionParent { - /** Updated QueueId. */ - queueId?: string; - /** Updated Priority. */ - priority?: number; - /** Updated WorkerSelectors. */ - workerSelectors?: Array; - /** The type discriminator describing a sub-type of ExceptionAction. */ - kind: "manualReclassify"; -} - -/** An action that modifies labels on a job and then reclassifies it. */ -export interface ReclassifyExceptionAction extends ExceptionActionParent { - /** The new classification policy that will determine queue, priority and worker selectors. */ - classificationPolicyId?: string; - /** Dictionary containing the labels to update (or add if not existing) in key-value pairs. Values must be primitive values - number, string, boolean. */ - labelsToUpsert?: Record; - /** The type discriminator describing a sub-type of ExceptionAction. */ - kind: "reclassify"; -} - -/** A queue that can contain jobs to be routed. */ -export interface RouterQueue { - /** Friendly name of this queue. */ - name?: string; - /** Id of a distribution policy that will determine how a job is distributed to workers. */ - distributionPolicyId?: string; - /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ - labels?: Record; - /** Id of an exception policy that determines various job escalation rules. */ - exceptionPolicyId?: string; -} - -/** A unit of work to be routed */ -export interface RouterJob { - /** Reference to an external parent context, eg. call ID. */ - channelReference?: string; - /** The channel identifier. eg. voice, chat, etc. */ - channelId?: string; - /** Id of a classification policy used for classifying this job. */ - classificationPolicyId?: string; - /** Id of a queue that this job is queued to. */ - queueId?: string; - /** Priority of this job. Value must be between -100 to 100. */ - priority?: number; - /** Reason code for cancelled or closed jobs. */ - dispositionCode?: string; - /** A collection of manually specified worker selectors, which a worker must satisfy in order to process this job. */ - requestedWorkerSelectors?: Array; - /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ - labels?: Record; - /** A set of non-identifying attributes attached to this job. Values must be primitive values - number, string, boolean. */ - tags?: Record; - /** Notes attached to a job, sorted by timestamp. */ - notes?: Array; - /** If provided, will determine how job matching will be carried out. Default mode: QueueAndMatchMode. */ - matchingMode?: JobMatchingMode; -} - -/** Assignment details of a job to a worker. */ -export interface RouterJobAssignment { - /** Id of the Worker assigned to the job. */ - workerId?: string; - /** Timestamp when the job was assigned to a worker in UTC. */ - assignedAt: Date | string; - /** Timestamp when the job was marked as completed after being assigned in UTC. */ - completedAt?: Date | string; - /** Timestamp when the job was marked as closed after being completed in UTC. */ - closedAt?: Date | string; -} - -/** A note attached to a job. */ -export interface RouterJobNote { - /** The message contained in the note. */ - message: string; - /** The time at which the note was added in UTC. If not provided, will default to the current time. */ - addedAt?: Date | string; -} - -/** - * A matching mode of one of the following types: - * QueueAndMatchMode: Used when matching worker to a job is required to be done right after job is queued. - * ScheduleAndSuspendMode: Used for scheduling jobs to be queued at a future time. At specified time, matching of a worker to the job will not start automatically. - * SuspendMode: Used when matching workers to a job needs to be suspended. - */ -export interface JobMatchingModeParent { - kind: JobMatchingModeKind; -} - -/** Describes a matching mode used for scheduling jobs to be queued at a future time. At the specified time, matching worker to a job will not start automatically. */ -export interface ScheduleAndSuspendMode extends JobMatchingModeParent { - /** Requested schedule time. */ - scheduleAt: Date | string; - /** The type discriminator describing ScheduleAndSuspendMode */ - kind: "scheduleAndSuspend"; -} - -/** Describes a matching mode where matching worker to a job is automatically started after job is queued successfully. */ -export interface QueueAndMatchMode extends JobMatchingModeParent { - /** The type discriminator describing QueueAndMatchMode */ - kind: "queueAndMatch"; -} - -/** Describes a matching mode where matching worker to a job is suspended. */ -export interface SuspendMode extends JobMatchingModeParent { - /** The type discriminator describing SuspendMode */ - kind: "suspend"; -} - -/** Request payload for reclassifying jobs. */ -export interface ReclassifyJobOptions { } - -/** Request payload for cancelling a job. */ -export interface CancelJobOptions { - /** A note that will be appended to a job's Notes collection with the current timestamp. */ - note?: string; - /** Indicates the outcome of a job, populate this field with your own custom values. If not provided, default value of "Cancelled" is set. */ - dispositionCode?: string; -} - -/** Request payload for completing jobs. */ -export interface CompleteJobOptions { - /** A note that will be appended to a job's Notes collection with the current timestamp. */ - note?: string; -} - -/** Request payload for closing jobs */ -export interface CloseJobOptions { - /** Indicates the outcome of a job, populate this field with your own custom values. */ - dispositionCode?: string; - /** If not provided, worker capacity is released immediately along with a JobClosedEvent notification. If provided, worker capacity is released along with a JobClosedEvent notification at a future time in UTC. */ - closeAt?: Date | string; - /** A note that will be appended to a job's Notes collection with the current timestamp. */ - note?: string; -} - -/** Request payload for unassigning a job. */ -export interface UnassignJobOptions { - /** If SuspendMatching is true, then a job is not queued for re-matching with a worker. */ - suspendMatching?: boolean; -} - -/** Request payload for declining offers. */ -export interface DeclineJobOfferOptions { - /** If the RetryOfferAt is not provided, then this job will not be offered again to the worker who declined this job unless the worker is de-registered and re-registered. If a RetryOfferAt time is provided, then the job will be re-matched to eligible workers at the retry time in UTC. The worker that declined the job will also be eligible for the job at that time. */ - retryOfferAt?: Date | string; -} - -/** An entity for jobs to be routed to. */ -export interface RouterWorker { - /** Collection of queue(s) that this worker can receive work from. */ - queues?: string[]; - /** The total capacity score this worker has to manage multiple concurrent jobs. */ - capacity?: number; - /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ - labels?: Record; - /** A set of non-identifying attributes attached to this worker. Values must be primitive values - number, string, boolean. */ - tags?: Record; - /** Collection of channel(s) this worker can handle and their impact on the workers capacity. */ - channels?: Array; - /** A flag indicating this worker is open to receive offers or not. */ - availableForOffers?: boolean; - /** If this is set, the worker will only receive up to this many new offers at a time. */ - maxConcurrentOffers?: number; -} - -/** Represents the capacity a job in this channel will consume from a worker. */ -export interface RouterChannel { - /** Id of a channel. */ - channelId: string; - /** The amount of capacity that an instance of a job of this channel will consume of the total worker capacity. */ - capacityCostPerJob: number; - /** The maximum number of jobs that can be supported concurrently for this channel. Value must be greater than zero. */ - maxNumberOfJobs?: number; -} - -/** An offer of a job to a worker. */ -export interface RouterJobOffer { - /** Id of the job. */ - jobId: string; - /** The capacity cost consumed by the job offer. */ - capacityCost: number; - /** Timestamp when the offer was created in UTC. */ - offeredAt?: Date | string; - /** Timestamp when the offer will expire in UTC. */ - expiresAt?: Date | string; -} - -/** The assignment for a worker to a job. */ -export interface RouterWorkerAssignment { - /** Id of the assignment. */ - assignmentId: string; - /** Id of the job assigned. */ - jobId: string; - /** The amount of capacity this assignment has consumed on the worker. */ - capacityCost: number; - /** The assignment time of the job in UTC. */ - assignedAt: Date | string; -} - -/** An attachment of queue selectors to resolve a queue to a job from a classification policy. */ -export type QueueSelectorAttachment = - | QueueSelectorAttachmentParent - | ConditionalQueueSelectorAttachment - | PassThroughQueueSelectorAttachment - | RuleEngineQueueSelectorAttachment - | StaticQueueSelectorAttachment - | WeightedAllocationQueueSelectorAttachment; -/** - * A rule of one of the following types: - * StaticRule: A rule providing static rules that always return the same result, regardless of input. - * DirectMapRule: A rule that return the same labels as the input labels. - * ExpressionRule: A rule providing inline expression rules. - * FunctionRule: A rule providing a binding to an HTTP Triggered Azure Function. - * WebhookRule: A rule providing a binding to a webserver following OAuth2.0 authentication protocol. - */ -export type RouterRule = - | RouterRuleParent - | DirectMapRouterRule - | ExpressionRouterRule - | FunctionRouterRule - | StaticRouterRule - | WebhookRouterRule; -/** An attachment which attaches worker selectors to a job. */ -export type WorkerSelectorAttachment = - | WorkerSelectorAttachmentParent - | ConditionalWorkerSelectorAttachment - | PassThroughWorkerSelectorAttachment - | RuleEngineWorkerSelectorAttachment - | StaticWorkerSelectorAttachment - | WeightedAllocationWorkerSelectorAttachment; -/** Abstract base class for defining a distribution mode. */ -export type DistributionMode = - | DistributionModeParent - | BestWorkerMode - | LongestIdleMode - | RoundRobinMode; -/** Abstract base class for defining a trigger for exception rules. */ -export type ExceptionTrigger = - | ExceptionTriggerParent - | QueueLengthExceptionTrigger - | WaitTimeExceptionTrigger; -/** The action to take when the exception is triggered. */ -export type ExceptionAction = - | ExceptionActionParent - | CancelExceptionAction - | ManualReclassifyExceptionAction - | ReclassifyExceptionAction; -/** - * A matching mode of one of the following types: - * QueueAndMatchMode: Used when matching worker to a job is required to be done right after job is queued. - * ScheduleAndSuspendMode: Used for scheduling jobs to be queued at a future time. At specified time, matching of a worker to the job will not start automatically. - * SuspendMode: Used when matching workers to a job needs to be suspended. - */ -export type JobMatchingMode = - | JobMatchingModeParent - | ScheduleAndSuspendMode - | QueueAndMatchMode - | SuspendMode; -/** Alias for QueueSelectorAttachmentKind */ -export type QueueSelectorAttachmentKind = string; -/** Alias for RouterRuleKind */ -export type RouterRuleKind = string; -/** Alias for ExpressionRouterRuleLanguage */ -export type ExpressionRouterRuleLanguage = string; -/** Alias for LabelOperator */ -export type LabelOperator = string; -/** Alias for WorkerSelectorAttachmentKind */ -export type WorkerSelectorAttachmentKind = string; -/** Alias for RouterWorkerSelectorStatus */ -export type RouterWorkerSelectorStatus = string; -/** Alias for DistributionModeKind */ -export type DistributionModeKind = string; -/** Alias for ScoringRuleParameterSelector */ -export type ScoringRuleParameterSelector = string; -/** Alias for ExceptionTriggerKind */ -export type ExceptionTriggerKind = string; -/** Alias for ExceptionActionKind */ -export type ExceptionActionKind = string; -/** Alias for RouterJobStatus */ -export type RouterJobStatus = string; -/** Alias for JobMatchingModeKind */ -export type JobMatchingModeKind = string; -/** Alias for RouterJobStatusSelector */ -export type RouterJobStatusSelector = string; -/** Alias for RouterWorkerState */ -export type RouterWorkerState = string; -/** Alias for RouterWorkerStateSelector */ -export type RouterWorkerStateSelector = string; diff --git a/sdk/communication/communication-job-router-rest/generated/outputModels.ts b/sdk/communication/communication-job-router-rest/generated/outputModels.ts deleted file mode 100644 index ccc072ce07c3..000000000000 --- a/sdk/communication/communication-job-router-rest/generated/outputModels.ts +++ /dev/null @@ -1,797 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - - -/** A container for the rules that govern how jobs are classified. */ -export interface ClassificationPolicyOutput { - /** The entity tag for this resource. */ - readonly etag: string; - /** Id of a classification policy. */ - readonly id: string; - /** Friendly name of this policy. */ - name?: string; - /** Id of a fallback queue to select if queue selector attachments doesn't find a match. */ - fallbackQueueId?: string; - /** Queue selector attachments used to resolve a queue for a job. */ - queueSelectorAttachments?: Array; - /** A rule to determine a priority score for a job. */ - prioritizationRule?: RouterRuleOutput; - /** Worker selector attachments used to attach worker selectors to a job. */ - workerSelectorAttachments?: Array; -} - -/** An attachment of queue selectors to resolve a queue to a job from a classification policy. */ -export interface QueueSelectorAttachmentOutputParent { - kind: QueueSelectorAttachmentKindOutput; -} - -/** Describes a set of queue selectors that will be attached if the given condition resolves to true. */ -export interface ConditionalQueueSelectorAttachmentOutput - extends QueueSelectorAttachmentOutputParent { - /** The condition that must be true for the queue selectors to be attached. */ - condition: RouterRuleOutput; - /** The queue selectors to attach. */ - queueSelectors: Array; - /** The type discriminator describing the type of queue selector attachment. */ - kind: "conditional"; -} - -/** - * A rule of one of the following types: - * StaticRule: A rule providing static rules that always return the same result, regardless of input. - * DirectMapRule: A rule that return the same labels as the input labels. - * ExpressionRule: A rule providing inline expression rules. - * FunctionRule: A rule providing a binding to an HTTP Triggered Azure Function. - * WebhookRule: A rule providing a binding to a webserver following OAuth2.0 authentication protocol. - */ -export interface RouterRuleOutputParent { - kind: RouterRuleKindOutput; -} - -/** A rule that return the same labels as the input labels. */ -export interface DirectMapRouterRuleOutput extends RouterRuleOutputParent { - /** The type discriminator describing a sub-type of Rule. */ - kind: "directMap"; -} - -/** A rule providing inline expression rules. */ -export interface ExpressionRouterRuleOutput extends RouterRuleOutputParent { - /** - * The expression language to compile to and execute. - * - * Possible values: "powerFx" - */ - language?: ExpressionRouterRuleLanguageOutput; - /** An expression to evaluate. Should contain return statement with calculated values. */ - expression: string; - /** The type discriminator describing a sub-type of Rule. */ - kind: "expression"; -} - -/** A rule providing a binding to an HTTP Triggered Azure Function. */ -export interface FunctionRouterRuleOutput extends RouterRuleOutputParent { - /** URL for Azure Function. */ - functionUri: string; - /** Credentials used to access Azure function rule. */ - credential?: FunctionRouterRuleCredentialOutput; - /** The type discriminator describing a sub-type of Rule. */ - kind: "function"; -} - -/** Credentials used to access Azure function rule. */ -export interface FunctionRouterRuleCredentialOutput { - /** Access key scoped to a particular function. */ - functionKey?: string; - /** Access key scoped to a Azure Function app. This key grants access to all functions under the app. */ - appKey?: string; - /** Client id, when AppKey is provided In context of Azure function, this is usually the name of the key. */ - clientId?: string; -} - -/** A rule providing static rules that always return the same result, regardless of input. */ -export interface StaticRouterRuleOutput extends RouterRuleOutputParent { - /** The static value this rule always returns. Values must be primitive values - number, string, boolean. */ - value?: any; - /** The type discriminator describing a sub-type of Rule. */ - kind: "static"; -} - -/** A rule providing a binding to an external web server. */ -export interface WebhookRouterRuleOutput extends RouterRuleOutputParent { - /** Uri for Authorization Server. */ - authorizationServerUri?: string; - /** OAuth2.0 Credentials used to Contoso's Authorization server. Reference: https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ */ - clientCredential?: OAuth2WebhookClientCredentialOutput; - /** Uri for Contoso's Web Server. */ - webhookUri?: string; - /** The type discriminator describing a sub-type of Rule. */ - kind: "webhook"; -} - -/** OAuth2.0 Credentials used to Contoso's Authorization server. Reference: https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ */ -export interface OAuth2WebhookClientCredentialOutput { - /** ClientId for Contoso Authorization server. */ - clientId?: string; - /** Client secret for Contoso Authorization server. */ - clientSecret?: string; -} - -/** Describes a condition that must be met against a set of labels for queue selection. */ -export interface RouterQueueSelectorOutput { - /** The label key to query against. */ - key: string; - /** - * Describes how the value of the label is compared to the value defined on the label selector. - * - * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" - */ - labelOperator: LabelOperatorOutput; - /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ - value?: any; -} - -/** Attaches a queue selector where the value is passed through from a job's label with the same key. */ -export interface PassThroughQueueSelectorAttachmentOutput - extends QueueSelectorAttachmentOutputParent { - /** The label key to query against. */ - key: string; - /** - * Describes how the value of the label is compared to the value pass through. - * - * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" - */ - labelOperator: LabelOperatorOutput; - /** The type discriminator describing the type of queue selector attachment. */ - kind: "passThrough"; -} - -/** Attaches queue selectors to a job when the RouterRule is resolved. */ -export interface RuleEngineQueueSelectorAttachmentOutput - extends QueueSelectorAttachmentOutputParent { - /** A RouterRule that resolves a collection of queue selectors to attach. */ - rule: RouterRuleOutput; - /** The type discriminator describing the type of queue selector attachment. */ - kind: "ruleEngine"; -} - -/** Describes a queue selector that will be attached to a job. */ -export interface StaticQueueSelectorAttachmentOutput - extends QueueSelectorAttachmentOutputParent { - /** The queue selector to attach. */ - queueSelector: RouterQueueSelectorOutput; - /** The type discriminator describing the type of queue selector attachment. */ - kind: "static"; -} - -/** Describes multiple sets of queue selectors, of which one will be selected and attached according to a weighting. */ -export interface WeightedAllocationQueueSelectorAttachmentOutput - extends QueueSelectorAttachmentOutputParent { - /** A collection of percentage based weighted allocations. */ - allocations: Array; - /** The type discriminator describing the type of queue selector attachment. */ - kind: "weightedAllocation"; -} - -/** Contains the weight percentage and queue selectors to be applied if selected for weighted distributions. */ -export interface QueueWeightedAllocationOutput { - /** The percentage of this weight, expressed as a fraction of 1. */ - weight: number; - /** A collection of queue selectors that will be applied if this allocation is selected. */ - queueSelectors: Array; -} - -/** An attachment which attaches worker selectors to a job. */ -export interface WorkerSelectorAttachmentOutputParent { - kind: WorkerSelectorAttachmentKindOutput; -} - -/** Describes a set of worker selectors that will be attached if the given condition resolves to true. */ -export interface ConditionalWorkerSelectorAttachmentOutput - extends WorkerSelectorAttachmentOutputParent { - /** The condition that must be true for the worker selectors to be attached. */ - condition: RouterRuleOutput; - /** The worker selectors to attach. */ - workerSelectors: Array; - /** The type discriminator describing the type of worker selector attachment. */ - kind: "conditional"; -} - -/** Describes a condition that must be met against a set of labels for worker selection. */ -export interface RouterWorkerSelectorOutput { - /** The label key to query against. */ - key: string; - /** - * Describes how the value of the label is compared to the value defined on the worker selector. - * - * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" - */ - labelOperator: LabelOperatorOutput; - /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ - value?: any; - /** Describes how long this label selector is valid in seconds. */ - expiresAfterSeconds?: number; - /** Pushes a job to the front of the queue as long as this selector is active. */ - expedite?: boolean; - /** - * Status of the worker selector. - * - * Possible values: "active", "expired" - */ - readonly status?: RouterWorkerSelectorStatusOutput; - /** The time at which this worker selector expires in UTC. */ - readonly expiresAt?: string; -} - -/** Attaches a worker selector where the value is passed through from a job's label with the same key. */ -export interface PassThroughWorkerSelectorAttachmentOutput - extends WorkerSelectorAttachmentOutputParent { - /** The label key to query against. */ - key: string; - /** - * Describes how the value of the label is compared to the value pass through. - * - * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" - */ - labelOperator: LabelOperatorOutput; - /** Describes how long the attached label selector is valid in seconds. */ - expiresAfterSeconds?: number; - /** The type discriminator describing the type of worker selector attachment. */ - kind: "passThrough"; -} - -/** Attaches worker selectors to a job when a RouterRule is resolved. */ -export interface RuleEngineWorkerSelectorAttachmentOutput - extends WorkerSelectorAttachmentOutputParent { - /** A RouterRule that resolves a collection of worker selectors to attach. */ - rule: RouterRuleOutput; - /** The type discriminator describing the type of worker selector attachment. */ - kind: "ruleEngine"; -} - -/** Describes a worker selector that will be attached to a job. */ -export interface StaticWorkerSelectorAttachmentOutput - extends WorkerSelectorAttachmentOutputParent { - /** The worker selector to attach. */ - workerSelector: RouterWorkerSelectorOutput; - /** The type discriminator describing the type of worker selector attachment. */ - kind: "static"; -} - -/** Describes multiple sets of worker selectors, of which one will be selected and attached according to a weighting. */ -export interface WeightedAllocationWorkerSelectorAttachmentOutput - extends WorkerSelectorAttachmentOutputParent { - /** A collection of percentage based weighted allocations. */ - allocations: Array; - /** The type discriminator describing the type of worker selector attachment. */ - kind: "weightedAllocation"; -} - -/** Contains the weight percentage and worker selectors to be applied if selected for weighted distributions. */ -export interface WorkerWeightedAllocationOutput { - /** The percentage of this weight, expressed as a fraction of 1. */ - weight: number; - /** A collection of worker selectors that will be applied if this allocation is selected. */ - workerSelectors: Array; -} - -/** Paged collection of ClassificationPolicy items */ -export interface PagedClassificationPolicyOutput { - /** The ClassificationPolicy items on this page */ - value: Array; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Policy governing how jobs are distributed to workers */ -export interface DistributionPolicyOutput { - /** The entity tag for this resource. */ - readonly etag: string; - /** Id of a distribution policy. */ - readonly id: string; - /** Friendly name of this policy. */ - name?: string; - /** Number of seconds after which any offers created under this policy will be expired. */ - offerExpiresAfterSeconds?: number; - /** Mode governing the specific distribution method. */ - mode?: DistributionModeOutput; -} - -/** Abstract base class for defining a distribution mode. */ -export interface DistributionModeOutputParent { - /** Governs the minimum desired number of active concurrent offers a job can have. */ - minConcurrentOffers?: number; - /** Governs the maximum number of active concurrent offers a job can have. */ - maxConcurrentOffers?: number; - /** If set to true, then router will match workers to jobs even if they don't match label selectors. Warning: You may get workers that are not qualified for a job they are matched with if you set this variable to true. This flag is intended more for temporary usage. By default, set to false. */ - bypassSelectors?: boolean; - kind: DistributionModeKindOutput; -} - -/** Jobs are distributed to the worker with the strongest abilities available. */ -export interface BestWorkerModeOutput extends DistributionModeOutputParent { - /** Define a scoring rule to use, when calculating a score to determine the best worker. If not set, will use a default scoring formula that uses the number of job labels that the worker labels match, as well as the number of label selectors the worker labels match and/or exceed using a logistic function (https://en.wikipedia.org/wiki/Logistic_function). */ - scoringRule?: RouterRuleOutput; - /** Options to configure 'scoringRule'. If not set, default values are used. */ - scoringRuleOptions?: ScoringRuleOptionsOutput; - /** The type discriminator describing a sub-type of Mode */ - kind: "bestWorker"; -} - -/** Encapsulates all options that can be passed as parameters for scoring rule with BestWorkerMode. */ -export interface ScoringRuleOptionsOutput { - /** Set batch size when 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. */ - batchSize?: number; - /** List of extra parameters from a job that will be sent as part of the payload to scoring rule. If not set, a job's labels (sent in the payload as `job`) and a job's worker selectors (sent in the payload as `selectors`) are added to the payload of the scoring rule by default. Note: Worker labels are always sent with scoring payload. */ - scoringParameters?: ScoringRuleParameterSelectorOutput[]; - /** If set to true, will score workers in batches, and the parameter name of the worker labels will be sent as `workers`. By default, set to false and the parameter name for the worker labels will be sent as `worker`. Note: If enabled, use 'batchSize' to set batch size. */ - isBatchScoringEnabled?: boolean; - /** If false, will sort scores by ascending order. By default, set to true. */ - descendingOrder?: boolean; -} - -/** Jobs are directed to the worker who has been idle longest. */ -export interface LongestIdleModeOutput extends DistributionModeOutputParent { - /** The type discriminator describing a sub-type of Mode. */ - kind: "longestIdle"; -} - -/** Jobs are distributed in order to workers, starting with the worker that is after the last worker to receive a job. */ -export interface RoundRobinModeOutput extends DistributionModeOutputParent { - /** The type discriminator describing a sub-type of Mode. */ - kind: "roundRobin"; -} - -/** Paged collection of DistributionPolicy items */ -export interface PagedDistributionPolicyOutput { - /** The DistributionPolicy items on this page */ - value: Array; - /** The link to the next page of items */ - nextLink?: string; -} - -/** A policy that defines actions to execute when exception are triggered. */ -export interface ExceptionPolicyOutput { - /** The entity tag for this resource. */ - readonly etag: string; - /** Id of an exception policy. */ - readonly id: string; - /** Friendly name of this policy. */ - name?: string; - /** A collection of exception rules on the exception policy. */ - exceptionRules?: Array; -} - -/** A rule that defines actions to execute upon a specific trigger. */ -export interface ExceptionRuleOutput { - /** Id of an exception rule. */ - id: string; - /** The trigger for this exception rule. */ - trigger: ExceptionTriggerOutput; - /** A collection of actions to perform once the exception is triggered. */ - actions: Array; -} - -/** Abstract base class for defining a trigger for exception rules. */ -export interface ExceptionTriggerOutputParent { - kind: ExceptionTriggerKindOutput; -} - -/** Trigger for an exception action on exceeding queue length. */ -export interface QueueLengthExceptionTriggerOutput - extends ExceptionTriggerOutputParent { - /** Threshold of number of jobs ahead in the queue to for this trigger to fire. */ - threshold: number; - /** The type discriminator describing a sub-type of ExceptionTrigger. */ - kind: "queueLength"; -} - -/** Trigger for an exception action on exceeding wait time. */ -export interface WaitTimeExceptionTriggerOutput - extends ExceptionTriggerOutputParent { - /** Threshold for wait time for this trigger. */ - thresholdSeconds: number; - /** The type discriminator describing a sub-type of ExceptionTrigger. */ - kind: "waitTime"; -} - -/** The action to take when the exception is triggered. */ -export interface ExceptionActionOutputParent { - /** Unique Id of the exception action. */ - id?: string; - kind: ExceptionActionKindOutput; -} - -/** An action that marks a job as cancelled. */ -export interface CancelExceptionActionOutput - extends ExceptionActionOutputParent { - /** A note that will be appended to a job's notes collection with the current timestamp. */ - note?: string; - /** Indicates the outcome of a job, populate this field with your own custom values. */ - dispositionCode?: string; - /** The type discriminator describing a sub-type of ExceptionAction. */ - kind: "cancel"; -} - -/** An action that manually reclassifies a job by providing the queue, priority and worker selectors. */ -export interface ManualReclassifyExceptionActionOutput - extends ExceptionActionOutputParent { - /** Updated QueueId. */ - queueId?: string; - /** Updated Priority. */ - priority?: number; - /** Updated WorkerSelectors. */ - workerSelectors?: Array; - /** The type discriminator describing a sub-type of ExceptionAction. */ - kind: "manualReclassify"; -} - -/** An action that modifies labels on a job and then reclassifies it. */ -export interface ReclassifyExceptionActionOutput - extends ExceptionActionOutputParent { - /** The new classification policy that will determine queue, priority and worker selectors. */ - classificationPolicyId?: string; - /** Dictionary containing the labels to update (or add if not existing) in key-value pairs. Values must be primitive values - number, string, boolean. */ - labelsToUpsert?: Record; - /** The type discriminator describing a sub-type of ExceptionAction. */ - kind: "reclassify"; -} - -/** Paged collection of ExceptionPolicy items */ -export interface PagedExceptionPolicyOutput { - /** The ExceptionPolicy items on this page */ - value: Array; - /** The link to the next page of items */ - nextLink?: string; -} - -/** A queue that can contain jobs to be routed. */ -export interface RouterQueueOutput { - /** The entity tag for this resource. */ - readonly etag: string; - /** Id of a queue. */ - readonly id: string; - /** Friendly name of this queue. */ - name?: string; - /** Id of a distribution policy that will determine how a job is distributed to workers. */ - distributionPolicyId?: string; - /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ - labels?: Record; - /** Id of an exception policy that determines various job escalation rules. */ - exceptionPolicyId?: string; -} - -/** Paged collection of RouterQueue items */ -export interface PagedRouterQueueOutput { - /** The RouterQueue items on this page */ - value: Array; - /** The link to the next page of items */ - nextLink?: string; -} - -/** A unit of work to be routed */ -export interface RouterJobOutput { - /** The entity tag for this resource. */ - readonly etag: string; - /** Id of a job. */ - readonly id: string; - /** Reference to an external parent context, eg. call ID. */ - channelReference?: string; - /** - * The status of the job. - * - * Possible values: "pendingClassification", "queued", "assigned", "completed", "closed", "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", "scheduleFailed", "waitingForActivation" - */ - readonly status?: RouterJobStatusOutput; - /** Timestamp a job was queued in UTC. */ - readonly enqueuedAt?: string; - /** The channel identifier. eg. voice, chat, etc. */ - channelId?: string; - /** Id of a classification policy used for classifying this job. */ - classificationPolicyId?: string; - /** Id of a queue that this job is queued to. */ - queueId?: string; - /** Priority of this job. Value must be between -100 to 100. */ - priority?: number; - /** Reason code for cancelled or closed jobs. */ - dispositionCode?: string; - /** A collection of manually specified worker selectors, which a worker must satisfy in order to process this job. */ - requestedWorkerSelectors?: Array; - /** A collection of worker selectors attached by a classification policy, which a worker must satisfy in order to process this job. */ - readonly attachedWorkerSelectors?: Array; - /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ - labels?: Record; - /** A collection of the assignments of the job. Key is AssignmentId. */ - readonly assignments?: Record; - /** A set of non-identifying attributes attached to this job. Values must be primitive values - number, string, boolean. */ - tags?: Record; - /** Notes attached to a job, sorted by timestamp. */ - notes?: Array; - /** If set, job will be scheduled to be enqueued at a given time. */ - readonly scheduledAt?: string; - /** If provided, will determine how job matching will be carried out. Default mode: QueueAndMatchMode. */ - matchingMode?: JobMatchingModeOutput; -} - -/** Assignment details of a job to a worker. */ -export interface RouterJobAssignmentOutput { - /** Id of a job assignment. */ - readonly assignmentId: string; - /** Id of the Worker assigned to the job. */ - workerId?: string; - /** Timestamp when the job was assigned to a worker in UTC. */ - assignedAt: string; - /** Timestamp when the job was marked as completed after being assigned in UTC. */ - completedAt?: string; - /** Timestamp when the job was marked as closed after being completed in UTC. */ - closedAt?: string; -} - -/** A note attached to a job. */ -export interface RouterJobNoteOutput { - /** The message contained in the note. */ - message: string; - /** The time at which the note was added in UTC. If not provided, will default to the current time. */ - addedAt?: string; -} - -/** - * A matching mode of one of the following types: - * QueueAndMatchMode: Used when matching worker to a job is required to be done right after job is queued. - * ScheduleAndSuspendMode: Used for scheduling jobs to be queued at a future time. At specified time, matching of a worker to the job will not start automatically. - * SuspendMode: Used when matching workers to a job needs to be suspended. - */ -export interface JobMatchingModeOutputParent { - kind: JobMatchingModeKindOutput; -} - -/** Describes a matching mode used for scheduling jobs to be queued at a future time. At the specified time, matching worker to a job will not start automatically. */ -export interface ScheduleAndSuspendModeOutput - extends JobMatchingModeOutputParent { - /** Requested schedule time. */ - scheduleAt: string; - /** The type discriminator describing ScheduleAndSuspendMode */ - kind: "scheduleAndSuspend"; -} - -/** Describes a matching mode where matching worker to a job is automatically started after job is queued successfully. */ -export interface QueueAndMatchModeOutput extends JobMatchingModeOutputParent { - /** The type discriminator describing QueueAndMatchMode */ - kind: "queueAndMatch"; -} - -/** Describes a matching mode where matching worker to a job is suspended. */ -export interface SuspendModeOutput extends JobMatchingModeOutputParent { - /** The type discriminator describing SuspendMode */ - kind: "suspend"; -} - -/** Response payload from reclassifying a job. */ -export interface ReclassifyJobResultOutput { } - -/** Response payload from cancelling a job. */ -export interface CancelJobResultOutput { } - -/** Response payload from completing a job. */ -export interface CompleteJobResultOutput { } - -/** Response payload from closing a job. */ -export interface CloseJobResultOutput { } - -/** Paged collection of RouterJob items */ -export interface PagedRouterJobOutput { - /** The RouterJob items on this page */ - value: Array; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Position and estimated wait time for a job. */ -export interface RouterJobPositionDetailsOutput { - /** Id of the job these details are about. */ - jobId: string; - /** Position of the job in question within that queue. */ - position: number; - /** Id of the queue this job is enqueued in. */ - queueId: string; - /** Length of the queue: total number of enqueued jobs. */ - queueLength: number; - /** Estimated wait time of the job rounded up to the nearest minute. */ - estimatedWaitTimeMinutes: number; -} - -/** Response payload after a job has been successfully unassigned. */ -export interface UnassignJobResultOutput { - /** Id of an unassigned job. */ - jobId: string; - /** The number of times a job is unassigned. At a maximum 3. */ - unassignmentCount: number; -} - -/** Response containing ids for the worker, job, and assignment from an accepted offer. */ -export interface AcceptJobOfferResultOutput { - /** Id of job assignment that assigns a worker that has accepted an offer to a job. */ - assignmentId: string; - /** Id of the job assigned. */ - jobId: string; - /** Id of the worker that has been assigned this job. */ - workerId: string; -} - -/** Response payload from declining a job. */ -export interface DeclineJobOfferResultOutput { } - -/** Statistics for the queue. */ -export interface RouterQueueStatisticsOutput { - /** Id of the queue these details are about. */ - queueId: string; - /** Length of the queue: total number of enqueued jobs. */ - length: number; - /** The estimated wait time of this queue rounded up to the nearest minute, grouped by job priority. */ - estimatedWaitTimeMinutes?: Record; - /** The wait time of the job that has been enqueued in this queue for the longest. */ - longestJobWaitTimeMinutes?: number; -} - -/** An entity for jobs to be routed to. */ -export interface RouterWorkerOutput { - /** The entity tag for this resource. */ - readonly etag: string; - /** Id of a worker. */ - readonly id: string; - /** - * Current state of a worker. - * - * Possible values: "active", "draining", "inactive" - */ - readonly state?: RouterWorkerStateOutput; - /** Collection of queue(s) that this worker can receive work from. */ - queues?: string[]; - /** The total capacity score this worker has to manage multiple concurrent jobs. */ - capacity?: number; - /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ - labels?: Record; - /** A set of non-identifying attributes attached to this worker. Values must be primitive values - number, string, boolean. */ - tags?: Record; - /** Collection of channel(s) this worker can handle and their impact on the workers capacity. */ - channels?: Array; - /** A list of active offers issued to this worker. */ - readonly offers?: Array; - /** A list of assigned jobs attached to this worker. */ - readonly assignedJobs?: Array; - /** A value indicating the workers capacity. A value of '1' means all capacity is consumed. A value of '0' means no capacity is currently consumed. */ - readonly loadRatio?: number; - /** A flag indicating this worker is open to receive offers or not. */ - availableForOffers?: boolean; - /** If this is set, the worker will only receive up to this many new offers at a time. */ - maxConcurrentOffers?: number; -} - -/** Represents the capacity a job in this channel will consume from a worker. */ -export interface RouterChannelOutput { - /** Id of a channel. */ - channelId: string; - /** The amount of capacity that an instance of a job of this channel will consume of the total worker capacity. */ - capacityCostPerJob: number; - /** The maximum number of jobs that can be supported concurrently for this channel. Value must be greater than zero. */ - maxNumberOfJobs?: number; -} - -/** An offer of a job to a worker. */ -export interface RouterJobOfferOutput { - /** Id of an offer. */ - readonly offerId: string; - /** Id of the job. */ - jobId: string; - /** The capacity cost consumed by the job offer. */ - capacityCost: number; - /** Timestamp when the offer was created in UTC. */ - offeredAt?: string; - /** Timestamp when the offer will expire in UTC. */ - expiresAt?: string; -} - -/** The assignment for a worker to a job. */ -export interface RouterWorkerAssignmentOutput { - /** Id of the assignment. */ - assignmentId: string; - /** Id of the job assigned. */ - jobId: string; - /** The amount of capacity this assignment has consumed on the worker. */ - capacityCost: number; - /** The assignment time of the job in UTC. */ - assignedAt: string; -} - -/** Paged collection of RouterWorker items */ -export interface PagedRouterWorkerOutput { - /** The RouterWorker items on this page */ - value: Array; - /** The link to the next page of items */ - nextLink?: string; -} - -/** An attachment of queue selectors to resolve a queue to a job from a classification policy. */ -export type QueueSelectorAttachmentOutput = - | QueueSelectorAttachmentOutputParent - | ConditionalQueueSelectorAttachmentOutput - | PassThroughQueueSelectorAttachmentOutput - | RuleEngineQueueSelectorAttachmentOutput - | StaticQueueSelectorAttachmentOutput - | WeightedAllocationQueueSelectorAttachmentOutput; -/** - * A rule of one of the following types: - * StaticRule: A rule providing static rules that always return the same result, regardless of input. - * DirectMapRule: A rule that return the same labels as the input labels. - * ExpressionRule: A rule providing inline expression rules. - * FunctionRule: A rule providing a binding to an HTTP Triggered Azure Function. - * WebhookRule: A rule providing a binding to a webserver following OAuth2.0 authentication protocol. - */ -export type RouterRuleOutput = - | RouterRuleOutputParent - | DirectMapRouterRuleOutput - | ExpressionRouterRuleOutput - | FunctionRouterRuleOutput - | StaticRouterRuleOutput - | WebhookRouterRuleOutput; -/** An attachment which attaches worker selectors to a job. */ -export type WorkerSelectorAttachmentOutput = - | WorkerSelectorAttachmentOutputParent - | ConditionalWorkerSelectorAttachmentOutput - | PassThroughWorkerSelectorAttachmentOutput - | RuleEngineWorkerSelectorAttachmentOutput - | StaticWorkerSelectorAttachmentOutput - | WeightedAllocationWorkerSelectorAttachmentOutput; -/** Abstract base class for defining a distribution mode. */ -export type DistributionModeOutput = - | DistributionModeOutputParent - | BestWorkerModeOutput - | LongestIdleModeOutput - | RoundRobinModeOutput; -/** Abstract base class for defining a trigger for exception rules. */ -export type ExceptionTriggerOutput = - | ExceptionTriggerOutputParent - | QueueLengthExceptionTriggerOutput - | WaitTimeExceptionTriggerOutput; -/** The action to take when the exception is triggered. */ -export type ExceptionActionOutput = - | ExceptionActionOutputParent - | CancelExceptionActionOutput - | ManualReclassifyExceptionActionOutput - | ReclassifyExceptionActionOutput; -/** - * A matching mode of one of the following types: - * QueueAndMatchMode: Used when matching worker to a job is required to be done right after job is queued. - * ScheduleAndSuspendMode: Used for scheduling jobs to be queued at a future time. At specified time, matching of a worker to the job will not start automatically. - * SuspendMode: Used when matching workers to a job needs to be suspended. - */ -export type JobMatchingModeOutput = - | JobMatchingModeOutputParent - | ScheduleAndSuspendModeOutput - | QueueAndMatchModeOutput - | SuspendModeOutput; -/** Alias for QueueSelectorAttachmentKindOutput */ -export type QueueSelectorAttachmentKindOutput = string; -/** Alias for RouterRuleKindOutput */ -export type RouterRuleKindOutput = string; -/** Alias for ExpressionRouterRuleLanguageOutput */ -export type ExpressionRouterRuleLanguageOutput = string; -/** Alias for LabelOperatorOutput */ -export type LabelOperatorOutput = string; -/** Alias for WorkerSelectorAttachmentKindOutput */ -export type WorkerSelectorAttachmentKindOutput = string; -/** Alias for RouterWorkerSelectorStatusOutput */ -export type RouterWorkerSelectorStatusOutput = string; -/** Alias for DistributionModeKindOutput */ -export type DistributionModeKindOutput = string; -/** Alias for ScoringRuleParameterSelectorOutput */ -export type ScoringRuleParameterSelectorOutput = string; -/** Alias for ExceptionTriggerKindOutput */ -export type ExceptionTriggerKindOutput = string; -/** Alias for ExceptionActionKindOutput */ -export type ExceptionActionKindOutput = string; -/** Alias for RouterJobStatusOutput */ -export type RouterJobStatusOutput = string; -/** Alias for JobMatchingModeKindOutput */ -export type JobMatchingModeKindOutput = string; -/** Alias for RouterWorkerStateOutput */ -export type RouterWorkerStateOutput = string; diff --git a/sdk/communication/communication-job-router-rest/generated/paginateHelper.ts b/sdk/communication/communication-job-router-rest/generated/paginateHelper.ts deleted file mode 100644 index 9358a3f884b0..000000000000 --- a/sdk/communication/communication-job-router-rest/generated/paginateHelper.ts +++ /dev/null @@ -1,298 +0,0 @@ -// 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-job-router-rest/generated/parameters.ts b/sdk/communication/communication-job-router-rest/generated/parameters.ts deleted file mode 100644 index 8f66b8ee3ddc..000000000000 --- a/sdk/communication/communication-job-router-rest/generated/parameters.ts +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - - -import { RawHttpHeadersInput } from "@azure/core-rest-pipeline"; -import { RequestParameters } from "@azure-rest/core-client"; -import { - ClassificationPolicy, - DistributionPolicy, - ExceptionPolicy, - RouterQueue, - RouterJob, - ReclassifyJobOptions, - CancelJobOptions, - CompleteJobOptions, - CloseJobOptions, - RouterJobStatusSelector, - UnassignJobOptions, - DeclineJobOfferOptions, - RouterWorker, - RouterWorkerStateSelector, -} from "./models.js"; - -export interface UpsertClassificationPolicyHeaders { - /** The request should only proceed if an entity matches this string. */ - "If-Match"?: string; - /** The request should only proceed if the entity was not modified after this time. */ - "If-Unmodified-Since"?: string; -} - -/** The resource instance. */ -export type ClassificationPolicyResourceMergeAndPatch = - Partial; - -export interface UpsertClassificationPolicyBodyParam { - /** The resource instance. */ - body: ClassificationPolicyResourceMergeAndPatch; -} - -export interface UpsertClassificationPolicyHeaderParam { - headers?: RawHttpHeadersInput & UpsertClassificationPolicyHeaders; -} - -export interface UpsertClassificationPolicyMediaTypesParam { - /** This request has a JSON Merge Patch body. */ - contentType: "application/merge-patch+json"; -} - -export type UpsertClassificationPolicyParameters = - UpsertClassificationPolicyHeaderParam & - UpsertClassificationPolicyMediaTypesParam & - UpsertClassificationPolicyBodyParam & - RequestParameters; -export type GetClassificationPolicyParameters = RequestParameters; -export type DeleteClassificationPolicyParameters = RequestParameters; - -export interface ListClassificationPoliciesQueryParamProperties { - /** Number of objects to return per page. */ - maxpagesize?: number; -} - -export interface ListClassificationPoliciesQueryParam { - queryParameters?: ListClassificationPoliciesQueryParamProperties; -} - -export type ListClassificationPoliciesParameters = - ListClassificationPoliciesQueryParam & RequestParameters; - -export interface UpsertDistributionPolicyHeaders { - /** The request should only proceed if an entity matches this string. */ - "If-Match"?: string; - /** The request should only proceed if the entity was not modified after this time. */ - "If-Unmodified-Since"?: string; -} - -/** The resource instance. */ -export type DistributionPolicyResourceMergeAndPatch = - Partial; - -export interface UpsertDistributionPolicyBodyParam { - /** The resource instance. */ - body: DistributionPolicyResourceMergeAndPatch; -} - -export interface UpsertDistributionPolicyHeaderParam { - headers?: RawHttpHeadersInput & UpsertDistributionPolicyHeaders; -} - -export interface UpsertDistributionPolicyMediaTypesParam { - /** This request has a JSON Merge Patch body. */ - contentType: "application/merge-patch+json"; -} - -export type UpsertDistributionPolicyParameters = - UpsertDistributionPolicyHeaderParam & - UpsertDistributionPolicyMediaTypesParam & - UpsertDistributionPolicyBodyParam & - RequestParameters; -export type GetDistributionPolicyParameters = RequestParameters; -export type DeleteDistributionPolicyParameters = RequestParameters; - -export interface ListDistributionPoliciesQueryParamProperties { - /** Number of objects to return per page. */ - maxpagesize?: number; -} - -export interface ListDistributionPoliciesQueryParam { - queryParameters?: ListDistributionPoliciesQueryParamProperties; -} - -export type ListDistributionPoliciesParameters = - ListDistributionPoliciesQueryParam & RequestParameters; - -export interface UpsertExceptionPolicyHeaders { - /** The request should only proceed if an entity matches this string. */ - "If-Match"?: string; - /** The request should only proceed if the entity was not modified after this time. */ - "If-Unmodified-Since"?: string; -} - -/** The resource instance. */ -export type ExceptionPolicyResourceMergeAndPatch = Partial; - -export interface UpsertExceptionPolicyBodyParam { - /** The resource instance. */ - body: ExceptionPolicyResourceMergeAndPatch; -} - -export interface UpsertExceptionPolicyHeaderParam { - headers?: RawHttpHeadersInput & UpsertExceptionPolicyHeaders; -} - -export interface UpsertExceptionPolicyMediaTypesParam { - /** This request has a JSON Merge Patch body. */ - contentType: "application/merge-patch+json"; -} - -export type UpsertExceptionPolicyParameters = UpsertExceptionPolicyHeaderParam & - UpsertExceptionPolicyMediaTypesParam & - UpsertExceptionPolicyBodyParam & - RequestParameters; -export type GetExceptionPolicyParameters = RequestParameters; -export type DeleteExceptionPolicyParameters = RequestParameters; - -export interface ListExceptionPoliciesQueryParamProperties { - /** Number of objects to return per page. */ - maxpagesize?: number; -} - -export interface ListExceptionPoliciesQueryParam { - queryParameters?: ListExceptionPoliciesQueryParamProperties; -} - -export type ListExceptionPoliciesParameters = ListExceptionPoliciesQueryParam & - RequestParameters; - -export interface UpsertQueueHeaders { - /** The request should only proceed if an entity matches this string. */ - "If-Match"?: string; - /** The request should only proceed if the entity was not modified after this time. */ - "If-Unmodified-Since"?: string; -} - -/** The resource instance. */ -export type RouterQueueResourceMergeAndPatch = Partial; - -export interface UpsertQueueBodyParam { - /** The resource instance. */ - body: RouterQueueResourceMergeAndPatch; -} - -export interface UpsertQueueHeaderParam { - headers?: RawHttpHeadersInput & UpsertQueueHeaders; -} - -export interface UpsertQueueMediaTypesParam { - /** This request has a JSON Merge Patch body. */ - contentType: "application/merge-patch+json"; -} - -export type UpsertQueueParameters = UpsertQueueHeaderParam & - UpsertQueueMediaTypesParam & - UpsertQueueBodyParam & - RequestParameters; -export type GetQueueParameters = RequestParameters; -export type DeleteQueueParameters = RequestParameters; - -export interface ListQueuesQueryParamProperties { - /** Number of objects to return per page. */ - maxpagesize?: number; -} - -export interface ListQueuesQueryParam { - queryParameters?: ListQueuesQueryParamProperties; -} - -export type ListQueuesParameters = ListQueuesQueryParam & RequestParameters; - -export interface UpsertJobHeaders { - /** The request should only proceed if an entity matches this string. */ - "If-Match"?: string; - /** The request should only proceed if the entity was not modified after this time. */ - "If-Unmodified-Since"?: string; -} - -/** The resource instance. */ -export type RouterJobResourceMergeAndPatch = Partial; - -export interface UpsertJobBodyParam { - /** The resource instance. */ - body: RouterJobResourceMergeAndPatch; -} - -export interface UpsertJobHeaderParam { - headers?: RawHttpHeadersInput & UpsertJobHeaders; -} - -export interface UpsertJobMediaTypesParam { - /** This request has a JSON Merge Patch body. */ - contentType: "application/merge-patch+json"; -} - -export type UpsertJobParameters = UpsertJobHeaderParam & - UpsertJobMediaTypesParam & - UpsertJobBodyParam & - RequestParameters; -export type GetJobParameters = RequestParameters; -export type DeleteJobParameters = RequestParameters; - -export interface ReclassifyBodyParam { - /** Request object for reclassifying a job. */ - body?: ReclassifyJobOptions; -} - -export type ReclassifyParameters = ReclassifyBodyParam & RequestParameters; - -export interface CancelBodyParam { - /** Request model for cancelling job. */ - body?: CancelJobOptions; -} - -export type CancelParameters = CancelBodyParam & RequestParameters; - -export interface CompleteBodyParam { - /** Request model for completing job. */ - body?: CompleteJobOptions; -} - -export type CompleteParameters = CompleteBodyParam & RequestParameters; - -export interface CloseBodyParam { - /** Request model for closing job. */ - body?: CloseJobOptions; -} - -export type CloseParameters = CloseBodyParam & RequestParameters; - -export interface ListJobsQueryParamProperties { - /** Number of objects to return per page. */ - maxpagesize?: number; - /** - * If specified, filter jobs by status. - * - * Possible values: "all", "pendingClassification", "queued", "assigned", "completed", "closed", "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", "scheduleFailed", "waitingForActivation", "active" - */ - status?: RouterJobStatusSelector; - /** If specified, filter jobs by queue. */ - queueId?: string; - /** If specified, filter jobs by channel. */ - channelId?: string; - /** If specified, filter jobs by classificationPolicy. */ - classificationPolicyId?: string; - /** If specified, filter on jobs that was scheduled before or at given timestamp. Range: (-Inf, scheduledBefore]. */ - scheduledBefore?: Date | string; - /** If specified, filter on jobs that was scheduled at or after given value. Range: [scheduledAfter, +Inf). */ - scheduledAfter?: Date | string; -} - -export interface ListJobsQueryParam { - queryParameters?: ListJobsQueryParamProperties; -} - -export type ListJobsParameters = ListJobsQueryParam & RequestParameters; -export type GetInQueuePositionParameters = RequestParameters; - -export interface UnassignBodyParam { - /** Request body for unassign route. */ - body?: UnassignJobOptions; -} - -export type UnassignParameters = UnassignBodyParam & RequestParameters; -export type AcceptParameters = RequestParameters; - -export interface DeclineBodyParam { - /** Request model for declining offer. */ - body?: DeclineJobOfferOptions; -} - -export type DeclineParameters = DeclineBodyParam & RequestParameters; -export type GetQueueStatisticsParameters = RequestParameters; - -export interface UpsertWorkerHeaders { - /** The request should only proceed if an entity matches this string. */ - "If-Match"?: string; - /** The request should only proceed if the entity was not modified after this time. */ - "If-Unmodified-Since"?: string; -} - -/** The resource instance. */ -export type RouterWorkerResourceMergeAndPatch = Partial; - -export interface UpsertWorkerBodyParam { - /** The resource instance. */ - body: RouterWorkerResourceMergeAndPatch; -} - -export interface UpsertWorkerHeaderParam { - headers?: RawHttpHeadersInput & UpsertWorkerHeaders; -} - -export interface UpsertWorkerMediaTypesParam { - /** This request has a JSON Merge Patch body. */ - contentType: "application/merge-patch+json"; -} - -export type UpsertWorkerParameters = UpsertWorkerHeaderParam & - UpsertWorkerMediaTypesParam & - UpsertWorkerBodyParam & - RequestParameters; -export type GetWorkerParameters = RequestParameters; -export type DeleteWorkerParameters = RequestParameters; - -export interface ListWorkersQueryParamProperties { - /** Number of objects to return per page. */ - maxpagesize?: number; - /** - * If specified, select workers by worker state. - * - * Possible values: "active", "draining", "inactive", "all" - */ - state?: RouterWorkerStateSelector; - /** If specified, select workers who have a channel configuration with this channel. */ - channelId?: string; - /** If specified, select workers who are assigned to this queue. */ - queueId?: string; - /** If set to true, select only workers who have capacity for the channel specified by `channelId` or for any channel if `channelId` not specified. If set to false, then will return all workers including workers without any capacity for jobs. Defaults to false. */ - hasCapacity?: boolean; -} - -export interface ListWorkersQueryParam { - queryParameters?: ListWorkersQueryParamProperties; -} - -export type ListWorkersParameters = ListWorkersQueryParam & RequestParameters; diff --git a/sdk/communication/communication-job-router-rest/generated/responses.ts b/sdk/communication/communication-job-router-rest/generated/responses.ts deleted file mode 100644 index 41b88d424c24..000000000000 --- a/sdk/communication/communication-job-router-rest/generated/responses.ts +++ /dev/null @@ -1,767 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - - -import { RawHttpHeaders } from "@azure/core-rest-pipeline"; -import { HttpResponse, ErrorResponse } from "@azure-rest/core-client"; -import { - ClassificationPolicyOutput, - PagedClassificationPolicyOutput, - DistributionPolicyOutput, - PagedDistributionPolicyOutput, - ExceptionPolicyOutput, - PagedExceptionPolicyOutput, - RouterQueueOutput, - PagedRouterQueueOutput, - RouterJobOutput, - ReclassifyJobResultOutput, - CancelJobResultOutput, - CompleteJobResultOutput, - CloseJobResultOutput, - PagedRouterJobOutput, - RouterJobPositionDetailsOutput, - UnassignJobResultOutput, - AcceptJobOfferResultOutput, - DeclineJobOfferResultOutput, - RouterQueueStatisticsOutput, - RouterWorkerOutput, - PagedRouterWorkerOutput, -} from "./outputModels.js"; - -export interface UpsertClassificationPolicy200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface UpsertClassificationPolicy200Response extends HttpResponse { - status: "200"; - body: ClassificationPolicyOutput; - headers: RawHttpHeaders & UpsertClassificationPolicy200Headers; -} - -export interface UpsertClassificationPolicy201Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded and a new resource has been created as a result. */ -export interface UpsertClassificationPolicy201Response extends HttpResponse { - status: "201"; - body: ClassificationPolicyOutput; - headers: RawHttpHeaders & UpsertClassificationPolicy201Headers; -} - -export interface UpsertClassificationPolicyDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface UpsertClassificationPolicyDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & UpsertClassificationPolicyDefaultHeaders; -} - -export interface GetClassificationPolicy200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface GetClassificationPolicy200Response extends HttpResponse { - status: "200"; - body: ClassificationPolicyOutput; - headers: RawHttpHeaders & GetClassificationPolicy200Headers; -} - -export interface GetClassificationPolicyDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface GetClassificationPolicyDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & GetClassificationPolicyDefaultHeaders; -} - -/** There is no content to send for this request, but the headers may be useful. */ -export interface DeleteClassificationPolicy204Response extends HttpResponse { - status: "204"; -} - -export interface DeleteClassificationPolicyDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface DeleteClassificationPolicyDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & DeleteClassificationPolicyDefaultHeaders; -} - -/** The request has succeeded. */ -export interface ListClassificationPolicies200Response extends HttpResponse { - status: "200"; - body: PagedClassificationPolicyOutput; -} - -export interface ListClassificationPoliciesDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface ListClassificationPoliciesDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & ListClassificationPoliciesDefaultHeaders; -} - -export interface UpsertDistributionPolicy200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface UpsertDistributionPolicy200Response extends HttpResponse { - status: "200"; - body: DistributionPolicyOutput; - headers: RawHttpHeaders & UpsertDistributionPolicy200Headers; -} - -export interface UpsertDistributionPolicy201Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded and a new resource has been created as a result. */ -export interface UpsertDistributionPolicy201Response extends HttpResponse { - status: "201"; - body: DistributionPolicyOutput; - headers: RawHttpHeaders & UpsertDistributionPolicy201Headers; -} - -export interface UpsertDistributionPolicyDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface UpsertDistributionPolicyDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & UpsertDistributionPolicyDefaultHeaders; -} - -export interface GetDistributionPolicy200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface GetDistributionPolicy200Response extends HttpResponse { - status: "200"; - body: DistributionPolicyOutput; - headers: RawHttpHeaders & GetDistributionPolicy200Headers; -} - -export interface GetDistributionPolicyDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface GetDistributionPolicyDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & GetDistributionPolicyDefaultHeaders; -} - -/** There is no content to send for this request, but the headers may be useful. */ -export interface DeleteDistributionPolicy204Response extends HttpResponse { - status: "204"; -} - -export interface DeleteDistributionPolicyDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface DeleteDistributionPolicyDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & DeleteDistributionPolicyDefaultHeaders; -} - -/** The request has succeeded. */ -export interface ListDistributionPolicies200Response extends HttpResponse { - status: "200"; - body: PagedDistributionPolicyOutput; -} - -export interface ListDistributionPoliciesDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface ListDistributionPoliciesDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & ListDistributionPoliciesDefaultHeaders; -} - -export interface UpsertExceptionPolicy200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface UpsertExceptionPolicy200Response extends HttpResponse { - status: "200"; - body: ExceptionPolicyOutput; - headers: RawHttpHeaders & UpsertExceptionPolicy200Headers; -} - -export interface UpsertExceptionPolicy201Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded and a new resource has been created as a result. */ -export interface UpsertExceptionPolicy201Response extends HttpResponse { - status: "201"; - body: ExceptionPolicyOutput; - headers: RawHttpHeaders & UpsertExceptionPolicy201Headers; -} - -export interface UpsertExceptionPolicyDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface UpsertExceptionPolicyDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & UpsertExceptionPolicyDefaultHeaders; -} - -export interface GetExceptionPolicy200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface GetExceptionPolicy200Response extends HttpResponse { - status: "200"; - body: ExceptionPolicyOutput; - headers: RawHttpHeaders & GetExceptionPolicy200Headers; -} - -export interface GetExceptionPolicyDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface GetExceptionPolicyDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & GetExceptionPolicyDefaultHeaders; -} - -/** There is no content to send for this request, but the headers may be useful. */ -export interface DeleteExceptionPolicy204Response extends HttpResponse { - status: "204"; -} - -export interface DeleteExceptionPolicyDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface DeleteExceptionPolicyDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & DeleteExceptionPolicyDefaultHeaders; -} - -/** The request has succeeded. */ -export interface ListExceptionPolicies200Response extends HttpResponse { - status: "200"; - body: PagedExceptionPolicyOutput; -} - -export interface ListExceptionPoliciesDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface ListExceptionPoliciesDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & ListExceptionPoliciesDefaultHeaders; -} - -export interface UpsertQueue200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface UpsertQueue200Response extends HttpResponse { - status: "200"; - body: RouterQueueOutput; - headers: RawHttpHeaders & UpsertQueue200Headers; -} - -export interface UpsertQueue201Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded and a new resource has been created as a result. */ -export interface UpsertQueue201Response extends HttpResponse { - status: "201"; - body: RouterQueueOutput; - headers: RawHttpHeaders & UpsertQueue201Headers; -} - -export interface UpsertQueueDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface UpsertQueueDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & UpsertQueueDefaultHeaders; -} - -export interface GetQueue200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface GetQueue200Response extends HttpResponse { - status: "200"; - body: RouterQueueOutput; - headers: RawHttpHeaders & GetQueue200Headers; -} - -export interface GetQueueDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface GetQueueDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & GetQueueDefaultHeaders; -} - -/** There is no content to send for this request, but the headers may be useful. */ -export interface DeleteQueue204Response extends HttpResponse { - status: "204"; -} - -export interface DeleteQueueDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface DeleteQueueDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & DeleteQueueDefaultHeaders; -} - -/** The request has succeeded. */ -export interface ListQueues200Response extends HttpResponse { - status: "200"; - body: PagedRouterQueueOutput; -} - -export interface ListQueuesDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface ListQueuesDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & ListQueuesDefaultHeaders; -} - -export interface UpsertJob200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface UpsertJob200Response extends HttpResponse { - status: "200"; - body: RouterJobOutput; - headers: RawHttpHeaders & UpsertJob200Headers; -} - -export interface UpsertJob201Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded and a new resource has been created as a result. */ -export interface UpsertJob201Response extends HttpResponse { - status: "201"; - body: RouterJobOutput; - headers: RawHttpHeaders & UpsertJob201Headers; -} - -export interface UpsertJobDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface UpsertJobDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & UpsertJobDefaultHeaders; -} - -export interface GetJob200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface GetJob200Response extends HttpResponse { - status: "200"; - body: RouterJobOutput; - headers: RawHttpHeaders & GetJob200Headers; -} - -export interface GetJobDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface GetJobDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & GetJobDefaultHeaders; -} - -/** There is no content to send for this request, but the headers may be useful. */ -export interface DeleteJob204Response extends HttpResponse { - status: "204"; -} - -export interface DeleteJobDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface DeleteJobDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & DeleteJobDefaultHeaders; -} - -/** The request has succeeded. */ -export interface Reclassify200Response extends HttpResponse { - status: "200"; - body: ReclassifyJobResultOutput; -} - -export interface ReclassifyDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface ReclassifyDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & ReclassifyDefaultHeaders; -} - -/** The request has succeeded. */ -export interface Cancel200Response extends HttpResponse { - status: "200"; - body: CancelJobResultOutput; -} - -export interface CancelDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface CancelDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & CancelDefaultHeaders; -} - -/** The request has succeeded. */ -export interface Complete200Response extends HttpResponse { - status: "200"; - body: CompleteJobResultOutput; -} - -export interface CompleteDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface CompleteDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & CompleteDefaultHeaders; -} - -/** The request has succeeded. */ -export interface Close200Response extends HttpResponse { - status: "200"; - body: CloseJobResultOutput; -} - -export interface CloseDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface CloseDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & CloseDefaultHeaders; -} - -/** The request has succeeded. */ -export interface ListJobs200Response extends HttpResponse { - status: "200"; - body: PagedRouterJobOutput; -} - -export interface ListJobsDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface ListJobsDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & ListJobsDefaultHeaders; -} - -/** The request has succeeded. */ -export interface GetInQueuePosition200Response extends HttpResponse { - status: "200"; - body: RouterJobPositionDetailsOutput; -} - -export interface GetInQueuePositionDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface GetInQueuePositionDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & GetInQueuePositionDefaultHeaders; -} - -/** The request has succeeded. */ -export interface Unassign200Response extends HttpResponse { - status: "200"; - body: UnassignJobResultOutput; -} - -export interface UnassignDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface UnassignDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & UnassignDefaultHeaders; -} - -/** The request has succeeded. */ -export interface Accept200Response extends HttpResponse { - status: "200"; - body: AcceptJobOfferResultOutput; -} - -export interface AcceptDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface AcceptDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & AcceptDefaultHeaders; -} - -/** The request has succeeded. */ -export interface Decline200Response extends HttpResponse { - status: "200"; - body: DeclineJobOfferResultOutput; -} - -export interface DeclineDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface DeclineDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & DeclineDefaultHeaders; -} - -/** The request has succeeded. */ -export interface GetQueueStatistics200Response extends HttpResponse { - status: "200"; - body: RouterQueueStatisticsOutput; -} - -export interface GetQueueStatisticsDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface GetQueueStatisticsDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & GetQueueStatisticsDefaultHeaders; -} - -export interface UpsertWorker200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface UpsertWorker200Response extends HttpResponse { - status: "200"; - body: RouterWorkerOutput; - headers: RawHttpHeaders & UpsertWorker200Headers; -} - -export interface UpsertWorker201Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded and a new resource has been created as a result. */ -export interface UpsertWorker201Response extends HttpResponse { - status: "201"; - body: RouterWorkerOutput; - headers: RawHttpHeaders & UpsertWorker201Headers; -} - -export interface UpsertWorkerDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface UpsertWorkerDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & UpsertWorkerDefaultHeaders; -} - -export interface GetWorker200Headers { - /** The entity tag for the response. */ - etag?: string; - /** The last modified timestamp. */ - "last-modified"?: string; -} - -/** The request has succeeded. */ -export interface GetWorker200Response extends HttpResponse { - status: "200"; - body: RouterWorkerOutput; - headers: RawHttpHeaders & GetWorker200Headers; -} - -export interface GetWorkerDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface GetWorkerDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & GetWorkerDefaultHeaders; -} - -/** There is no content to send for this request, but the headers may be useful. */ -export interface DeleteWorker204Response extends HttpResponse { - status: "204"; -} - -export interface DeleteWorkerDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface DeleteWorkerDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & DeleteWorkerDefaultHeaders; -} - -/** The request has succeeded. */ -export interface ListWorkers200Response extends HttpResponse { - status: "200"; - body: PagedRouterWorkerOutput; -} - -export interface ListWorkersDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface ListWorkersDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & ListWorkersDefaultHeaders; -} diff --git a/sdk/communication/communication-job-router-rest/package.json b/sdk/communication/communication-job-router-rest/package.json index e903801500ed..f66b33cfd6b3 100644 --- a/sdk/communication/communication-job-router-rest/package.json +++ b/sdk/communication/communication-job-router-rest/package.json @@ -1,9 +1,29 @@ { "name": "@azure-rest/communication-job-router", - "sdk-type": "client", - "author": "Microsoft Corporation", - "version": "1.1.0-beta.3", + "version": "1.0.0-beta.1", "description": "Azure client library for Azure Communication Job Router 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, + "project": "./tsconfig.src.json" + }, + "type": "module", "keywords": [ "node", "azure", @@ -12,104 +32,79 @@ "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/", "README.md", - "LICENSE", - "review/", - "CHANGELOG.md" + "LICENSE" ], - "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:samples": "dev-tool samples publish --force", - "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": "dev-tool samples run samples-dev", - "extract-api": "dev-tool run vendored rimraf 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", - "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 test:node && npm run test:browser", - "test:browser": "npm run clean && dev-tool run build-package && dev-tool run build-test && dev-tool run test:vitest --browser", - "test:node": "dev-tool run test:vitest", - "test:node:esm": "dev-tool run test:vitest --esm", - "update-snippets": "dev-tool run update-snippets" + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-job-router-rest/README.md", + "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", + "//metadata": { + "constantPaths": [ + { + "path": "src/azureCommunicationRoutingServiceClient.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.9.0", - "@azure/core-rest-pipeline": "^1.18.0", - "@azure/logger": "^1.1.4", + "@azure/core-rest-pipeline": "^1.20.0", + "@azure/logger": "^1.2.0", "tslib": "^2.8.1" }, "devDependencies": { "@azure-tools/test-credential": "^2.0.0", "@azure-tools/test-recorder": "^4.1.0", "@azure-tools/test-utils-vitest": "^1.0.0", - "@azure/core-util": "^1.11.0", "@azure/dev-tool": "^1.0.0", "@azure/eslint-plugin-azure-sdk": "^3.0.0", - "@azure/identity": "^4.5.0", + "@azure/identity": "^4.9.1", "@types/node": "^18.0.0", "@vitest/browser": "^3.0.9", "@vitest/coverage-istanbul": "^3.0.9", - "autorest": "latest", "dotenv": "^16.0.0", "eslint": "^9.9.0", - "playwright": "^1.48.2", + "playwright": "^1.52.0", "typescript": "~5.8.2", "vitest": "^3.0.9" }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-job-router-rest/README.md", - "//metadata": { - "constantPaths": [ - { - "path": "src/azureCommunicationRoutingServiceClient.ts", - "prefix": "userAgentInfo" - } - ] + "scripts": { + "build": "npm run clean && dev-tool run build-package && dev-tool run extract-api", + "build:samples": "echo skipped", + "build:test": "npm run clean && dev-tool run build-package && dev-tool run build-test", + "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}\" ", + "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 extract-api", + "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", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "integration-test:browser": "echo skipped", + "integration-test:node": "echo skipped", + "lint": "eslint package.json api-extractor.json src test", + "lint:fix": "eslint package.json api-extractor.json src test --fix --fix-type [problem,suggestion]", + "minify": "dev-tool run vendored uglifyjs -c -m --comments --source-map \"content='./dist/index.js.map'\" -o ./dist/index.min.js ./dist/index.js", + "pack": "npm pack 2>&1", + "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", + "test:browser": "npm run clean && dev-tool run build-package && dev-tool run build-test && dev-tool run test:vitest --browser", + "test:node": "dev-tool run test:vitest", + "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", + "update-snippets": "dev-tool run update-snippets", + "test:node:esm": "dev-tool run test:vitest --esm" }, "browser": "./dist/browser/index.js", - "//sampleConfiguration": { - "productName": "Azure client library for Azure Communication Job Router services", - "productSlugs": [ - "azure", - "azure-communication-services" - ] - }, - "type": "module", - "tshy": { - "exports": { - "./package.json": "./package.json", - ".": "./src/index.ts" - }, - "dialects": [ - "esm", - "commonjs" - ], - "esmDialects": [ - "browser", - "react-native" - ], - "selfLink": false, - "project": "./tsconfig.src.json" - }, + "react-native": "./dist/react-native/index.js", "exports": { "./package.json": "./package.json", ".": { @@ -130,5 +125,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-job-router-rest/review/communication-job-router.api.md b/sdk/communication/communication-job-router-rest/review/communication-job-router.api.md index e7f08b01ff65..4d724e61b0fe 100644 --- a/sdk/communication/communication-job-router-rest/review/communication-job-router.api.md +++ b/sdk/communication/communication-job-router-rest/review/communication-job-router.api.md @@ -8,7 +8,6 @@ import type { Client } from '@azure-rest/core-client'; import type { ClientOptions } from '@azure-rest/core-client'; import type { ErrorResponse } from '@azure-rest/core-client'; import type { HttpResponse } from '@azure-rest/core-client'; -import type { KeyCredential } from '@azure/core-auth'; import type { PathUncheckedResponse } from '@azure-rest/core-client'; import type { RawHttpHeaders } from '@azure/core-rest-pipeline'; import type { RawHttpHeadersInput } from '@azure/core-rest-pipeline'; @@ -282,10 +281,7 @@ export interface ConditionalWorkerSelectorAttachmentOutput extends WorkerSelecto } // @public -function createClient(connectionString: string, options: ClientOptions): AzureCommunicationRoutingServiceClient; - -// @public -function createClient(endpoint: string, credentialOrOptions?: KeyCredential | TokenCredential, options?: ClientOptions): AzureCommunicationRoutingServiceClient; +function createClient(endpointParam: string, credentials: TokenCredential, { apiVersion, ...options }?: AzureCommunicationRoutingServiceClientOptions): AzureCommunicationRoutingServiceClient; export default createClient; // @public (undocumented) diff --git a/sdk/communication/communication-job-router-rest/sample.env b/sdk/communication/communication-job-router-rest/sample.env deleted file mode 100644 index 64e43f31bba2..000000000000 --- a/sdk/communication/communication-job-router-rest/sample.env +++ /dev/null @@ -1,3 +0,0 @@ -# Used in most samples. Retrieve these values from a Communication Services instance -# in the Azure Portal. -COMMUNICATION_CONNECTION_STRING="endpoint=https://.communication.azure.net/;accessKey=" diff --git a/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Create.ts b/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Create.ts deleted file mode 100644 index 33e0162a3261..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Create.ts +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import "dotenv/config"; -/** - * @summary Classification policy crud - */ -import type { - QueueLengthExceptionTrigger, - AzureCommunicationRoutingServiceClient, -} from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a classification policy -async function createClassificationPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longestIdle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger: QueueLengthExceptionTrigger = { - kind: "queueLength", - threshold: 100, - }; - - const exceptionPolicyId = "exception-policy-123"; - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [ - { - id: "MaxWaitTimeExceeded", - actions: [ - { - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }, - ], - trigger: queueLengthExceptionTrigger, - }, - ], - }, - }); - - const classificationPolicyId = "classification-policy-123"; - const salesQueueId = "queue-123"; - await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "Default Classification Policy", - fallbackQueueId: salesQueueId, - queueSelectorAttachments: [ - { - kind: "static", - queueSelector: { key: "department", labelOperator: "equal", value: "xbox" }, - }, - ], - workerSelectorAttachments: [ - { - kind: "static", - workerSelector: { key: "english", labelOperator: "greaterThan", value: 5 }, - }, - ], - prioritizationRule: { - kind: "expression", - language: "powerFx", - expression: 'If(job.department = "xbox", 2, 1)', - }, - }, - }); - - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: "distribution-policy-123", - name: "Main", - labels: {}, - exceptionPolicyId: "exception-policy-123", - }, - }); - - const result = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - fallbackQueueId: "queue-123", - queueSelectorAttachments: [ - { - kind: "conditional", - queueSelectors: [ - { - key: "foo", - labelOperator: "equal", - value: { default: 10 }, - }, - ], - condition: { - kind: "direct-map-rule", - }, - }, - ], - prioritizationRule: { - kind: "static", - value: { default: 2 }, - }, - }, - }); - - console.log("classification policy: " + result); -} - -createClassificationPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Delete.ts b/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Delete.ts deleted file mode 100644 index 912f6b4cf321..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Delete.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Classification policy crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete classification policy -async function deleteClassificationPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const policyId = "classification-policy-123"; - - const result = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", policyId) - .delete(); - - console.log("classification policy: " + result); -} - -deleteClassificationPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Get.ts b/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Get.ts deleted file mode 100644 index 36f0b9168768..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Get.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Classification policy crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a classification policy - -async function getClassificationPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const policyId = "classification-policy-123"; - - const result = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", policyId) - .get(); - - console.log("classification policy: " + result); -} - -getClassificationPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_List.ts b/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_List.ts deleted file mode 100644 index c0dbebcfd709..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_List.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Classification policy crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter, { isUnexpected, paginate } from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List classification policies -async function listClassificationPolicies(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - // let pagesCount = 1; - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/classificationPolicies") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (!isUnexpected(initialResponse)) { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listClassificationPolicies().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Update.ts b/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Update.ts deleted file mode 100644 index 1b61843ca6dc..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/ClassificationPolicy_Update.ts +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Classification policy crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a classification policy -async function updateClassificationPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const classificationPolicyId = "classification-policy-123"; - const salesQueueId = "queue-123"; - const result = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "Default Classification Policy", - fallbackQueueId: salesQueueId, - queueSelectorAttachments: [ - { - kind: "static", - queueSelector: { key: "department", labelOperator: "equal", value: "xbox" }, - }, - ], - workerSelectorAttachments: [ - { - kind: "static", - workerSelector: { key: "english", labelOperator: "greaterThan", value: 5 }, - }, - ], - prioritizationRule: { - kind: "expression", - language: "powerFx", - expression: 'If(job.department = "xbox", 2, 1)', - }, - }, - }); - - console.log("classification policy: " + result); -} - -updateClassificationPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Create.ts b/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Create.ts deleted file mode 100644 index eda7374cf2b2..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Create.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create an distribution policy -async function createDistributionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const id = "distribution-policy-123"; - const result = await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", id) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longestIdle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - console.log("distribution policy: " + result); -} - -createDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Delete.ts b/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Delete.ts deleted file mode 100644 index 36bcbf4e8567..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Delete.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete distribution policy -async function deleteDistributionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const policyId = "distribution-policy-123"; - - const result = await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", policyId) - .delete(); - - console.log("distribution policy: " + result); -} - -deleteDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Get.ts b/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Get.ts deleted file mode 100644 index a0cadfe63c95..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Get.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a distribution policy - -async function getDistributionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const policyId = "distribution-policy-123"; - - const result = await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", policyId) - .get(); - - console.log("distribution policy: " + result); -} - -getDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_List.ts b/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_List.ts deleted file mode 100644 index 5eaa784e3bc5..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_List.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter, { isUnexpected, paginate } from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List distribution policies -async function listDistributionPolicies(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/distributionPolicies") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (!isUnexpected(initialResponse)) { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listDistributionPolicies().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Update.ts b/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Update.ts deleted file mode 100644 index 5644eb40d377..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/DistributionPolicy_Update.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a distribution policy -async function updateDistributionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const id = "distribution-policy-123"; - const result = await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", id) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longestIdle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - console.log("distribution policy: " + result); -} - -updateDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Create.ts b/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Create.ts deleted file mode 100644 index 376c75403164..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Create.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ -import type { - AzureCommunicationRoutingServiceClient, - QueueLengthExceptionTrigger, -} from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create an exception policy -async function createExceptionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger: QueueLengthExceptionTrigger = { - kind: "queueLength", - threshold: 10, - }; - - const id = "exception-policy-123"; - - const result = await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", id) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [ - { - id: "MaxWaitTimeExceeded", - actions: [ - { - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }, - ], - trigger: queueLengthExceptionTrigger, - }, - ], - }, - }); - - console.log("exception policy: " + result); -} - -createExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Delete.ts b/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Delete.ts deleted file mode 100644 index 0f4a6473de65..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Delete.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete exception policy -async function deleteExceptionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const policyId = "exception-policy-123"; - - const result = await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", policyId) - .delete(); - - console.log("exception policy: " + result); -} - -deleteExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Get.ts b/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Get.ts deleted file mode 100644 index 87066f5883c5..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Get.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a exception policy - -async function getExceptionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const policyId = "exception-policy-123"; - - const result = await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", policyId) - .get(); - - console.log("exception policy: " + result); -} - -getExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_List.ts b/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_List.ts deleted file mode 100644 index 0e571073bd7b..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_List.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ - -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter, { isUnexpected, paginate } from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listExceptionPolicies(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/exceptionPolicies") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (!isUnexpected(initialResponse)) { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listExceptionPolicies().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Update.ts b/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Update.ts deleted file mode 100644 index f692fbfa5b62..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/ExceptionPolicy_Update.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ - -import type { - QueueLengthExceptionTrigger, - AzureCommunicationRoutingServiceClient, -} from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a exception policy -async function updateExceptionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger: QueueLengthExceptionTrigger = { - kind: "queueLength", - threshold: 10, - }; - - const id = "exception-policy-123"; - - const result = await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", id) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [ - { - id: "MaxWaitTimeExceeded", - actions: [ - { - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }, - ], - trigger: queueLengthExceptionTrigger, - }, - ], - }, - }); - console.log("exception policy: " + result); -} - -updateExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/QuickStart.ts b/sdk/communication/communication-job-router-rest/samples-dev/QuickStart.ts deleted file mode 100644 index dc8aadc2279e..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/QuickStart.ts +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Quick start workflow for creating queue, job and worker, routing/matching job with worker - */ -import type { - RouterWorkerOutput, - AzureCommunicationRoutingServiceClient, - AcceptJobOfferResultOutput, - RouterJobOutput, -} from "@azure-rest/communication-job-router"; -import JobRouter, { isUnexpected } from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -async function quickStart(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - // Create a Distribution Policy - const distributionPolicyId = "distribution-policy-123"; - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution policy 123", - mode: { - kind: "longestIdle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - // Create a Queue - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: distributionPolicyId, - name: "Main", - }, - }); - - // Create a Job - const jobId = "router-job-123"; - await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelId: "ChatChannel", - queueId: queueId, - channelReference: "abc", - priority: 2, - labels: {}, - }, - }); - - // Register a Worker - // Register a worker associated with the queue that was just created. We will assign labels to the - // worker to include all relevant information for example, skills, which will be used to determine - // whether a job can be offered to a worker or not. - const workerId = "router-worker-123"; - await routerClient.path("/routing/workers/{workerId}", workerId).patch({ - contentType: "application/merge-patch+json", - body: { - capacity: 100, - queues: [queueId], - labels: {}, - channels: [ - { - channelId: "ChatChannel", - capacityCostPerJob: 10, - }, - { - channelId: "CustomVoiceChannel", - capacityCostPerJob: 100, - }, - ], - availableForOffers: true, - }, - }); - - await delay(5000); - // Check offers to a Worker - // Once the worker has been registered, Router will send an offer to the worker if the worker satisfies requirements - // for a job. See Offer flow https://learn.microsoft.com/azure/communication-services/concepts/router/concepts#offer - // - // We should get a RouterWorkerOfferIssued from our EventGrid subscription. - - // However, we could also wait a few seconds and then query the worker directly against the Job Router API to see if - // an offer was issued to it. - const workerResponse = await routerClient.path("/routing/workers/{workerId}", workerId).get(); - if (isUnexpected(workerResponse)) { - throw workerResponse; - } - const workerResult = workerResponse.body as RouterWorkerOutput; - - for await (const offer of workerResult.offers!) { - console.log(`Worker ${workerId} has an active offer for job ${offer.jobId}`); - } - - // Accepting an offer - // Once a worker receives an offer, it can take two possible actions: accept or decline. We are going to accept the offer. - // fetching the offer id - const jobOffer = workerResult.offers![0]; - - const offerId = jobOffer.offerId; // `OfferId` can be retrieved directly from consuming event from Event grid - - // accepting the offer sent to `worker-1` - const acceptJobOfferResponse = await routerClient - .path("/routing/workers/{workerId}/offers/{offerId}:accept", workerId, offerId) - .post(); - if (isUnexpected(acceptJobOfferResponse)) { - throw acceptJobOfferResponse; - } - const acceptJobOfferResult = acceptJobOfferResponse.body as AcceptJobOfferResultOutput; - - console.log(`Offer: ${jobOffer.offerId} sent to worker: ${workerId} has been accepted`); - console.log( - `Job has been assigned to worker: ${workerId} with assignment: ${acceptJobOfferResult.assignmentId}`, - ); - - // verify job assignment is populated when querying job - let updatedJobResponse = await routerClient.path("/routing/jobs/{jobId}", jobId).get(); - if (isUnexpected(updatedJobResponse)) { - throw updatedJobResponse; - } - let updatedJob = updatedJobResponse.body as RouterJobOutput; - - console.log(`Job assignment has been successful: - ${ - updatedJob.status === "assigned" && - Object.prototype.hasOwnProperty.call(updatedJob.assignments!, acceptJobOfferResult.assignmentId) - }`); - - // Completing a job - // Once the worker is done with the job, the worker has to mark the job as `completed`. - const completeJob = await routerClient - .path( - "/routing/jobs/{jobId}/assignments/{assignmentId}:complete", - jobId, - acceptJobOfferResult.assignmentId, - ) - .post({ - body: { - note: `Job has been completed by ${workerId} at ${new Date()}`, - }, - }); - - console.log(`Job has been successfully completed: ${completeJob}`); - - // Closing a job - // After a job has been completed, the worker can perform wrap up actions to the job before closing the job and finally - // releasing its capacity to accept more incoming jobs - const closeJob = await routerClient - .path( - "/routing/jobs/{jobId}/assignments/{assignmentId}:close", - jobId, - acceptJobOfferResult.assignmentId, - ) - .post({ - body: { - note: `Job has been closed by ${workerId} at ${new Date()}`, - }, - }); - console.log(`Job has been successfully closed: ${closeJob}`); - - // Optionally, a job can also be set up to be marked as closed in the future. - const afterTwoSeconds = new Date(); - await afterTwoSeconds.setSeconds(afterTwoSeconds.getSeconds() + 2); - const closeJobInFuture = await routerClient - .path( - "/routing/jobs/{jobId}/assignments/{assignmentId}:close", - jobId, - acceptJobOfferResult.assignmentId, - ) - .post({ - body: { - closeAt: afterTwoSeconds, - note: `Job has been marked to close in the future by ${workerId} at ${afterTwoSeconds}`, - }, - }); - console.log(`Job has been marked to close: ${closeJobInFuture}`); // You'll received a 202 in that case - - await delay(2000); - - updatedJobResponse = await routerClient.path("/routing/jobs/{jobId}", jobId).get(); - if (isUnexpected(updatedJobResponse)) { - throw updatedJobResponse; - } - updatedJob = updatedJobResponse.body as RouterJobOutput; - - console.log(`Updated job status: ${updatedJob.status === "closed"}`); -} - -function delay(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -quickStart().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Create.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Create.ts deleted file mode 100644 index 84c9c15642d4..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Create.ts +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -import type { - AzureCommunicationRoutingServiceClient, - QueueLengthExceptionTrigger, -} from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a router job -async function createRouterJob(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution policy 123", - mode: { - kind: "longestIdle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger: QueueLengthExceptionTrigger = { - kind: "queueLength", - threshold: 100, - }; - - const exceptionPolicyId = "exception-policy-123"; - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [ - { - id: "MaxWaitTimeExceeded", - actions: [ - { - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }, - ], - trigger: queueLengthExceptionTrigger, - }, - ], - }, - }); - - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: "distribution-policy-123", - name: "Main", - labels: {}, - exceptionPolicyId: "exception-policy-123", - }, - }); - - const jobId = "router-job-123"; - const result = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelId: "ChatChannel", - queueId: queueId, - channelReference: "abc", - priority: 2, - labels: {}, - }, - }); - - console.log("router job: " + result); -} - -createRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Delete.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Delete.ts deleted file mode 100644 index 06b8fc1d8813..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Delete.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete router job -async function deleteRouterJob(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const entityId = "router-job-123"; - - const result = await routerClient.path("/routing/jobs/{jobId}", entityId).delete(); - - console.log("router job: " + result); -} - -deleteRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Get.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Get.ts deleted file mode 100644 index 377efbc0eb30..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Get.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router job - -async function getRouterJob(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const entityId = "router-job-123"; - - const result = await routerClient.path("/routing/jobs/{jobId}", entityId).get(); - - console.log("router job: " + result); -} - -getRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_List.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_List.ts deleted file mode 100644 index 5f921fa59fdd..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_List.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter, { isUnexpected, paginate } from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listRouterJobs(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/jobs") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (!isUnexpected(initialResponse)) { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listRouterJobs().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Update.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Update.ts deleted file mode 100644 index 18d827b0f138..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterJob_Update.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a router job -async function updateRouterJob(): Promise { - // Create the JobRouter Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: "distribution-policy-123", - name: "Main", - labels: {}, - exceptionPolicyId: "exception-policy-123", - }, - }); - - const jobId = "router-job-123"; - const result = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelId: "ChatChannel", - queueId: queueId, - channelReference: "abc", - priority: 2, - labels: {}, - }, - }); - - console.log("router job: " + result); -} - -updateRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Create.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Create.ts deleted file mode 100644 index 7e04ecdb7d70..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Create.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a router jobQueue -async function createJobQueue(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution policy 123", - mode: { - kind: "longestIdle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - const queueId = "queue-123"; - const result = await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: distributionPolicyId, - name: "Main", - }, - }); - - console.log("router jobQueue: " + result); -} - -createJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Delete.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Delete.ts deleted file mode 100644 index ac5ff21988c9..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Delete.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete router jobQueue -async function deleteJobQueue(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const entityId = "queue-123"; - - const result = await routerClient.path("/routing/queues/{queueId}", entityId).delete(); - - console.log("router jobQueue: " + result); -} - -deleteJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Get.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Get.ts deleted file mode 100644 index 61f953ab160e..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Get.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router jobQueue - -async function getJobQueue(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const entityId = "router-jobQueue-123"; - - const result = await routerClient.path("/routing/queues/{queueId}", entityId).get(); - - console.log("router jobQueue: " + result); -} - -getJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_GetStatistics.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_GetStatistics.ts deleted file mode 100644 index 9e5855f10b1a..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_GetStatistics.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ - -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router jobQueue's statistics - -async function getJobQueueStatistics(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const entityId = "router-jobQueue-123"; - - const result = await routerClient.path("/routing/queues/{queueId}/statistics", entityId).get(); - - console.log("router jobQueue: " + result); -} - -getJobQueueStatistics().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_List.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_List.ts deleted file mode 100644 index 62f85a6f401e..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_List.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter, { isUnexpected, paginate } from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listJobQueues(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/queues") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (!isUnexpected(initialResponse)) { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listJobQueues().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Update.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Update.ts deleted file mode 100644 index 79f9c51a8e99..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterQueue_Update.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a router jobQueue -async function updateJobQueue(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution policy 123", - mode: { - kind: "longestIdle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - const queueId = "queue-123"; - const result = await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: distributionPolicyId, - name: "Main", - }, - }); - - console.log("router jobQueue: " + result); -} - -updateJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Create.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Create.ts deleted file mode 100644 index 39317d59b045..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Create.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a router worker -async function createRouterWorker(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const id = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - capacity: 100, - queues: ["MainQueue", "SecondaryQueue"], - labels: {}, - channels: [ - { - channelId: "CustomChatChannel", - capacityCostPerJob: 10, - }, - { - channelId: "CustomVoiceChannel", - capacityCostPerJob: 100, - }, - ], - }, - }); - - console.log("router worker: " + result); -} - -createRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Delete.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Delete.ts deleted file mode 100644 index 102ad65d3f44..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Delete.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete router worker -async function deleteRouterWorker(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const entityId = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", entityId).delete(); - - console.log("router worker: " + result); -} - -deleteRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Get.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Get.ts deleted file mode 100644 index de26d12ad97a..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Get.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router worker -async function getRouterWorker(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const entityId = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", entityId).get(); - - console.log("router worker: " + result); -} - -getRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_List.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_List.ts deleted file mode 100644 index 05cbdd6e8156..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_List.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter, { isUnexpected, paginate } from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listRouterWorkers(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/queues") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (!isUnexpected(initialResponse)) { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listRouterWorkers().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Update.ts b/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Update.ts deleted file mode 100644 index 08793efef84d..000000000000 --- a/sdk/communication/communication-job-router-rest/samples-dev/RouterWorker_Update.ts +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -import type { AzureCommunicationRoutingServiceClient } from "@azure-rest/communication-job-router"; -import JobRouter from "@azure-rest/communication-job-router"; -import "dotenv/config"; - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a router worker -async function updateRouterWorker(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = JobRouter(connectionString); - - const id = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - capacity: 100, - queues: ["MainQueue", "SecondaryQueue"], - labels: {}, - channels: [ - { - channelId: "CustomChatChannel", - capacityCostPerJob: 10, - }, - { - channelId: "CustomVoiceChannel", - capacityCostPerJob: 100, - }, - ], - }, - }); - console.log("router worker: " + result); -} - -updateRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Create.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Create.js deleted file mode 100644 index 5abd575782b6..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Create.js +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -const dotenv = require("dotenv"); -/** - * @summary Classification policy crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; - -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a classification policy -async function createClassificationPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger = { - kind: "queue-length", - threshold: 100, - }; - - const exceptionPolicyId = "exception-policy-123"; - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [ - { - id: "MaxWaitTimeExceeded", - actions: [ - { - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }, - ], - trigger: queueLengthExceptionTrigger, - }, - ], - }, - }); - - const classificationPolicyId = "classification-policy-123"; - const salesQueueId = "queue-123"; - await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "Default Classification Policy", - fallbackQueueId: salesQueueId, - queueSelectorAttachments: [ - { - kind: "static", - queueSelector: { key: "department", labelOperator: "equal", value: "xbox" }, - }, - ], - workerSelectorAttachments: [ - { - kind: "static", - workerSelector: { key: "english", labelOperator: "greaterThan", value: 5 }, - }, - ], - prioritizationRule: { - kind: "expression-rule", - language: "powerFx", - expression: 'If(job.department = "xbox", 2, 1)', - }, - }, - }); - - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: "distribution-policy-123", - name: "Main", - labels: {}, - exceptionPolicyId: "exception-policy-123", - }, - }); - - const result = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - fallbackQueueId: "queue-123", - queueSelectorAttachments: [ - { - kind: "conditional", - queueSelectors: [ - { - key: "foo", - labelOperator: "equal", - value: { default: 10 }, - }, - ], - condition: { - kind: "direct-map-rule", - }, - }, - ], - prioritizationRule: { - kind: "static-rule", - value: { default: 2 }, - }, - }, - }); - - console.log("classification policy: " + result); -} - -void createClassificationPolicy(); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Delete.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Delete.js deleted file mode 100644 index 71f33b626920..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Delete.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Classification policy crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete classification policy -async function deleteClassificationPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const policyId = "classification-policy-123"; - - const result = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", policyId) - .delete(); - - console.log("classification policy: " + result); -} - -deleteClassificationPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Get.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Get.js deleted file mode 100644 index 2c953bfa8ca7..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Get.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Classification policy crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a classification policy - -async function getClassificationPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const policyId = "classification-policy-123"; - - const result = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", policyId) - .get(); - - console.log("classification policy: " + result); -} - -void getClassificationPolicy(); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_List.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_List.js deleted file mode 100644 index 85061a8aa1b7..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_List.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Classification policy crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default, - { paginate } = require("@azure-rest/communication-job-router"); -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List classification policies -async function listClassificationPolicies() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - // let pagesCount = 1; - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/classificationPolicies") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listClassificationPolicies().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Update.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Update.js deleted file mode 100644 index d9a024ba8f10..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Update.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Classification policy crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a classification policy -async function updateClassificationPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const classificationPolicyId = "classification-policy-123"; - const salesQueueId = "queue-123"; - const result = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "Default Classification Policy", - fallbackQueueId: salesQueueId, - queueSelectorAttachments: [ - { - kind: "static", - queueSelector: { key: "department", labelOperator: "equal", value: "xbox" }, - }, - ], - workerSelectorAttachments: [ - { - kind: "static", - workerSelector: { key: "english", labelOperator: "greaterThan", value: 5 }, - }, - ], - prioritizationRule: { - kind: "expression-rule", - language: "powerFx", - expression: 'If(job.department = "xbox", 2, 1)', - }, - }, - }); - - console.log("classification policy: " + result); -} - -void updateClassificationPolicy(); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Create.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Create.js deleted file mode 100644 index fa0b465eba29..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Create.js +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create an distribution policy -async function createDistributionPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const id = "distribution-policy-123"; - const result = await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", id) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - console.log("distribution policy: " + result); -} - -createDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Delete.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Delete.js deleted file mode 100644 index 7bf75819aaf8..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Delete.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete distribution policy -async function deleteDistributionPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const policyId = "distribution-policy-123"; - - const result = await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", policyId) - .delete(); - - console.log("distribution policy: " + result); -} - -deleteDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Get.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Get.js deleted file mode 100644 index 2c078a6e5841..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Get.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a distribution policy - -async function getDistributionPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const policyId = "distribution-policy-123"; - - const result = await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", policyId) - .get(); - - console.log("distribution policy: " + result); -} - -getDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_List.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_List.js deleted file mode 100644 index 199c728f1041..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_List.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - -const { paginate } = require("@azure-rest/communication-job-router"); -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List distribution policies -async function listDistributionPolicies() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/distributionPolicies") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listDistributionPolicies().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Update.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Update.js deleted file mode 100644 index a7b4a17a7021..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Update.js +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a distribution policy -async function updateDistributionPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const id = "distribution-policy-123"; - const result = await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", id) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - console.log("distribution policy: " + result); -} - -updateDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Create.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Create.js deleted file mode 100644 index c7e8b9446b2a..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Create.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create an exception policy -async function createExceptionPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger = { - kind: "queue-length", - threshold: 10, - }; - - const id = "exception-policy-123"; - - const result = await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", id) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [ - { - id: "MaxWaitTimeExceeded", - actions: [ - { - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }, - ], - trigger: queueLengthExceptionTrigger, - }, - ], - }, - }); - - console.log("exception policy: " + result); -} - -createExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Delete.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Delete.js deleted file mode 100644 index 19540a656d2f..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Delete.js +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete exception policy -async function deleteExceptionPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const policyId = "exception-policy-123"; - - const result = await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", policyId) - .delete(); - - console.log("exception policy: " + result); -} - -deleteExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Get.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Get.js deleted file mode 100644 index 1e8d7b941b66..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Get.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a exception policy - -async function getExceptionPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const policyId = "exception-policy-123"; - - const result = await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", policyId) - .get(); - - console.log("exception policy: " + result); -} - -getExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_List.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_List.js deleted file mode 100644 index 6cc4e8114fac..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_List.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ - -const { paginate } = require("@azure-rest/communication-job-router"); -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listExceptionPolicies() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/exceptionPolicies") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listExceptionPolicies().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Update.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Update.js deleted file mode 100644 index 393434debc4c..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Update.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ - -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a exception policy -async function updateExceptionPolicy() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger = { - kind: "queue-length", - threshold: 10, - }; - - const id = "exception-policy-123"; - - const result = await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", id) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [ - { - id: "MaxWaitTimeExceeded", - actions: [ - { - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }, - ], - trigger: queueLengthExceptionTrigger, - }, - ], - }, - }); - console.log("exception policy: " + result); -} - -updateExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/QuickStart.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/QuickStart.js deleted file mode 100644 index 5acc71e1e116..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/QuickStart.js +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Quick start workflow for creating queue, job and worker, routing/matching job with worker - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -async function quickStart() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - // Create a Distribution Policy - const distributionPolicyId = "distribution-policy-123"; - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - // Create a Queue - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: distributionPolicyId, - name: "Main", - }, - }); - - // Create a Job - const jobId = "router-job-123"; - await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelId: "ChatChannel", - queueId: queueId, - channelReference: "abc", - priority: 2, - labels: {}, - }, - }); - - // Register a Worker - // Register a worker associated with the queue that was just created. We will assign labels to the - // worker to include all relevant information for example, skills, which will be used to determine - // whether a job can be offered to a worker or not. - const workerId = "router-worker-123"; - await routerClient.path("/routing/workers/{workerId}", workerId).patch({ - contentType: "application/merge-patch+json", - body: { - capacity: 100, - queues: [queueId], - labels: {}, - channels: [ - { - channelId: "ChatChannel", - capacityCostPerJob: 10, - }, - { - channelId: "CustomVoiceChannel", - capacityCostPerJob: 100, - }, - ], - availableForOffers: true, - }, - }); - - await delay(5000); - // Check offers to a Worker - // Once the worker has been registered, Router will send an offer to the worker if the worker satisfies requirements - // for a job. See Offer flow https://learn.microsoft.com/azure/communication-services/concepts/router/concepts#offer - // - // We should get a RouterWorkerOfferIssued from our EventGrid subscription. - - // However, we could also wait a few seconds and then query the worker directly against the Job Router API to see if - // an offer was issued to it. - const workerResponse = await routerClient.path("/routing/workers/{workerId}", workerId).get(); - if (workerResponse.status !== "200") { - throw new Error("get works fails"); - } - const workerResult = workerResponse.body; - - for await (let offer of workerResult.offers) { - console.log(`Worker ${workerId} has an active offer for job ${offer.jobId}`); - } - - // Accepting an offer - // Once a worker receives an offer, it can take two possible actions: accept or decline. We are going to accept the offer. - // fetching the offer id - const jobOffer = workerResult.offers[0]; - - const offerId = jobOffer.offerId; // `OfferId` can be retrieved directly from consuming event from Event grid - - // accepting the offer sent to `worker-1` - const acceptJobOfferResponse = await routerClient - .path("/routing/workers/{workerId}/offers/{offerId}:accept", workerId, offerId) - .post(); - if (acceptJobOfferResponse.status !== "200") { - throw new Error("accept job offer fails"); - } - const acceptJobOfferResult = acceptJobOfferResponse.body; - - console.log(`Offer: ${jobOffer.offerId} sent to worker: ${workerId} has been accepted`); - console.log( - `Job has been assigned to worker: ${workerId} with assignment: ${acceptJobOfferResult.assignmentId}`, - ); - - // verify job assignment is populated when querying job - let updatedJobResponse = await routerClient.path("/routing/jobs/{jobId}", jobId).get(); - if (updatedJobResponse.status !== "200") { - throw new Error("get job fails"); - } - let updatedJob = updatedJobResponse.body; - - console.log(`Job assignment has been successful: - ${ - updatedJob.status == "assigned" && - updatedJob.assignments.hasOwnProperty(acceptJobOfferResult.assignmentId) - }`); - - // Completing a job - // Once the worker is done with the job, the worker has to mark the job as `completed`. - const completeJob = await routerClient - .path( - "/routing/jobs/{jobId}/assignments/{assignmentId}:complete", - jobId, - acceptJobOfferResult.assignmentId, - ) - .post({ - body: { - note: `Job has been completed by ${workerId} at ${new Date()}`, - }, - }); - - console.log(`Job has been successfully completed: ${completeJob}`); - - // Closing a job - // After a job has been completed, the worker can perform wrap up actions to the job before closing the job and finally - // releasing its capacity to accept more incoming jobs - const closeJob = await routerClient - .path( - "/routing/jobs/{jobId}/assignments/{assignmentId}:close", - jobId, - acceptJobOfferResult.assignmentId, - ) - .post({ - body: { - note: `Job has been closed by ${workerId} at ${new Date()}`, - }, - }); - console.log(`Job has been successfully closed: ${closeJob}`); - - // Optionally, a job can also be set up to be marked as closed in the future. - const afterTwoSeconds = new Date(); - afterTwoSeconds.setSeconds(afterTwoSeconds.getSeconds() + 2); - const closeJobInFuture = await routerClient - .path( - "/routing/jobs/{jobId}/assignments/{assignmentId}:close", - jobId, - acceptJobOfferResult.assignmentId, - ) - .post({ - body: { - closeAt: afterTwoSeconds, - note: `Job has been marked to close in the future by ${workerId} at ${afterTwoSeconds}`, - }, - }); - console.log(`Job has been marked to close: ${closeJobInFuture}`); // You'll received a 202 in that case - - await delay(2000); - - updatedJobResponse = await routerClient.path("/routing/jobs/{jobId}", jobId).get(); - if (updatedJobResponse.status !== "200") { - throw new Error("get job fails"); - } - updatedJob = updatedJobResponse.body; - - console.log(`Updated job status: ${updatedJob.status == "closed"}`); -} - -function delay(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -quickStart().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/README.md b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/README.md deleted file mode 100644 index c5b7d8dbc04e..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/README.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -page_type: sample -languages: - - javascript -products: - - azure - - azure-communication-services -urlFragment: communication-job-router-javascript-beta ---- - -# Azure client library for Azure Communication Job Router services client library samples for JavaScript (Beta) - -These sample programs show how to use the JavaScript client libraries for Azure client library for Azure Communication Job Router services in some common scenarios. - -| **File Name** | **Description** | -| ------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | -| [ClassificationPolicy_Create.js][classificationpolicy_create] | Classification policy crud | -| [ClassificationPolicy_Delete.js][classificationpolicy_delete] | Classification policy crud | -| [ClassificationPolicy_Get.js][classificationpolicy_get] | Classification policy crud | -| [ClassificationPolicy_List.js][classificationpolicy_list] | Classification policy crud | -| [ClassificationPolicy_Update.js][classificationpolicy_update] | Classification policy crud | -| [DistributionPolicy_Create.js][distributionpolicy_create] | Distribution policy crud | -| [DistributionPolicy_Delete.js][distributionpolicy_delete] | Distribution policy crud | -| [DistributionPolicy_Get.js][distributionpolicy_get] | Distribution policy crud | -| [DistributionPolicy_List.js][distributionpolicy_list] | Distribution policy crud | -| [DistributionPolicy_Update.js][distributionpolicy_update] | Distribution policy crud | -| [ExceptionPolicy_Create.js][exceptionpolicy_create] | Exception policy crud | -| [ExceptionPolicy_Delete.js][exceptionpolicy_delete] | Exception policy crud | -| [ExceptionPolicy_Get.js][exceptionpolicy_get] | Exception policy crud | -| [ExceptionPolicy_List.js][exceptionpolicy_list] | Exception policy crud | -| [ExceptionPolicy_Update.js][exceptionpolicy_update] | Exception policy crud | -| [QuickStart.js][quickstart] | Quick start workflow for creating queue, job and worker, routing/matching job with worker | -| [RouterJob_Create.js][routerjob_create] | router job crud | -| [RouterJob_Delete.js][routerjob_delete] | router job crud | -| [RouterJob_Get.js][routerjob_get] | router job crud | -| [RouterJob_List.js][routerjob_list] | router job crud | -| [RouterJob_Update.js][routerjob_update] | router job crud | -| [RouterQueue_Create.js][routerqueue_create] | job queue crud | -| [RouterQueue_Delete.js][routerqueue_delete] | job queue crud | -| [RouterQueue_Get.js][routerqueue_get] | job queue crud | -| [RouterQueue_GetStatistics.js][routerqueue_getstatistics] | job queue crud | -| [RouterQueue_List.js][routerqueue_list] | job queue crud | -| [RouterQueue_Update.js][routerqueue_update] | job queue crud | -| [RouterWorker_Create.js][routerworker_create] | router worker crud | -| [RouterWorker_Delete.js][routerworker_delete] | router worker crud | -| [RouterWorker_Get.js][routerworker_get] | router worker crud | -| [RouterWorker_List.js][routerworker_list] | router worker crud | -| [RouterWorker_Update.js][routerworker_update] | router worker crud | - -## 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 ClassificationPolicy_Create.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 COMMUNICATION_CONNECTION_STRING="" node ClassificationPolicy_Create.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[classificationpolicy_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Create.js -[classificationpolicy_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Delete.js -[classificationpolicy_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Get.js -[classificationpolicy_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_List.js -[classificationpolicy_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ClassificationPolicy_Update.js -[distributionpolicy_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Create.js -[distributionpolicy_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Delete.js -[distributionpolicy_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Get.js -[distributionpolicy_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_List.js -[distributionpolicy_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/DistributionPolicy_Update.js -[exceptionpolicy_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Create.js -[exceptionpolicy_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Delete.js -[exceptionpolicy_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Get.js -[exceptionpolicy_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_List.js -[exceptionpolicy_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/ExceptionPolicy_Update.js -[quickstart]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/QuickStart.js -[routerjob_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Create.js -[routerjob_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Delete.js -[routerjob_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Get.js -[routerjob_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_List.js -[routerjob_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Update.js -[routerqueue_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Create.js -[routerqueue_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Delete.js -[routerqueue_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Get.js -[routerqueue_getstatistics]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_GetStatistics.js -[routerqueue_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_List.js -[routerqueue_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Update.js -[routerworker_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Create.js -[routerworker_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Delete.js -[routerworker_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Get.js -[routerworker_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_List.js -[routerworker_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Update.js -[apiref]: https://learn.microsoft.com/javascript/api/@azure/communication-job-router -[freesub]: https://azure.microsoft.com/free/ -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-job-router-rest/README.md diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Create.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Create.js deleted file mode 100644 index 7e09ad55c952..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Create.js +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a router job -async function createRouterJob() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger = { - kind: "queue-length", - threshold: 100, - }; - - const exceptionPolicyId = "exception-policy-123"; - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [ - { - id: "MaxWaitTimeExceeded", - actions: [ - { - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }, - ], - trigger: queueLengthExceptionTrigger, - }, - ], - }, - }); - - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: "distribution-policy-123", - name: "Main", - labels: {}, - exceptionPolicyId: "exception-policy-123", - }, - }); - - const jobId = "router-job-123"; - const result = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelId: "ChatChannel", - queueId: queueId, - channelReference: "abc", - priority: 2, - labels: {}, - }, - }); - - console.log("router job: " + result); -} - -createRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Delete.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Delete.js deleted file mode 100644 index 37b4dc296348..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Delete.js +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete router job -async function deleteRouterJob() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const entityId = "router-job-123"; - - const result = await routerClient.path("/routing/jobs/{jobId}", entityId).delete(); - - console.log("router job: " + result); -} - -deleteRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Get.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Get.js deleted file mode 100644 index 3081917bbc1e..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Get.js +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router job - -async function getRouterJob() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const entityId = "router-job-123"; - - const result = await routerClient.path("/routing/jobs/{jobId}", entityId).get(); - - console.log("router job: " + result); -} - -getRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_List.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_List.js deleted file mode 100644 index 849eaef5171d..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_List.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default, - { paginate } = require("@azure-rest/communication-job-router"); -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listRouterJobs() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/jobs") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listRouterJobs().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Update.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Update.js deleted file mode 100644 index 8384e5d0741a..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterJob_Update.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a router job -async function updateRouterJob() { - // Create the JobRouter Client - const routerClient = JobRouter(connectionString); - - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: "distribution-policy-123", - name: "Main", - labels: {}, - exceptionPolicyId: "exception-policy-123", - }, - }); - - const jobId = "router-job-123"; - const result = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelId: "ChatChannel", - queueId: queueId, - channelReference: "abc", - priority: 2, - labels: {}, - }, - }); - - console.log("router job: " + result); -} - -updateRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Create.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Create.js deleted file mode 100644 index 6ad3c4ab33f6..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Create.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a router jobQueue -async function createJobQueue() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - const queueId = "queue-123"; - const result = await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: distributionPolicyId, - name: "Main", - }, - }); - - console.log("router jobQueue: " + result); -} - -createJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Delete.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Delete.js deleted file mode 100644 index e28a32e3a749..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Delete.js +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete router jobQueue -async function deleteJobQueue() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const entityId = "queue-123"; - - const result = await routerClient.path("/routing/queues/{queueId}", entityId).delete(); - - console.log("router jobQueue: " + result); -} - -deleteJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Get.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Get.js deleted file mode 100644 index 9a30c08111cf..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Get.js +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router jobQueue - -async function getJobQueue() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const entityId = "router-jobQueue-123"; - - const result = await routerClient.path("/routing/queues/{queueId}", entityId).get(); - - console.log("router jobQueue: " + result); -} - -getJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_GetStatistics.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_GetStatistics.js deleted file mode 100644 index 73df2cd1f5b7..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_GetStatistics.js +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ - -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router jobQueue's statistics - -async function getJobQueueStatistics() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const entityId = "router-jobQueue-123"; - - const result = await routerClient.path("/routing/queues/{queueId}/statistics", entityId).get(); - - console.log("router jobQueue: " + result); -} - -getJobQueueStatistics().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_List.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_List.js deleted file mode 100644 index 3a75ea593e41..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_List.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default, - { paginate } = require("@azure-rest/communication-job-router"); -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listJobQueues() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/queues") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listJobQueues().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Update.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Update.js deleted file mode 100644 index 04c9960289aa..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterQueue_Update.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a router jobQueue -async function updateJobQueue() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - - const queueId = "queue-123"; - const result = await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: distributionPolicyId, - name: "Main", - }, - }); - - console.log("router jobQueue: " + result); -} - -updateJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Create.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Create.js deleted file mode 100644 index 9035b810b6da..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Create.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a router worker -async function createRouterWorker() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const id = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - capacity: 100, - queues: ["MainQueue", "SecondaryQueue"], - labels: {}, - channels: [ - { - channelId: "CustomChatChannel", - capacityCostPerJob: 10, - }, - { - channelId: "CustomVoiceChannel", - capacityCostPerJob: 100, - }, - ], - }, - }); - - console.log("router worker: " + result); -} - -createRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Delete.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Delete.js deleted file mode 100644 index 8fd74c24779e..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Delete.js +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete router worker -async function deleteRouterWorker() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const entityId = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", entityId).delete(); - - console.log("router worker: " + result); -} - -deleteRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Get.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Get.js deleted file mode 100644 index 03a69906185c..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Get.js +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router worker -async function getRouterWorker() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const entityId = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", entityId).get(); - - console.log("router worker: " + result); -} - -getRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_List.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_List.js deleted file mode 100644 index 2f00526c8935..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_List.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default, - { paginate } = require("@azure-rest/communication-job-router"); -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listRouterWorkers() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient - .path("/routing/queues") - .get({ queryParameters: { maxpagesize: maxPageSize } }); - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listRouterWorkers().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Update.js b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Update.js deleted file mode 100644 index d08e7a526ed8..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/RouterWorker_Update.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -const JobRouter = require("@azure-rest/communication-job-router").default; -require("dotenv").config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a router worker -async function updateRouterWorker() { - // Create the Router Client - const routerClient = JobRouter(connectionString); - - const id = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - capacity: 100, - queues: ["MainQueue", "SecondaryQueue"], - labels: {}, - channels: [ - { - channelId: "CustomChatChannel", - capacityCostPerJob: 10, - }, - { - channelId: "CustomVoiceChannel", - capacityCostPerJob: 100, - }, - ], - }, - }); - console.log("router worker: " + result); -} - -updateRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/package.json b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/package.json deleted file mode 100644 index 303547aa1a4b..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "@azure-samples/communication-job-router-js-beta", - "private": true, - "version": "1.0.0", - "description": "Azure client library for Azure Communication Job Router services client library samples for JavaScript (Beta)", - "engines": { - "node": ">=18.0.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Azure/azure-sdk-for-js.git", - "directory": "sdk/communication/communication-job-router-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-job-router-rest", - "dependencies": { - "@azure-rest/communication-job-router": "next", - "dotenv": "latest" - } -} diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/sample.env b/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/sample.env deleted file mode 100644 index 64e43f31bba2..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/javascript/sample.env +++ /dev/null @@ -1,3 +0,0 @@ -# Used in most samples. Retrieve these values from a Communication Services instance -# in the Azure Portal. -COMMUNICATION_CONNECTION_STRING="endpoint=https://.communication.azure.net/;accessKey=" diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/README.md b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/README.md deleted file mode 100644 index 74c1cd8315b0..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/README.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -page_type: sample -languages: - - typescript -products: - - azure - - azure-communication-services -urlFragment: communication-job-router-typescript-beta ---- - -# Azure client library for Azure Communication Job Router services client library samples for TypeScript (Beta) - -These sample programs show how to use the TypeScript client libraries for Azure client library for Azure Communication Job Router services in some common scenarios. - -| **File Name** | **Description** | -| ------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | -| [ClassificationPolicy_Create.ts][classificationpolicy_create] | Classification policy crud | -| [ClassificationPolicy_Delete.ts][classificationpolicy_delete] | Classification policy crud | -| [ClassificationPolicy_Get.ts][classificationpolicy_get] | Classification policy crud | -| [ClassificationPolicy_List.ts][classificationpolicy_list] | Classification policy crud | -| [ClassificationPolicy_Update.ts][classificationpolicy_update] | Classification policy crud | -| [DistributionPolicy_Create.ts][distributionpolicy_create] | Distribution policy crud | -| [DistributionPolicy_Delete.ts][distributionpolicy_delete] | Distribution policy crud | -| [DistributionPolicy_Get.ts][distributionpolicy_get] | Distribution policy crud | -| [DistributionPolicy_List.ts][distributionpolicy_list] | Distribution policy crud | -| [DistributionPolicy_Update.ts][distributionpolicy_update] | Distribution policy crud | -| [ExceptionPolicy_Create.ts][exceptionpolicy_create] | Exception policy crud | -| [ExceptionPolicy_Delete.ts][exceptionpolicy_delete] | Exception policy crud | -| [ExceptionPolicy_Get.ts][exceptionpolicy_get] | Exception policy crud | -| [ExceptionPolicy_List.ts][exceptionpolicy_list] | Exception policy crud | -| [ExceptionPolicy_Update.ts][exceptionpolicy_update] | Exception policy crud | -| [QuickStart.ts][quickstart] | Quick start workflow for creating queue, job and worker, routing/matching job with worker | -| [RouterJob_Create.ts][routerjob_create] | router job crud | -| [RouterJob_Delete.ts][routerjob_delete] | router job crud | -| [RouterJob_Get.ts][routerjob_get] | router job crud | -| [RouterJob_List.ts][routerjob_list] | router job crud | -| [RouterJob_Update.ts][routerjob_update] | router job crud | -| [RouterQueue_Create.ts][routerqueue_create] | job queue crud | -| [RouterQueue_Delete.ts][routerqueue_delete] | job queue crud | -| [RouterQueue_Get.ts][routerqueue_get] | job queue crud | -| [RouterQueue_GetStatistics.ts][routerqueue_getstatistics] | job queue crud | -| [RouterQueue_List.ts][routerqueue_list] | job queue crud | -| [RouterQueue_Update.ts][routerqueue_update] | job queue crud | -| [RouterWorker_Create.ts][routerworker_create] | router worker crud | -| [RouterWorker_Delete.ts][routerworker_delete] | router worker crud | -| [RouterWorker_Get.ts][routerworker_get] | router worker crud | -| [RouterWorker_List.ts][routerworker_list] | router worker crud | -| [RouterWorker_Update.ts][routerworker_update] | router worker crud | - -## 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/ClassificationPolicy_Create.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 COMMUNICATION_CONNECTION_STRING="" node dist/ClassificationPolicy_Create.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[classificationpolicy_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Create.ts -[classificationpolicy_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Delete.ts -[classificationpolicy_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Get.ts -[classificationpolicy_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_List.ts -[classificationpolicy_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Update.ts -[distributionpolicy_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Create.ts -[distributionpolicy_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Delete.ts -[distributionpolicy_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Get.ts -[distributionpolicy_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_List.ts -[distributionpolicy_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Update.ts -[exceptionpolicy_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Create.ts -[exceptionpolicy_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Delete.ts -[exceptionpolicy_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Get.ts -[exceptionpolicy_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_List.ts -[exceptionpolicy_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Update.ts -[quickstart]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/QuickStart.ts -[routerjob_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Create.ts -[routerjob_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Delete.ts -[routerjob_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Get.ts -[routerjob_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_List.ts -[routerjob_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Update.ts -[routerqueue_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Create.ts -[routerqueue_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Delete.ts -[routerqueue_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Get.ts -[routerqueue_getstatistics]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_GetStatistics.ts -[routerqueue_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_List.ts -[routerqueue_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Update.ts -[routerworker_create]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Create.ts -[routerworker_delete]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Delete.ts -[routerworker_get]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Get.ts -[routerworker_list]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_List.ts -[routerworker_update]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Update.ts -[apiref]: https://learn.microsoft.com/javascript/api/@azure/communication-job-router -[freesub]: https://azure.microsoft.com/free/ -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-job-router-rest/README.md -[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/package.json b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/package.json deleted file mode 100644 index 6729308f8f99..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "@azure-samples/communication-job-router-ts-beta", - "private": true, - "version": "1.0.0", - "description": "Azure client library for Azure Communication Job Router services client library samples for TypeScript (Beta)", - "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-job-router-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-job-router-rest", - "dependencies": { - "@azure-rest/communication-job-router": "next", - "dotenv": "latest" - }, - "devDependencies": { - "@types/node": "^18.0.0", - "typescript": "~5.8.2", - "rimraf": "latest" - } -} diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/sample.env b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/sample.env deleted file mode 100644 index 64e43f31bba2..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/sample.env +++ /dev/null @@ -1,3 +0,0 @@ -# Used in most samples. Retrieve these values from a Communication Services instance -# in the Azure Portal. -COMMUNICATION_CONNECTION_STRING="endpoint=https://.communication.azure.net/;accessKey=" diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Create.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Create.ts deleted file mode 100644 index 292624380656..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Create.ts +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import * as dotenv from "dotenv"; -/** - * @summary Classification policy crud - */ -import JobRouter, { - QueueLengthExceptionTrigger, - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; - -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a classification policy -async function createClassificationPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient.path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId).patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - } - }) - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger: QueueLengthExceptionTrigger = { - kind: "queue-length", - threshold: 100, - }; - - const exceptionPolicyId = "exception-policy-123"; - await routerClient.path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId).patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [{ - id: "MaxWaitTimeExceeded", - actions: [{ - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }], - trigger: queueLengthExceptionTrigger, - }] - } - }) - - const classificationPolicyId = "classification-policy-123"; - const salesQueueId = "queue-123"; - await routerClient.path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId).patch({ - contentType: "application/merge-patch+json", - body: { - name: "Default Classification Policy", - fallbackQueueId: salesQueueId, - queueSelectorAttachments: [ - { - kind: "static", - queueSelector: { key: "department", labelOperator: "equal", value: "xbox" } - }, - ], - workerSelectorAttachments: [{ - kind: "static", - workerSelector: { key: "english", labelOperator: "greaterThan", value: 5 } - }], - prioritizationRule: { - kind: "expression-rule", - language: "powerFx", - expression: "If(job.department = \"xbox\", 2, 1)" - } - } - }); - - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: "distribution-policy-123", - name: "Main", - labels: {}, - exceptionPolicyId: "exception-policy-123", - } - }) - - const result = await routerClient.path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId).patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - fallbackQueueId: "queue-123", - queueSelectorAttachments: [ - { - kind: "conditional", - queueSelectors: [{ - key: "foo", - labelOperator: "equal", - value: { default: 10 }, - }], - condition: { - kind: "direct-map-rule" - } - }, - ], - prioritizationRule: { - kind: "static-rule", - value: { default: 2 }, - }, - } - }); - - console.log("classification policy: " + result); -} - -void createClassificationPolicy(); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Delete.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Delete.ts deleted file mode 100644 index e685fafcc21e..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Delete.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - - -/** - * @summary Classification policy crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete classification policy -async function deleteClassificationPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const policyId = "classification-policy-123"; - - const result = await routerClient.path("/routing/classificationPolicies/{classificationPolicyId}", policyId).delete(); - - console.log("classification policy: " + result); -} - -deleteClassificationPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Get.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Get.ts deleted file mode 100644 index 2e593305e545..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Get.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Classification policy crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a classification policy - -async function getClassificationPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const policyId = "classification-policy-123"; - - const result = await routerClient.path("/routing/classificationPolicies/{classificationPolicyId}", policyId).get(); - - console.log("classification policy: " + result); -} - -void getClassificationPolicy(); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_List.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_List.ts deleted file mode 100644 index 35add20dfba1..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_List.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Classification policy crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient, - paginate -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List classification policies -async function listClassificationPolicies(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - // let pagesCount = 1; - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient.path("/routing/classificationPolicies").get({ queryParameters: { maxpagesize: maxPageSize } }) - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } - -} - -listClassificationPolicies().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Update.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Update.ts deleted file mode 100644 index 2639fabc16e3..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ClassificationPolicy_Update.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** - * @summary Classification policy crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient, -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a classification policy -async function updateClassificationPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const classificationPolicyId = "classification-policy-123"; - const salesQueueId = "queue-123"; - const result = await routerClient.path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId).patch({ - contentType: "application/merge-patch+json", - body: { - name: "Default Classification Policy", - fallbackQueueId: salesQueueId, - queueSelectorAttachments: [ - { - kind: "static", - queueSelector: { key: "department", labelOperator: "equal", value: "xbox" } - }, - ], - workerSelectorAttachments: [{ - kind: "static", - workerSelector: { key: "english", labelOperator: "greaterThan", value: 5 } - }], - prioritizationRule: { - kind: "expression-rule", - language: "powerFx", - expression: "If(job.department = \"xbox\", 2, 1)" - } - } - }); - - console.log("classification policy: " + result); -} - -void updateClassificationPolicy(); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Create.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Create.ts deleted file mode 100644 index 4b2642f2609d..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Create.ts +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - - -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create an distribution policy -async function createDistributionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const id = "distribution-policy-123"; - const result = await routerClient.path("/routing/distributionPolicies/{distributionPolicyId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - } - }) - - console.log("distribution policy: " + result); -} - -createDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Delete.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Delete.ts deleted file mode 100644 index eb29349c0bcd..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Delete.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - - -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete distribution policy -async function deleteDistributionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const policyId = "distribution-policy-123"; - - const result = await routerClient.path("/routing/distributionPolicies/{distributionPolicyId}", policyId).delete(); - - console.log("distribution policy: " + result); -} - -deleteDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Get.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Get.ts deleted file mode 100644 index fb274ccfc6b6..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Get.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - - -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a distribution policy - -async function getDistributionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const policyId = "distribution-policy-123"; - - const result = await routerClient.path("/routing/distributionPolicies/{distributionPolicyId}", policyId).get(); - - console.log("distribution policy: " + result); -} - -getDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_List.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_List.ts deleted file mode 100644 index 5fd95065937d..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_List.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - - -import JobRouter, { - AzureCommunicationRoutingServiceClient, - paginate -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List distribution policies -async function listDistributionPolicies(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient.path("/routing/distributionPolicies").get({ queryParameters: { maxpagesize: maxPageSize } }) - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listDistributionPolicies().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Update.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Update.ts deleted file mode 100644 index c65935dc048f..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/DistributionPolicy_Update.ts +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Distribution policy crud - */ - - -import JobRouter, { - AzureCommunicationRoutingServiceClient, -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a distribution policy -async function updateDistributionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const id = "distribution-policy-123"; - const result = await routerClient.path("/routing/distributionPolicies/{distributionPolicyId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - } - }) - - console.log("distribution policy: " + result); -} - -updateDistributionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Create.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Create.ts deleted file mode 100644 index af77e7bae8f8..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Create.ts +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient, - QueueLengthExceptionTrigger -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create an exception policy -async function createExceptionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger: QueueLengthExceptionTrigger = { - kind: "queue-length", - threshold: 10, - }; - - const id = "exception-policy-123"; - - const result = await routerClient.path("/routing/exceptionPolicies/{exceptionPolicyId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [{ - id: "MaxWaitTimeExceeded", - actions: [{ - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }], - trigger: queueLengthExceptionTrigger, - }] - } - }); - - console.log("exception policy: " + result); -} - -createExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Delete.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Delete.ts deleted file mode 100644 index aed2576f2323..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Delete.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete exception policy -async function deleteExceptionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const policyId = "exception-policy-123"; - - const result = await routerClient.path("/routing/exceptionPolicies/{exceptionPolicyId}", policyId).delete(); - - console.log("exception policy: " + result); -} - -deleteExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Get.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Get.ts deleted file mode 100644 index b461493de375..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Get.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a exception policy - -async function getExceptionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const policyId = "exception-policy-123"; - - const result = await routerClient.path("/routing/exceptionPolicies/{exceptionPolicyId}", policyId).get(); - - console.log("exception policy: " + result); -} - -getExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_List.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_List.ts deleted file mode 100644 index f355e290b1ed..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_List.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ - - - -import JobRouter, { - AzureCommunicationRoutingServiceClient, - paginate -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listExceptionPolicies(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient.path("/routing/exceptionPolicies").get({ queryParameters: { maxpagesize: maxPageSize } }) - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listExceptionPolicies().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Update.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Update.ts deleted file mode 100644 index e5e8f8ac1849..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/ExceptionPolicy_Update.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Exception policy crud - */ - -import JobRouter, { - QueueLengthExceptionTrigger, - AzureCommunicationRoutingServiceClient, -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a exception policy -async function updateExceptionPolicy(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger: QueueLengthExceptionTrigger = { - kind: "queue-length", - threshold: 10, - }; - - const id = "exception-policy-123"; - - const result = await routerClient.path("/routing/exceptionPolicies/{exceptionPolicyId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [{ - id: "MaxWaitTimeExceeded", - actions: [{ - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }], - trigger: queueLengthExceptionTrigger, - }] - } - }); - console.log("exception policy: " + result); -} - -updateExceptionPolicy().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/QuickStart.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/QuickStart.ts deleted file mode 100644 index a41f68868063..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/QuickStart.ts +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary Quick start workflow for creating queue, job and worker, routing/matching job with worker - */ -import JobRouter, { - RouterWorkerOutput, - AzureCommunicationRoutingServiceClient, - AcceptJobOfferResultOutput, - RouterJobOutput -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -async function quickStart(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - // Create a Distribution Policy - const distributionPolicyId = "distribution-policy-123"; - await routerClient.path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId).patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - } - }) - - // Create a Queue - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: distributionPolicyId, - name: "Main", - } - }) - - // Create a Job - const jobId = "router-job-123"; - await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelId: "ChatChannel", - queueId: queueId, - channelReference: "abc", - priority: 2, - labels: {}, - } - }) - - // Register a Worker - // Register a worker associated with the queue that was just created. We will assign labels to the - // worker to include all relevant information for example, skills, which will be used to determine - // whether a job can be offered to a worker or not. - const workerId = "router-worker-123" - await routerClient.path("/routing/workers/{workerId}", workerId).patch({ - contentType: "application/merge-patch+json", - body: { - capacity: 100, - queues: [ - queueId - ], - labels: {}, - channels: [{ - channelId: "ChatChannel", - capacityCostPerJob: 10 - }, { - channelId: "CustomVoiceChannel", - capacityCostPerJob: 100 - }], - availableForOffers: true - } - }) - - await delay(5000); - // Check offers to a Worker - // Once the worker has been registered, Router will send an offer to the worker if the worker satisfies requirements - // for a job. See Offer flow https://learn.microsoft.com/azure/communication-services/concepts/router/concepts#offer - // - // We should get a RouterWorkerOfferIssued from our EventGrid subscription. - - // However, we could also wait a few seconds and then query the worker directly against the Job Router API to see if - // an offer was issued to it. - const workerResponse = await routerClient.path("/routing/workers/{workerId}", workerId).get(); - if (workerResponse.status !== "200") { - throw new Error("get works fails") - } - const workerResult = (workerResponse.body as RouterWorkerOutput) - - for await (let offer of workerResult.offers!) { - console.log(`Worker ${workerId} has an active offer for job ${offer.jobId}`); - } - - - // Accepting an offer - // Once a worker receives an offer, it can take two possible actions: accept or decline. We are going to accept the offer. - // fetching the offer id - const jobOffer = workerResult.offers![0]; - - const offerId = jobOffer.offerId; // `OfferId` can be retrieved directly from consuming event from Event grid - - // accepting the offer sent to `worker-1` - const acceptJobOfferResponse = await routerClient.path("/routing/workers/{workerId}/offers/{offerId}:accept", workerId, offerId).post() - if (acceptJobOfferResponse.status !== "200") { - throw new Error("accept job offer fails") - } - const acceptJobOfferResult = (acceptJobOfferResponse.body as AcceptJobOfferResultOutput) - - console.log(`Offer: ${jobOffer.offerId} sent to worker: ${workerId} has been accepted`); - console.log( - `Job has been assigned to worker: ${workerId} with assignment: ${acceptJobOfferResult.assignmentId}` - ); - - // verify job assignment is populated when querying job - let updatedJobResponse = await routerClient.path("/routing/jobs/{jobId}", jobId).get(); - if (updatedJobResponse.status !== "200") { - throw new Error("get job fails") - } - let updatedJob = (updatedJobResponse.body as RouterJobOutput) - - - console.log(`Job assignment has been successful: - ${updatedJob.status == "assigned" && - updatedJob.assignments!.hasOwnProperty(acceptJobOfferResult.assignmentId) - }`); - - // Completing a job - // Once the worker is done with the job, the worker has to mark the job as `completed`. - const completeJob = await routerClient.path("/routing/jobs/{jobId}/assignments/{assignmentId}:complete", jobId, acceptJobOfferResult.assignmentId).post({ - body: { - note: `Job has been completed by ${workerId} at ${new Date()}` - } - }) - - console.log(`Job has been successfully completed: ${completeJob}`); - - // Closing a job - // After a job has been completed, the worker can perform wrap up actions to the job before closing the job and finally - // releasing its capacity to accept more incoming jobs - const closeJob = await routerClient.path("/routing/jobs/{jobId}/assignments/{assignmentId}:close", jobId, acceptJobOfferResult.assignmentId).post({ - body: { - note: `Job has been closed by ${workerId} at ${new Date()}` - } - }) - console.log(`Job has been successfully closed: ${closeJob}`); - - // Optionally, a job can also be set up to be marked as closed in the future. - const afterTwoSeconds = new Date(); - afterTwoSeconds.setSeconds(afterTwoSeconds.getSeconds() + 2); - const closeJobInFuture = await routerClient.path("/routing/jobs/{jobId}/assignments/{assignmentId}:close", jobId, acceptJobOfferResult.assignmentId).post({ - body: { - closeAt: afterTwoSeconds, - note: `Job has been marked to close in the future by ${workerId} at ${afterTwoSeconds}` - } - }) - console.log(`Job has been marked to close: ${closeJobInFuture}`); // You'll received a 202 in that case - - await delay(2000); - - updatedJobResponse = await routerClient.path("/routing/jobs/{jobId}", jobId).get(); - if (updatedJobResponse.status !== "200") { - throw new Error("get job fails") - } - updatedJob = (updatedJobResponse.body as RouterJobOutput) - - console.log(`Updated job status: ${updatedJob.status == "closed"}`); -} - -function delay(ms: number) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -quickStart().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Create.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Create.ts deleted file mode 100644 index 2ef9cc882b73..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Create.ts +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient, - QueueLengthExceptionTrigger -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a router job -async function createRouterJob(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient.path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId).patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - } - }) - - // define exception trigger for queue over flow - const queueLengthExceptionTrigger: QueueLengthExceptionTrigger = { - kind: "queue-length", - threshold: 100, - }; - - const exceptionPolicyId = "exception-policy-123"; - await routerClient.path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId).patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - exceptionRules: [{ - id: "MaxWaitTimeExceeded", - actions: [{ - kind: "reclassify", - classificationPolicyId: "Main", - labelsToUpsert: { - escalated: true, - }, - }], - trigger: queueLengthExceptionTrigger, - }] - } - }); - - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: "distribution-policy-123", - name: "Main", - labels: {}, - exceptionPolicyId: "exception-policy-123", - } - }) - - - const jobId = "router-job-123"; - const result = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelId: "ChatChannel", - queueId: queueId, - channelReference: "abc", - priority: 2, - labels: {}, - } - }) - - console.log("router job: " + result); -} - -createRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Delete.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Delete.ts deleted file mode 100644 index 6ef5ac115e70..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Delete.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete router job -async function deleteRouterJob(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const entityId = "router-job-123"; - - const result = await routerClient.path("/routing/jobs/{jobId}", entityId).delete(); - - console.log("router job: " + result); -} - -deleteRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Get.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Get.ts deleted file mode 100644 index 96462330aeec..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Get.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router job - -async function getRouterJob(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const entityId = "router-job-123"; - - const result = await routerClient.path("/routing/jobs/{jobId}", entityId).get(); - - console.log("router job: " + result); -} - -getRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_List.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_List.ts deleted file mode 100644 index a4ac94a1eae5..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_List.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -import JobRouter, { - paginate, - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listRouterJobs(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient.path("/routing/jobs").get({ queryParameters: { maxpagesize: maxPageSize } }) - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listRouterJobs().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Update.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Update.ts deleted file mode 100644 index 1c2e1b042a08..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterJob_Update.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router job crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a router job -async function updateRouterJob(): Promise { - // Create the JobRouter Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const queueId = "queue-123"; - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: "distribution-policy-123", - name: "Main", - labels: {}, - exceptionPolicyId: "exception-policy-123", - } - }) - - const jobId = "router-job-123"; - const result = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelId: "ChatChannel", - queueId: queueId, - channelReference: "abc", - priority: 2, - labels: {}, - } - }) - - console.log("router job: " + result); -} - -updateRouterJob().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Create.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Create.ts deleted file mode 100644 index 561d6c626e28..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Create.ts +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient, -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a router jobQueue -async function createJobQueue(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient.path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId).patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - } - }) - - const queueId = "queue-123"; - const result = await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: distributionPolicyId, - name: "Main", - } - }) - - console.log("router jobQueue: " + result); -} - -createJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Delete.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Delete.ts deleted file mode 100644 index 26d57b1027ef..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Delete.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete router jobQueue -async function deleteJobQueue(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const entityId = "queue-123"; - - const result = await routerClient.path("/routing/queues/{queueId}", entityId).delete(); - - console.log("router jobQueue: " + result); -} - -deleteJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Get.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Get.ts deleted file mode 100644 index 086be0aca660..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Get.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router jobQueue - -async function getJobQueue(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const entityId = "router-jobQueue-123"; - - const result = await routerClient.path("/routing/queues/{queueId}", entityId).get(); - - console.log("router jobQueue: " + result); -} - -getJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_GetStatistics.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_GetStatistics.ts deleted file mode 100644 index 9a2b05e1b783..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_GetStatistics.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ - - - -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router jobQueue's statistics - -async function getJobQueueStatistics(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const entityId = "router-jobQueue-123"; - - const result = await routerClient.path("/routing/queues/{queueId}/statistics", entityId).get(); - - console.log("router jobQueue: " + result); -} - -getJobQueueStatistics().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_List.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_List.ts deleted file mode 100644 index 2c0f5e441946..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_List.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -import JobRouter, { - paginate, - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listJobQueues(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient.path("/routing/queues").get({ queryParameters: { maxpagesize: maxPageSize } }) - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listJobQueues().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Update.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Update.ts deleted file mode 100644 index d15672edfcea..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterQueue_Update.ts +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary job queue crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a router jobQueue -async function updateJobQueue(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const distributionPolicyId = "distribution-policy-123"; - await routerClient.path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId).patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longest-idle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - } - }) - - const queueId = "queue-123"; - const result = await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: distributionPolicyId, - name: "Main", - } - }) - - console.log("router jobQueue: " + result); -} - -updateJobQueue().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Create.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Create.ts deleted file mode 100644 index 76114640cf7a..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Create.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Create a router worker -async function createRouterWorker(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const id = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - capacity: 100, - queues: [ - "MainQueue", - "SecondaryQueue" - ], - labels: {}, - channels: [{ - channelId: "CustomChatChannel", - capacityCostPerJob: 10 - }, { - channelId: "CustomVoiceChannel", - capacityCostPerJob: 100 - }], - } - }) - - console.log("router worker: " + result); -} - -createRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Delete.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Delete.ts deleted file mode 100644 index e95fa8ca593c..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Delete.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router" -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Delete router worker -async function deleteRouterWorker(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const entityId = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", entityId).delete(); - - console.log("router worker: " + result); -} - -deleteRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Get.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Get.ts deleted file mode 100644 index 32c6da924dd2..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Get.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Get a router worker -async function getRouterWorker(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const entityId = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", entityId).get(); - - console.log("router worker: " + result); -} - -getRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_List.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_List.ts deleted file mode 100644 index 48b13f8ab718..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_List.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -import JobRouter, { - paginate, - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// List exception policies -async function listRouterWorkers(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const maxPageSize = 3; - // Get the first page which also contains information on how to get the next page. - const initialResponse = await routerClient.path("/routing/queues").get({ queryParameters: { maxpagesize: maxPageSize } }) - - if (initialResponse.status == "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, initialResponse); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - console.log(item); - } - } -} - -listRouterWorkers().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Update.ts b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Update.ts deleted file mode 100644 index 1b5e79dfd903..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/src/RouterWorker_Update.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * @summary router worker crud - */ -import JobRouter, { - AzureCommunicationRoutingServiceClient -} from "@azure-rest/communication-job-router"; -import * as dotenv from "dotenv"; -dotenv.config(); - -const connectionString = process.env["COMMUNICATION_CONNECTION_STRING"] || ""; - -// Update a router worker -async function updateRouterWorker(): Promise { - // Create the Router Client - const routerClient: AzureCommunicationRoutingServiceClient = - JobRouter(connectionString); - - const id = "router-worker-123"; - - const result = await routerClient.path("/routing/workers/{workerId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - capacity: 100, - queues: [ - "MainQueue", - "SecondaryQueue" - ], - labels: {}, - channels: [{ - channelId: "CustomChatChannel", - capacityCostPerJob: 10 - }, { - channelId: "CustomVoiceChannel", - capacityCostPerJob: 100 - }], - } - }) - console.log("router worker: " + result); -} - -updateRouterWorker().catch(console.error); diff --git a/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/tsconfig.json b/sdk/communication/communication-job-router-rest/samples/v1-beta/typescript/tsconfig.json deleted file mode 100644 index 984eed535aa8..000000000000 --- a/sdk/communication/communication-job-router-rest/samples/v1-beta/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-job-router-rest/src/azureCommunicationRoutingServiceClient.ts b/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceClient.ts index 3ee9e513f5af..25cd41fa3cc9 100644 --- a/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceClient.ts +++ b/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceClient.ts @@ -4,6 +4,7 @@ import type { ClientOptions } from "@azure-rest/core-client"; import { getClient } from "@azure-rest/core-client"; import { logger } from "./logger.js"; +import type { TokenCredential } from "@azure/core-auth"; import type { AzureCommunicationRoutingServiceClient } from "./clientDefinitions.js"; /** The optional parameters for the client */ @@ -15,17 +16,19 @@ export interface AzureCommunicationRoutingServiceClientOptions extends ClientOpt /** * Initialize a new instance of `AzureCommunicationRoutingServiceClient` * @param endpointParam - Uri of your Communication resource + * @param credentials - uniquely identify client credential * @param options - the parameter for all optional parameters */ export default function createClient( endpointParam: string, + credentials: TokenCredential, { apiVersion = "2024-01-18-preview", ...options }: AzureCommunicationRoutingServiceClientOptions = {}, ): AzureCommunicationRoutingServiceClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; - const userAgentInfo = `azsdk-js-communication-job-router-rest/1.1.0-beta.3`; + const userAgentInfo = `azsdk-js-communication-job-router-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` @@ -38,8 +41,15 @@ export default function createClient( loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info, }, + credentials: { + scopes: options.credentials?.scopes ?? ["https://communication.azure.com/.default"], + }, }; - const client = getClient(endpointUrl, options) as AzureCommunicationRoutingServiceClient; + const client = getClient( + endpointUrl, + credentials, + options, + ) as AzureCommunicationRoutingServiceClient; client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); client.pipeline.addPolicy({ @@ -53,6 +63,7 @@ export default function createClient( Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" }api-version=${apiVersion}`; } + return next(req); }, }); diff --git a/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceCustmizedClient.ts b/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceCustmizedClient.ts deleted file mode 100644 index c0c9bec08aa0..000000000000 --- a/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceCustmizedClient.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { ClientOptions } from "@azure-rest/core-client"; -import type { KeyCredential, TokenCredential } from "@azure/core-auth"; -import { isTokenCredential } from "@azure/core-auth"; -import type { AzureCommunicationRoutingServiceClient } from "./clientDefinitions.js"; -import { - createCommunicationAuthPolicy, - isKeyCredential, - parseClientArguments, -} from "@azure/communication-common"; -import createGeneratedClient from "./azureCommunicationRoutingServiceClient.js"; - -/** - * Initialize a new instance of `AzureCommunicationRoutingServiceClient` - * @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, -): AzureCommunicationRoutingServiceClient; - -/** - * Initialize a new instance of `AzureCommunicationRoutingServiceClient` - * @param endpoint - Uri of your Communication resource - * @param credentialOrOptions - The key or token credential. - * @param options - the parameter for all optional parameters - */ -export default function createClient( - endpoint: string, - credentialOrOptions?: KeyCredential | TokenCredential, - options?: ClientOptions, -): AzureCommunicationRoutingServiceClient; - -// Implementation -export default function createClient( - arg1: string, - arg2?: ClientOptions | (KeyCredential | TokenCredential), - arg3?: ClientOptions, -): AzureCommunicationRoutingServiceClient { - let credentialOrOptions: KeyCredential | TokenCredential | undefined; - let options: ClientOptions | undefined; - const connectionStringOrUrl = arg1; - - // Determine which constructor is being called based on the types of the arguments - if (isTokenCredential(arg2) || isKeyCredential(arg2)) { - credentialOrOptions = arg2 as KeyCredential | TokenCredential; - options = arg3 as ClientOptions; - } else { - options = arg2 as ClientOptions; - } - if (options === undefined) { - options = {}; - } - - // Rest of the function remains the same, using connectionStringOrUrl or endpoint as needed - const { url, credential } = parseClientArguments(connectionStringOrUrl, credentialOrOptions); - const client = createGeneratedClient(url, options); - const authPolicy = createCommunicationAuthPolicy(credential); - client.pipeline.addPolicy(authPolicy); - - return client; -} diff --git a/sdk/communication/communication-job-router-rest/src/index.ts b/sdk/communication/communication-job-router-rest/src/index.ts index 92afbd477873..1c1e0181dcda 100644 --- a/sdk/communication/communication-job-router-rest/src/index.ts +++ b/sdk/communication/communication-job-router-rest/src/index.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import AzureCommunicationRoutingServiceClient from "./azureCommunicationRoutingServiceCustmizedClient.js"; +import AzureCommunicationRoutingServiceClient from "./azureCommunicationRoutingServiceClient.js"; export * from "./azureCommunicationRoutingServiceClient.js"; export * from "./parameters.js"; diff --git a/sdk/communication/communication-job-router-rest/src/isUnexpected.ts b/sdk/communication/communication-job-router-rest/src/isUnexpected.ts index 3799fd2f884e..2a4c05d342b5 100644 --- a/sdk/communication/communication-job-router-rest/src/isUnexpected.ts +++ b/sdk/communication/communication-job-router-rest/src/isUnexpected.ts @@ -395,6 +395,7 @@ function getParametrizedPathSuccess(method: string, path: string): string[] { matchedValue = value; } } + return matchedValue; } diff --git a/sdk/communication/communication-job-router-rest/test/internal/utils/mockClient.ts b/sdk/communication/communication-job-router-rest/test/internal/utils/mockClient.ts deleted file mode 100644 index 0f5db06ffc29..000000000000 --- a/sdk/communication/communication-job-router-rest/test/internal/utils/mockClient.ts +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { ClientOptions } from "@azure-rest/core-client"; -import * as dotenv from "dotenv"; -import type { RecorderStartOptions, TestInfo } from "@azure-tools/test-recorder"; -import { Recorder, env } from "@azure-tools/test-recorder"; -import JobRouter from "../../../src/index.js"; -import type { AzureCommunicationRoutingServiceClient } from "../../../src/index.js"; -import { isNodeLike } from "@azure/core-util"; -import { generateToken } from "../../public/utils/connection.js"; - -if (isNodeLike) { - dotenv.config(); -} - -const envSetupForPlayback: { [k: string]: string } = { - COMMUNICATION_CONNECTION_STRING: "endpoint=https://endpoint/;accesskey=banana", -}; - -const fakeToken = generateToken(); -export const recorderOptions: RecorderStartOptions = { - envSetupForPlayback, - sanitizerOptions: { - bodyKeySanitizers: [{ jsonPath: "$.accessToken.token", value: fakeToken }], - }, - removeCentralSanitizers: [ - "AZSDK3493", // .name in the body is not a secret and is listed below in the beforeEach section - "AZSDK3430", // .id in the body is not a secret and is listed below in the beforeEach section - ], -}; - -export async function createRecorder(context: TestInfo | undefined): Promise { - const recorder = new Recorder(context); - await recorder.start(recorderOptions); - await recorder.addSanitizers(recorderOptions.sanitizerOptions!, ["record", "playback"]); - await recorder.setMatcher("HeaderlessMatcher"); - return recorder; -} - -export interface RecordedRouterClient { - routerClient: AzureCommunicationRoutingServiceClient; - recorder: Recorder; -} - -export async function createRecordedRouterClientWithConnectionString( - context: TestInfo, -): Promise { - const recorder = await createRecorder(context); - - return { - routerClient: JobRouter( - env.COMMUNICATION_CONNECTION_STRING as string, - recorder.configureClientOptions({}) as ClientOptions, - ), - recorder, - }; -} diff --git a/sdk/communication/communication-job-router-rest/test/public/methods/classificationPolicies.spec.ts b/sdk/communication/communication-job-router-rest/test/public/methods/classificationPolicies.spec.ts deleted file mode 100644 index b5f29d804fad..000000000000 --- a/sdk/communication/communication-job-router-rest/test/public/methods/classificationPolicies.spec.ts +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { Recorder } from "@azure-tools/test-recorder"; -import type { - AzureCommunicationRoutingServiceClient, - ClassificationPolicyOutput, -} from "../../../src/index.js"; -import { paginate } from "../../../src/index.js"; -import { - getClassificationPolicyRequest, - getDistributionPolicyRequest, - getExceptionPolicyRequest, - getQueueRequest, -} from "../utils/testData.js"; -import { createRecordedRouterClientWithConnectionString } from "../../internal/utils/mockClient.js"; -import { timeoutMs } from "../utils/constants.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("JobRouterClient", () => { - let routerClient: AzureCommunicationRoutingServiceClient; - let recorder: Recorder; - - const testRunId = "recorded-d-policies"; - - const { classificationPolicyId, classificationPolicyRequest } = - getClassificationPolicyRequest(testRunId); - - const { distributionPolicyId, distributionPolicyRequest } = - getDistributionPolicyRequest(testRunId); - - const { exceptionPolicyId, exceptionPolicyRequest } = getExceptionPolicyRequest(testRunId); - - const { queueId, queueRequest } = getQueueRequest(testRunId); - - describe("classification Policy Operations", () => { - beforeEach(async (ctx) => { - ({ routerClient, recorder } = await createRecordedRouterClientWithConnectionString(ctx)); - - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: distributionPolicyRequest, - }); - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: exceptionPolicyRequest, - }); - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: queueRequest, - }); - }); - - afterEach(async () => { - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .delete(); - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .delete(); - await routerClient.path("/routing/queues/{queueId}", queueId).delete(); - - await recorder.stop(); - }); - - it("should create a classification policy", { timeout: timeoutMs }, async () => { - const response = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: classificationPolicyRequest, - }); - - if (response.status !== "201") { - throw new Error("request fails"); - } - const result = response.body as ClassificationPolicyOutput; - - assert.isDefined(result); - assert.isDefined(result?.id); - assert.equal(result.name, classificationPolicyRequest.name); - }); - - it("should get a classification policy", { timeout: timeoutMs }, async () => { - const response = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .get(); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const result = response.body as ClassificationPolicyOutput; - - assert.equal(result.id, classificationPolicyId); - assert.equal(result.name, classificationPolicyRequest.name); - }); - - it("should update a classification policy", { timeout: timeoutMs }, async () => { - const updatePatch = { ...classificationPolicyRequest, name: "new-name" }; - let response = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: updatePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const updateResult = response.body as ClassificationPolicyOutput; - - const removePatch = { ...classificationPolicyRequest, name: null! }; - response = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: removePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const removeResult = response.body as ClassificationPolicyOutput; - - assert.isDefined(updateResult); - assert.isDefined(updateResult.id); - assert.isDefined(removeResult); - assert.isDefined(removeResult.id); - assert.equal(updateResult.name, updatePatch.name); - assert.isUndefined(removeResult.name); - }); - - it("should list classification policies", { timeout: timeoutMs }, async () => { - const result: ClassificationPolicyOutput[] = []; - const response = await routerClient - .path("/routing/classificationPolicies") - .get({ queryParameters: { maxpagesize: 20 } }); - - if (response.status === "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, response); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - result.push(item as ClassificationPolicyOutput); - } - } - - assert.isNotEmpty(result); - }); - - it("should delete a classification policy", { timeout: timeoutMs }, async () => { - const response = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .delete(); - - if (response.status !== "204") { - throw new Error("request fails"); - } - - assert.isDefined(response); - }); - }); -}); diff --git a/sdk/communication/communication-job-router-rest/test/public/methods/distributionPolicies.spec.ts b/sdk/communication/communication-job-router-rest/test/public/methods/distributionPolicies.spec.ts deleted file mode 100644 index 237346af2883..000000000000 --- a/sdk/communication/communication-job-router-rest/test/public/methods/distributionPolicies.spec.ts +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { Recorder } from "@azure-tools/test-recorder"; -import type { - AzureCommunicationRoutingServiceClient, - DistributionPolicyOutput, -} from "../../../src/index.js"; -import { paginate } from "../../../src/index.js"; -import { getDistributionPolicyRequest } from "../utils/testData.js"; -import { createRecordedRouterClientWithConnectionString } from "../../internal/utils/mockClient.js"; -import { timeoutMs } from "../utils/constants.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("JobRouterClient", () => { - let routerClient: AzureCommunicationRoutingServiceClient; - let recorder: Recorder; - - const testRunId = "recorded-d-policies"; - - const { distributionPolicyIdForCreationAndDeletionTest, distributionPolicyRequest } = - getDistributionPolicyRequest(testRunId); - - describe("Distribution Policy Operations", () => { - beforeEach(async (ctx) => { - ({ routerClient, recorder } = await createRecordedRouterClientWithConnectionString(ctx)); - }); - - afterEach(async () => { - await recorder.stop(); - }); - - it("should create a distribution policy", { timeout: timeoutMs }, async () => { - const response = await routerClient - .path( - "/routing/distributionPolicies/{distributionPolicyId}", - distributionPolicyIdForCreationAndDeletionTest, - ) - .patch({ - contentType: "application/merge-patch+json", - body: distributionPolicyRequest, - }); - - if (response.status !== "201") { - throw new Error("request fails"); - } - const result = response.body as DistributionPolicyOutput; - - assert.isDefined(result); - assert.isDefined(result?.id); - assert.equal(result.name, distributionPolicyRequest.name); - }); - - it("should get a distribution policy", { timeout: timeoutMs }, async () => { - const response = await routerClient - .path( - "/routing/distributionPolicies/{distributionPolicyId}", - distributionPolicyIdForCreationAndDeletionTest, - ) - .get(); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const result = response.body as DistributionPolicyOutput; - - assert.equal(result.id, distributionPolicyIdForCreationAndDeletionTest); - assert.equal(result.name, distributionPolicyRequest.name); - assert.equal( - result.offerExpiresAfterSeconds, - distributionPolicyRequest.offerExpiresAfterSeconds, - ); - assert.deepEqual(result.mode, distributionPolicyRequest.mode); - }); - - it("should update a distribution policy", { timeout: timeoutMs }, async () => { - const updatePatch = { ...distributionPolicyRequest, name: "new-name" }; - let response = await routerClient - .path( - "/routing/distributionPolicies/{distributionPolicyId}", - distributionPolicyIdForCreationAndDeletionTest, - ) - .patch({ - contentType: "application/merge-patch+json", - body: updatePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const updateResult = response.body as DistributionPolicyOutput; - - const removePatch = { ...distributionPolicyRequest, name: null! }; - response = await routerClient - .path( - "/routing/distributionPolicies/{distributionPolicyId}", - distributionPolicyIdForCreationAndDeletionTest, - ) - .patch({ - contentType: "application/merge-patch+json", - body: removePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const removeResult = response.body as DistributionPolicyOutput; - - assert.isDefined(updateResult); - assert.isDefined(updateResult.id); - assert.isDefined(removeResult); - assert.isDefined(removeResult.id); - assert.equal(updateResult.name, updatePatch.name); - assert.isUndefined(removeResult.name); - }); - - it("should list distribution policies", { timeout: timeoutMs }, async () => { - const result: DistributionPolicyOutput[] = []; - const response = await routerClient - .path("/routing/distributionPolicies") - .get({ queryParameters: { maxpagesize: 20 } }); - - if (response.status === "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, response); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - result.push(item as DistributionPolicyOutput); - } - } - - assert.isNotEmpty(result); - }); - - it("should delete a distribution policy", { timeout: timeoutMs }, async () => { - const response = await routerClient - .path( - "/routing/distributionPolicies/{distributionPolicyId}", - distributionPolicyIdForCreationAndDeletionTest, - ) - .delete(); - - if (response.status !== "204") { - throw new Error("request fails"); - } - - assert.isDefined(response); - }); - }); -}); diff --git a/sdk/communication/communication-job-router-rest/test/public/methods/exceptionPolicies.spec.ts b/sdk/communication/communication-job-router-rest/test/public/methods/exceptionPolicies.spec.ts deleted file mode 100644 index d68724863b2e..000000000000 --- a/sdk/communication/communication-job-router-rest/test/public/methods/exceptionPolicies.spec.ts +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { Recorder } from "@azure-tools/test-recorder"; -import type { - AzureCommunicationRoutingServiceClient, - ExceptionPolicyOutput, -} from "../../../src/index.js"; -import { paginate } from "../../../src/index.js"; -import { getExceptionPolicyRequest } from "../utils/testData.js"; -import { createRecordedRouterClientWithConnectionString } from "../../internal/utils/mockClient.js"; -import { timeoutMs } from "../utils/constants.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("JobRouterClient", () => { - let routerClient: AzureCommunicationRoutingServiceClient; - let recorder: Recorder; - - const testRunId = "recorded-d-policies"; - - const { exceptionPolicyIdForCreationAndDeletionTest, exceptionPolicyRequest } = - getExceptionPolicyRequest(testRunId); - - describe("exception Policy Operations", () => { - beforeEach(async (ctx) => { - ({ routerClient, recorder } = await createRecordedRouterClientWithConnectionString(ctx)); - }); - - afterEach(async () => { - await recorder.stop(); - }); - - it("should create a exception policy", { timeout: timeoutMs }, async () => { - // TODO. we have a transient bug for creating existed exception policy return 400, try rotate the id for Record testing if this fails - const response = await routerClient - .path( - "/routing/exceptionPolicies/{exceptionPolicyId}", - exceptionPolicyIdForCreationAndDeletionTest, - ) - .patch({ - contentType: "application/merge-patch+json", - body: exceptionPolicyRequest, - }); - - if (response.status !== "201") { - throw new Error("request fails"); - } - const result = response.body as ExceptionPolicyOutput; - - assert.isDefined(result); - assert.isDefined(result?.id); - assert.equal(result.name, exceptionPolicyRequest.name); - }); - - it("should get a exception policy", { timeout: timeoutMs }, async () => { - const response = await routerClient - .path( - "/routing/exceptionPolicies/{exceptionPolicyId}", - exceptionPolicyIdForCreationAndDeletionTest, - ) - .get(); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const result = response.body as ExceptionPolicyOutput; - - assert.equal(result.id, exceptionPolicyIdForCreationAndDeletionTest); - assert.equal(result.name, exceptionPolicyRequest.name); - // TODO. Minor. need to fix "id" in actions in exceptionRules on service repo - // assert.deepEqual(result.exceptionRules, exceptionPolicyRequest.exceptionRules); - }); - - it("should update a exception policy", { timeout: timeoutMs }, async () => { - const updatePatch = { ...exceptionPolicyRequest, name: "new-name" }; - let response = await routerClient - .path( - "/routing/exceptionPolicies/{exceptionPolicyId}", - exceptionPolicyIdForCreationAndDeletionTest, - ) - .patch({ - contentType: "application/merge-patch+json", - body: updatePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const updateResult = response.body as ExceptionPolicyOutput; - - const removePatch = { ...exceptionPolicyRequest, name: null! }; - response = await routerClient - .path( - "/routing/exceptionPolicies/{exceptionPolicyId}", - exceptionPolicyIdForCreationAndDeletionTest, - ) - .patch({ - contentType: "application/merge-patch+json", - body: removePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const removeResult = response.body as ExceptionPolicyOutput; - - assert.isDefined(updateResult); - assert.isDefined(updateResult.id); - assert.isDefined(removeResult); - assert.isDefined(removeResult.id); - assert.equal(updateResult.name, updatePatch.name); - assert.isUndefined(removeResult.name); - }); - - it("should list exception policies", { timeout: timeoutMs }, async () => { - const result: ExceptionPolicyOutput[] = []; - const response = await routerClient - .path("/routing/exceptionPolicies") - .get({ queryParameters: { maxpagesize: 20 } }); - - if (response.status === "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, response); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - result.push(item as ExceptionPolicyOutput); - } - } - - assert.isNotEmpty(result); - }); - - it("should delete a exception policy", { timeout: timeoutMs }, async () => { - const response = await routerClient - .path( - "/routing/exceptionPolicies/{exceptionPolicyId}", - exceptionPolicyIdForCreationAndDeletionTest, - ) - .delete(); - - if (response.status !== "204") { - throw new Error("request fails"); - } - - assert.isDefined(response); - }); - }); -}); diff --git a/sdk/communication/communication-job-router-rest/test/public/methods/jobs.spec.ts b/sdk/communication/communication-job-router-rest/test/public/methods/jobs.spec.ts deleted file mode 100644 index b9944e3b045a..000000000000 --- a/sdk/communication/communication-job-router-rest/test/public/methods/jobs.spec.ts +++ /dev/null @@ -1,323 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { Recorder } from "@azure-tools/test-recorder"; -import type { - AzureCommunicationRoutingServiceClient, - RouterJob, - RouterJobOutput, - RouterJobPositionDetailsOutput, -} from "../../../src/index.js"; -import { paginate } from "../../../src/index.js"; -import { - getClassificationPolicyRequest, - getDistributionPolicyRequest, - getExceptionPolicyRequest, - getJobRequest, - getQueueRequest, -} from "../utils/testData.js"; -import { createRecordedRouterClientWithConnectionString } from "../../internal/utils/mockClient.js"; -import { timeoutMs } from "../utils/constants.js"; -import { pollForJobQueued, retry } from "../utils/polling.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("JobRouterClient", () => { - let routerClient: AzureCommunicationRoutingServiceClient; - let recorder: Recorder; - - const testRunId = "recorded-jobs"; - - const { distributionPolicyId, distributionPolicyRequest } = - getDistributionPolicyRequest(testRunId); - const { exceptionPolicyId, exceptionPolicyRequest } = getExceptionPolicyRequest(testRunId); - const { queueId, queueRequest } = getQueueRequest(testRunId); - const { classificationPolicyId, classificationPolicyRequest } = - getClassificationPolicyRequest(testRunId); - const { jobId, jobRequest } = getJobRequest(testRunId); - - describe("Job Operations", () => { - beforeEach(async (ctx) => { - ({ routerClient, recorder } = await createRecordedRouterClientWithConnectionString(ctx)); - - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: distributionPolicyRequest, - }); - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: exceptionPolicyRequest, - }); - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: queueRequest, - }); - await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: classificationPolicyRequest, - }); - }); - - afterEach(async () => { - await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .delete(); - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .delete(); - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .delete(); - await routerClient.path("/routing/queues/{queueId}", queueId).delete(); - - await recorder.stop(); - }); - - it("should create a job", { timeout: timeoutMs }, async () => { - const response = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: jobRequest, - }); - if (response.status !== "201") { - throw new Error("request fails"); - } - const result = response.body as RouterJobOutput; - - assert.isDefined(result); - assert.isDefined(result.id); - assert.equal(result.id, jobId); - }); - - // TODO. Fix the transient bug on existing job - // it("should create a scheduled job", async () => { - // const currentTime: Date = new Date(); - // currentTime.setSeconds(currentTime.getSeconds() + 5); - // const scheduledTime: string = recorder.variable("scheduledTime", currentTime.toISOString()); - // - // const scheduledJob = getScheduledJob(scheduledTime); - // - // - // const response = await routerClient.path("/routing/jobs/{jobId}", scheduledJobId).patch({ - // contentType: "application/merge-patch+json", - // body: scheduledJob - // }) - // if (response.status !== "201") { - // throw new Error("request fails") - // } - // const result = (response.body as RouterJobOutput) - // - // assert.isDefined(result); - // assert.isDefined(result.id); - // assert.isDefined(result.matchingMode); - // assert.equal(result.id, scheduledJobId); - // assert.equal( - // (result.matchingMode as ScheduleAndSuspendModeOutput).scheduleAt, - // scheduledTime - // ); - // }).timeout(timeoutMs); - - it("should get a job", { timeout: timeoutMs }, async () => { - const response = await routerClient.path("/routing/jobs/{jobId}", jobId).get(); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const result = response.body as RouterJobOutput; - - assert.isDefined(result); - assert.isDefined(result.id); - assert.equal(result.id, jobId); - }); - - it("should update a job", { timeout: timeoutMs }, async () => { - const updatePatch = { ...jobRequest, priority: 25, dispositionCode: "testCode" }; - let response = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: updatePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const updateResult = response.body as RouterJobOutput; - - const removePatch = { ...jobRequest, priority: null!, dispositionCode: null! }; - response = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: removePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const removeResult = response.body as RouterJobOutput; - - assert.isDefined(updateResult); - assert.isDefined(updateResult.id); - assert.isDefined(removeResult); - assert.isDefined(removeResult.id); - assert.equal(updateResult.id, jobId); - assert.equal(removeResult.id, jobId); - assert.equal(updateResult.priority, updatePatch.priority); - assert.equal(removeResult.priority, 1); - assert.isUndefined(removeResult.dispositionCode); - }); - - it("should get queue position for a job", { timeout: timeoutMs }, async () => { - await pollForJobQueued(jobId, routerClient); - const response = await routerClient.path("/routing/jobs/{jobId}/position", jobId).get(); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const result = response.body as RouterJobPositionDetailsOutput; - - assert.isDefined(result); - assert.isDefined(result.position); - assert.equal(jobId, result.jobId); - }); - - it("should reclassify a job", { timeout: timeoutMs }, async () => { - let result; - await retry( - async () => { - const response = await routerClient - .path("/routing/jobs/{jobId}:reclassify", jobId) - .post(); - - if (response.status !== "200") { - throw new Error("request fails"); - } - result = response.body; - }, - { retries: 3, retryIntervalMs: 1500 }, - ); - - assert.isDefined(result); - }); - - it("should list jobs", { timeout: timeoutMs }, async () => { - const result: RouterJob[] = []; - const response = await routerClient - .path("/routing/jobs") - .get({ queryParameters: { maxpagesize: 20 } }); - - if (response.status === "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, response); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - result.push(item as RouterJobOutput); - } - } - - assert.isNotEmpty(result); - }); - - // it("should list scheduled jobs", async () => { - // const currentTime: Date = new Date(); - // currentTime.setSeconds(currentTime.getSeconds() + 30); - // const scheduledTime: string = recorder.variable("scheduledTime", currentTime.toISOString()); - // const result: RouterJob[] = []; - // - // const response = await routerClient.path("/routing/jobs").get({ - // queryParameters: { - // maxpagesize: 20, - // scheduledBefore: new Date(scheduledTime), - // }, - // }); - // - // if (response.status === "200") { - // // The paginate helper creates a paged async iterator using metadata from the first page. - // const items = paginate(routerClient, response); - // - // // We get an PageableAsyncIterator so we need to do `for await`. - // for await (const item of items) { - // result.push(item as RouterJobOutput); - // } - // } - // - // assert.isNotEmpty(result); - // }).timeout(timeoutMs); - - it("should cancel a job", { timeout: timeoutMs }, async () => { - let result; - await retry( - async () => { - const response = await routerClient.path("/routing/jobs/{jobId}:cancel", jobId).post(); - - if (response.status !== "200") { - throw new Error("request fails"); - } - result = response.body; - }, - { retries: 3, retryIntervalMs: 1500 }, - ); - - assert.isDefined(result); - }); - - it("should delete a job", { timeout: timeoutMs * 4 }, async () => { - let deleted = false; - await retry( - async () => { - const interResponse = await routerClient.path("/routing/jobs/{jobId}", jobId).get(); - if (interResponse.status !== "200") { - throw new Error("request fails"); - } - const job = interResponse.body as RouterJobOutput; - - if (job.status !== "cancelled") { - await routerClient.path("/routing/jobs/{jobId}:cancel", jobId).post(); - } else { - const response = await routerClient.path("/routing/jobs/{jobId}", jobId).delete(); - if (response.status !== "204") { - throw new Error("request fails"); - } - - assert.isDefined(response); - deleted = true; - } - }, - { retries: 5, retryIntervalMs: 1500 }, - ); - - assert.isTrue(deleted); - }); - - // TODO. Fix the transient bug on existing job - // it("should delete a scheduled job", async () => { - // let deleted = false; - // await retry( - // async () => { - // const interResponse = await routerClient.path("/routing/jobs/{jobId}", scheduledJobId).get() - // if (interResponse.status !== "200") { - // throw new Error("request fails") - // } - // const job = (interResponse.body as RouterJobOutput) - // - // if (job.status !== "cancelled") { - // await routerClient.path("/routing/jobs/{jobId}:cancel", scheduledJobId).post() - // } else { - // const response = await routerClient.path("/routing/jobs/{jobId}", scheduledJobId).delete() - // if (response.status !== "204") { - // throw new Error("request fails") - // } - // - // assert.isDefined(response); - // deleted = true; - // } - // }, - // { retries: 5, retryIntervalMs: 1500 } - // ); - // - // assert.isTrue(deleted) - // }).timeout(timeoutMs * 4); - }); -}); diff --git a/sdk/communication/communication-job-router-rest/test/public/methods/queues.spec.ts b/sdk/communication/communication-job-router-rest/test/public/methods/queues.spec.ts deleted file mode 100644 index a71450f3bbf0..000000000000 --- a/sdk/communication/communication-job-router-rest/test/public/methods/queues.spec.ts +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { Recorder } from "@azure-tools/test-recorder"; -import type { - AzureCommunicationRoutingServiceClient, - RouterQueueOutput, -} from "../../../src/index.js"; -import { paginate } from "../../../src/index.js"; -import { - getQueueRequest, - getExceptionPolicyRequest, - getDistributionPolicyRequest, -} from "../utils/testData.js"; -import { createRecordedRouterClientWithConnectionString } from "../../internal/utils/mockClient.js"; -import { timeoutMs } from "../utils/constants.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("JobRouterClient", () => { - let routerClient: AzureCommunicationRoutingServiceClient; - let recorder: Recorder; - - const testRunId = "recorded-queues"; - - const { distributionPolicyId, distributionPolicyRequest } = - getDistributionPolicyRequest(testRunId); - const { exceptionPolicyId, exceptionPolicyRequest } = getExceptionPolicyRequest(testRunId); - const { queueId, queueRequest } = getQueueRequest(testRunId); - - describe("Queue Operations", () => { - beforeEach(async (ctx) => { - ({ routerClient, recorder } = await createRecordedRouterClientWithConnectionString(ctx)); - - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: distributionPolicyRequest, - }); - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: exceptionPolicyRequest, - }); - }); - - afterEach(async () => { - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .delete(); - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .delete(); - - await recorder.stop(); - }); - - it("should create a queue", { timeout: timeoutMs }, async () => { - const response = await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: queueRequest, - }); - - if (response.status !== "201") { - throw new Error("request fails"); - } - const result = response.body as RouterQueueOutput; - - assert.isDefined(result); - assert.isDefined(result?.id); - assert.equal(result.name, queueRequest.name); - }); - - it("should get a queue", { timeout: timeoutMs }, async () => { - const response = await routerClient.path("/routing/queues/{queueId}", queueId).get(); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const result = response.body as RouterQueueOutput; - - assert.equal(result.id, queueId); - assert.equal(result.name, queueRequest.name); - }); - - it("should update a queue", { timeout: timeoutMs }, async () => { - const updatePatch = { ...queueRequest, name: "new-name" }; - let response = await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: updatePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const updateResult = response.body as RouterQueueOutput; - - const removePatch = { ...queueRequest, name: null! }; - response = await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: removePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const removeResult = response.body as RouterQueueOutput; - - assert.isDefined(updateResult); - assert.isDefined(updateResult.id); - assert.isDefined(removeResult); - assert.isDefined(removeResult.id); - assert.equal(updateResult.name, updatePatch.name); - assert.isUndefined(removeResult.name); - }); - - it("should list queues", { timeout: timeoutMs }, async () => { - const result: RouterQueueOutput[] = []; - const response = await routerClient - .path("/routing/queues") - .get({ queryParameters: { maxpagesize: 20 } }); - - if (response.status === "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, response); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - result.push(item as RouterQueueOutput); - } - } - - assert.isNotEmpty(result); - }); - - it("should delete a queue", { timeout: timeoutMs }, async () => { - const response = await routerClient.path("/routing/queues/{queueId}", queueId).delete(); - - if (response.status !== "204") { - throw new Error("request fails"); - } - - assert.isDefined(response); - }); - }); -}); diff --git a/sdk/communication/communication-job-router-rest/test/public/methods/workers.spec.ts b/sdk/communication/communication-job-router-rest/test/public/methods/workers.spec.ts deleted file mode 100644 index cd6ee9e149bc..000000000000 --- a/sdk/communication/communication-job-router-rest/test/public/methods/workers.spec.ts +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { Recorder } from "@azure-tools/test-recorder"; -import type { - AzureCommunicationRoutingServiceClient, - RouterWorkerOutput, -} from "../../../src/index.js"; -import { paginate } from "../../../src/index.js"; -import { - getDistributionPolicyRequest, - getExceptionPolicyRequest, - getQueueRequest, - getWorkerRequest, -} from "../utils/testData.js"; -import { createRecordedRouterClientWithConnectionString } from "../../internal/utils/mockClient.js"; -import { sleep, timeoutMs } from "../utils/constants.js"; -import { describe, it, assert, beforeEach, afterEach } from "vitest"; - -describe("JobRouterClient", () => { - let routerClient: AzureCommunicationRoutingServiceClient; - let recorder: Recorder; - - const testRunId = "recorded-workers"; - - const { distributionPolicyId, distributionPolicyRequest } = - getDistributionPolicyRequest(testRunId); - const { exceptionPolicyId, exceptionPolicyRequest } = getExceptionPolicyRequest(testRunId); - const { queueId, queueRequest } = getQueueRequest(testRunId); - const { workerId, workerRequest } = getWorkerRequest(testRunId); - - describe("Worker Operations", () => { - beforeEach(async (ctx) => { - ({ routerClient, recorder } = await createRecordedRouterClientWithConnectionString(ctx)); - - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: distributionPolicyRequest, - }); - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: exceptionPolicyRequest, - }); - await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: queueRequest, - }); - }); - - afterEach(async () => { - await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", distributionPolicyId) - .delete(); - await routerClient - .path("/routing/exceptionPolicies/{exceptionPolicyId}", exceptionPolicyId) - .delete(); - await routerClient.path("/routing/queues/{queueId}", queueId).delete(); - - await recorder.stop(); - }); - - it("should create a worker", { timeout: timeoutMs }, async () => { - const response = await routerClient.path("/routing/workers/{workerId}", workerId).patch({ - contentType: "application/merge-patch+json", - body: workerRequest, - }); - - if (response.status !== "201") { - throw new Error("request fails"); - } - const result = response.body as RouterWorkerOutput; - - assert.isDefined(result); - assert.isDefined(result?.id); - assert.equal(result.capacity, workerRequest.capacity); - }); - - it("should get a worker", { timeout: timeoutMs }, async () => { - const response = await routerClient.path("/routing/workers/{workerId}", workerId).get(); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const result = response.body as RouterWorkerOutput; - - assert.equal(result.id, workerId); - assert.equal(result.capacity, workerRequest.capacity); - assert.deepEqual(result.channels, workerRequest.channels); - }); - - it("should update a worker", { timeout: timeoutMs }, async () => { - const updatePatch = { - ...workerRequest, - capacity: 100, - labels: { label1: "label1value" }, - tags: { tag1: "tag1value" }, - }; - let response = await routerClient.path("/routing/workers/{workerId}", workerId).patch({ - contentType: "application/merge-patch+json", - body: updatePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const updateResult = response.body as RouterWorkerOutput; - - const removePatch = { ...workerRequest, tags: null! }; - response = await routerClient.path("/routing/workers/{workerId}", workerId).patch({ - contentType: "application/merge-patch+json", - body: removePatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const removeResult = response.body as RouterWorkerOutput; - - assert.isDefined(updateResult); - assert.isDefined(updateResult.id); - assert.isDefined(removeResult); - assert.isDefined(removeResult.id); - assert.equal(updateResult.capacity, updatePatch.capacity); - assert.isEmpty(removeResult.tags); - }); - - it("should register and deregister a worker", { timeout: timeoutMs }, async () => { - const registerPatch = { ...workerRequest, availableForOffers: true }; - let response = await routerClient.path("/routing/workers/{workerId}", workerId).patch({ - contentType: "application/merge-patch+json", - body: registerPatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const registerResult = response.body as RouterWorkerOutput; - - await sleep(2000); - const deregisterPatch = { ...workerRequest, availableForOffers: false }; - response = await routerClient.path("/routing/workers/{workerId}", workerId).patch({ - contentType: "application/merge-patch+json", - body: deregisterPatch, - }); - - if (response.status !== "200") { - throw new Error("request fails"); - } - const deregisterResult = response.body as RouterWorkerOutput; - - assert.isDefined(registerResult); - assert.isDefined(registerResult?.id); - assert.equal(registerResult.availableForOffers, true); - - assert.isDefined(deregisterResult); - assert.isDefined(deregisterResult?.id); - assert.equal(deregisterResult.availableForOffers, false); - }); - - it("should list workers", { timeout: timeoutMs }, async () => { - const result: RouterWorkerOutput[] = []; - const response = await routerClient - .path("/routing/workers") - .get({ queryParameters: { maxpagesize: 20 } }); - - if (response.status === "200") { - // The paginate helper creates a paged async iterator using metadata from the first page. - const items = paginate(routerClient, response); - - // We get an PageableAsyncIterator so we need to do `for await`. - for await (const item of items) { - result.push(item as RouterWorkerOutput); - } - } - - assert.isNotEmpty(result); - }); - - it("should delete a worker", { timeout: timeoutMs }, async () => { - const response = await routerClient.path("/routing/workers/{workerId}", workerId).delete(); - - if (response.status !== "204") { - throw new Error("request fails"); - } - - assert.isDefined(response); - }); - }); -}); diff --git a/sdk/communication/communication-job-router-rest/test/public/sampleTest.spec.ts b/sdk/communication/communication-job-router-rest/test/public/sampleTest.spec.ts new file mode 100644 index 000000000000..e4591bbad342 --- /dev/null +++ b/sdk/communication/communication-job-router-rest/test/public/sampleTest.spec.ts @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { assert, beforeEach, afterEach, it, describe } from "vitest"; + +describe("My test", () => { + // let recorder: Recorder; + + beforeEach(async () => { + // recorder = await createRecorder(this); + }); + + afterEach(async () => { + // await recorder.stop(); + }); + + it("sample test", async function () { + assert.equal(1, 1); + }); +}); diff --git a/sdk/communication/communication-job-router-rest/test/public/utils/connection.ts b/sdk/communication/communication-job-router-rest/test/public/utils/connection.ts deleted file mode 100644 index 339bb57667cf..000000000000 --- a/sdk/communication/communication-job-router-rest/test/public/utils/connection.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { isNodeLike } from "@azure/core-util"; - -export const baseUri = "https://contoso.api.fake"; - -declare function btoa(stringToEncode: string): string; - -export const generateToken = (): string => { - const validForMinutes = 60; - const expiresOn = (Date.now() + validForMinutes * 60 * 1000) / 1000; - const tokenString = JSON.stringify({ exp: expiresOn }); - const base64Token = isNodeLike ? Buffer.from(tokenString).toString("base64") : btoa(tokenString); - return `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${base64Token}.adM-ddBZZlQ1WlN3pdPBOF5G4Wh9iZpxNP_fSvpF4cWs`; -}; diff --git a/sdk/communication/communication-job-router-rest/test/public/utils/constants.ts b/sdk/communication/communication-job-router-rest/test/public/utils/constants.ts deleted file mode 100644 index 8c3f34496637..000000000000 --- a/sdk/communication/communication-job-router-rest/test/public/utils/constants.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// // Copyright (c) Microsoft Corporation. -// // Licensed under the MIT License. -// import { v4 as uuid } from "uuid"; -// import { env } from "@azure-tools/test-recorder"; -// -// // HACK: Intentionally block to: -// // * avoid 'duplicate sequence number' error from service (calling commands too fast?) -export function sleep(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)); -} -// -export const timeoutMs: number = 15000; -// -// export const getTestRunId = (staticId: string): string => { -// return ["record", "playback", "undefined"].includes(env.TEST_MODE!) ? staticId : uuid(); -// }; diff --git a/sdk/communication/communication-job-router-rest/test/public/utils/env-browser.mts b/sdk/communication/communication-job-router-rest/test/public/utils/env-browser.mts deleted file mode 100644 index fc36ab244fad..000000000000 --- a/sdk/communication/communication-job-router-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-job-router-rest/test/public/utils/env.ts b/sdk/communication/communication-job-router-rest/test/public/utils/env.ts deleted file mode 100644 index 866412f4082d..000000000000 --- a/sdk/communication/communication-job-router-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-job-router-rest/test/public/utils/polling.ts b/sdk/communication/communication-job-router-rest/test/public/utils/polling.ts deleted file mode 100644 index 59616a34696e..000000000000 --- a/sdk/communication/communication-job-router-rest/test/public/utils/polling.ts +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { - AzureCommunicationRoutingServiceClient, - RouterJobOutput, -} from "../../../src/index.js"; -import type { RouterJob } from "../../../src/index.js"; - -export async function pollForJobQueued( - jobId: string, - routerClient: AzureCommunicationRoutingServiceClient, -): Promise { - let job: RouterJobOutput = { - id: "dummy", - etag: "dummy", - }; - while (job.status !== "queued") { - const response = await routerClient.path("/routing/jobs/{jobId}", jobId).get(); - if (response.status !== "200") { - throw new Error("request fails"); - } - job = response.body as RouterJobOutput; - } - - return job; -} - -/** - * Runs the function `fn` - * and retries automatically if it fails. - * - * Tries max `1 + retries` times - * with `retryIntervalMs` milliseconds between retries. - * - * From https://mtsknn.fi/blog/js-retry-on-fail/ - */ -export const retry = async ( - fn: () => Promise | T, - { retries, retryIntervalMs }: { retries: number; retryIntervalMs: number }, -): Promise => { - const sleep = (ms = 0): Promise => new Promise((resolve) => setTimeout(resolve, ms)); - try { - return await fn(); - } catch (error) { - if (retries <= 0) { - throw error; - } - await sleep(retryIntervalMs); - return retry(fn, { retries: retries - 1, retryIntervalMs }); - } -}; diff --git a/sdk/communication/communication-job-router-rest/test/public/utils/recordedClient.ts b/sdk/communication/communication-job-router-rest/test/public/utils/recordedClient.ts index 7c20ce5e5829..14dcd9fa397c 100644 --- a/sdk/communication/communication-job-router-rest/test/public/utils/recordedClient.ts +++ b/sdk/communication/communication-job-router-rest/test/public/utils/recordedClient.ts @@ -1,23 +1,14 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { RecorderStartOptions, TestInfo } from "@azure-tools/test-recorder"; -import { Recorder } from "@azure-tools/test-recorder"; -import "./env.js"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - 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 replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, - removeCentralSanitizers: [ - "AZSDK3493", // .name in the body is not a secret and is listed below in the beforeEach section - "AZSDK3430", // .id in the body is not a secret and is listed below in the beforeEach section - ], + envSetupForPlayback: replaceableVariables, }; /** @@ -25,7 +16,7 @@ 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): Promise { +export async function createRecorder(context: VitestTestContext): Promise { const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; diff --git a/sdk/communication/communication-job-router-rest/test/public/utils/testData.ts b/sdk/communication/communication-job-router-rest/test/public/utils/testData.ts deleted file mode 100644 index 977538601509..000000000000 --- a/sdk/communication/communication-job-router-rest/test/public/utils/testData.ts +++ /dev/null @@ -1,417 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import type { - ClassificationPolicy, - ConditionalQueueSelectorAttachment, - DistributionPolicy, - ExceptionPolicy, - ExceptionRule, - ExpressionRouterRule, - RouterQueue, - PassThroughQueueSelectorAttachment, - RouterQueueSelector, - RouterWorker, - StaticQueueSelectorAttachment, - RouterJob, -} from "../../../src/index.js"; - -const queueId = "test-a-queue"; -const exceptionPolicyId = "test-e-policy"; -const exceptionPolicyId2 = "test-h-policy"; -const distributionPolicyId = "test-d-policy"; -const distributionPolicyId2 = "test-p-policy"; -const classificationPolicyId = "test-c-policy"; -const jobId = "test-job"; -const jobId2 = "test-8-job"; -const workerId = "test-worker"; - -const product = "O365"; -const region = "NA"; -const english = "EN"; -const french = "FR"; - -const isO365: ExpressionRouterRule = { - kind: "expression", - language: "powerFx", - expression: `If(job.Product = "${product}", true, false)`, -}; - -const isEnglish: ExpressionRouterRule = { - kind: "expression", - language: "powerFx", - expression: `If(job.Language = "${english}", true, false)`, -}; - -const isFrench: ExpressionRouterRule = { - kind: "expression", - language: "powerFx", - expression: `If(job.Language = "${french}", true, false)`, -}; - -function getQueueIdSelector(guid: string): RouterQueueSelector { - return { - key: "Id", - labelOperator: "equal", - value: { [`${queueId}-${guid}`]: `${queueId}-${guid}` }, - }; -} - -const queueDoesNotExistSelector: RouterQueueSelector = { - key: "Id", - labelOperator: "equal", - value: { queueDoesNotExist: "queueDoesNotExist" }, -}; - -const englishSelector: RouterQueueSelector = { - key: "Language", - labelOperator: "equal", - value: english, -}; - -const frenchSelector: RouterQueueSelector = { - key: "Language", - labelOperator: "equal", - value: french, -}; - -const staticQueueDoesNotExistSelector: StaticQueueSelectorAttachment = { - kind: "static", - queueSelector: queueDoesNotExistSelector, -}; - -const passThroughRegionSelector: PassThroughQueueSelectorAttachment = { - kind: "passThrough", - key: "Region", - labelOperator: "equal", -}; - -const passThroughProductSelector: PassThroughQueueSelectorAttachment = { - kind: "passThrough", - key: "Product", - labelOperator: "equal", -}; - -function getConditionalProductSelector(guid: string): ConditionalQueueSelectorAttachment { - return { - kind: "conditional", - condition: isO365, - queueSelectors: [getQueueIdSelector(guid)], - }; -} - -const conditionalEnglishSelector: ConditionalQueueSelectorAttachment = { - kind: "conditional", - condition: isEnglish, - queueSelectors: [englishSelector], -}; - -const conditionalFrenchSelector: ConditionalQueueSelectorAttachment = { - kind: "conditional", - condition: isFrench, - queueSelectors: [frenchSelector], -}; - -/** An extended model for id. */ -export interface WithId { - /** The id of model. */ - id: string; -} - -export function getQueueEnglish(guid: string): RouterQueue & WithId { - return { - id: `${queueId}-english-${guid}`, - name: `${queueId}-english-${guid}`, - distributionPolicyId: `${distributionPolicyId}-${guid}`, - labels: { Region: region, Product: product, Language: english }, - }; -} - -export function getQueueFrench(guid: string): RouterQueue & WithId { - return { - id: `${queueId}-french-${guid}`, - name: `${queueId}-french-${guid}`, - distributionPolicyId: `${distributionPolicyId}-${guid}`, - labels: { Region: region, Product: product, Language: french }, - }; -} - -export function getClassificationPolicyFallback(guid: string): ClassificationPolicy & WithId { - return { - id: `${classificationPolicyId}-fallback-${guid}`, - name: `${classificationPolicyId}-fallback`, - fallbackQueueId: `${queueId}-${guid}`, - queueSelectorAttachments: [staticQueueDoesNotExistSelector], - }; -} - -export function getClassificationPolicyConditional(guid: string): ClassificationPolicy & WithId { - return { - id: `${classificationPolicyId}-conditional-${guid}`, - name: `${classificationPolicyId}-conditional`, - fallbackQueueId: `${queueId}-${guid}`, - queueSelectorAttachments: [getConditionalProductSelector(guid)], - }; -} - -export function getClassificationPolicyPassthrough(guid: string): ClassificationPolicy & WithId { - return { - id: `${classificationPolicyId}-passthrough-${guid}`, - name: `${classificationPolicyId}-passthrough`, - fallbackQueueId: `${queueId}-${guid}`, - queueSelectorAttachments: [passThroughRegionSelector, passThroughProductSelector], - }; -} - -export function getClassificationPolicyCombined(guid: string): ClassificationPolicy & WithId { - return { - id: `${classificationPolicyId}-combined-${guid}`, - name: `${classificationPolicyId}-combined`, - fallbackQueueId: `${queueId}-${guid}`, - queueSelectorAttachments: [ - passThroughRegionSelector, - passThroughProductSelector, - conditionalEnglishSelector, - conditionalFrenchSelector, - ], - }; -} - -export interface TestJobRequest { - id: string; - options: RouterJob; -} -export function getJobFallback(guid: string): TestJobRequest { - return { - id: `${jobId}-fallback-${guid}`, - options: { - channelId: "test-channel", - priority: 1, - classificationPolicyId: `${classificationPolicyId}-fallback-${guid}`, - }, - }; -} - -export function getJobConditional(guid: string): TestJobRequest { - return { - id: `${jobId}-conditional-${guid}`, - options: { - channelId: "test-channel", - priority: 1, - classificationPolicyId: `${classificationPolicyId}-conditional-${guid}`, - labels: { Product: product }, - }, - }; -} - -export function getJobPassthrough(guid: string): TestJobRequest { - return { - id: `${jobId}-passthrough-${guid}`, - options: { - channelId: "test-channel", - priority: 1, - classificationPolicyId: `${classificationPolicyId}-passthrough-${guid}`, - labels: { Region: region, Language: english }, - }, - }; -} - -export function getJobEnglish(guid: string): TestJobRequest { - return { - id: `${jobId}-english-${guid}`, - options: { - channelId: "test-channel", - priority: 1, - classificationPolicyId: `${classificationPolicyId}-combined-${guid}`, - labels: { Product: product, Region: region, Language: english }, - }, - }; -} - -export function getJobFrench(guid: string): TestJobRequest { - return { - id: `${jobId}-french-${guid}`, - options: { - channelId: "test-channel", - priority: 1, - classificationPolicyId: `${classificationPolicyId}-combined-${guid}`, - labels: { Product: product, Region: region, Language: "FR" }, - }, - }; -} - -export interface QueueRequest { - queueId: string; - queueRequest: RouterQueue & WithId; -} -export function getQueueRequest(guid: string): QueueRequest { - const id = `${queueId}-${guid}`; - return { - queueId: id, - queueRequest: { - id, - name: queueId, - exceptionPolicyId: `${exceptionPolicyId}-${guid}`, - distributionPolicyId: `${distributionPolicyId}-${guid}`, - labels: {}, - }, - }; -} - -export interface ExceptionPolicyRequest { - exceptionPolicyId: string; - exceptionPolicyIdForCreationAndDeletionTest: string; - exceptionPolicyRequest: ExceptionPolicy; -} -export function getExceptionPolicyRequestWithReclassifyAction( - guid: string, -): ExceptionPolicyRequest { - return getExceptionPolicyRequestInternal(guid, true); -} -export function getExceptionPolicyRequest(guid: string): ExceptionPolicyRequest { - return getExceptionPolicyRequestInternal(guid, false); -} -function getExceptionPolicyRequestInternal( - guid: string, - addReclassifyAction: boolean, -): ExceptionPolicyRequest { - const id = `${exceptionPolicyId}-${guid}`; - const id2 = `${exceptionPolicyId2}-${guid}`; - const exceptionRules = getExceptionRules(guid, addReclassifyAction); - return { - exceptionPolicyId: id, - exceptionPolicyIdForCreationAndDeletionTest: id2, - exceptionPolicyRequest: { - name: exceptionPolicyId, - exceptionRules, - }, - }; -} - -function getExceptionRules(guid: string, addReclassifyAction: boolean): Array { - const exceptionRules: Array = [ - { - id: "MaxWaitTimeExceededCancel", - actions: [ - { - kind: "cancel", - note: "wait time exceeded; cancelling", - }, - ], - trigger: { - kind: "waitTime", - thresholdSeconds: 10, - }, - }, - ]; - - if (addReclassifyAction) { - exceptionRules.push({ - id: "MaxWaitTimeExceededReclassify", - actions: [ - { - kind: "reclassify", - classificationPolicyId: `${classificationPolicyId}-${guid}`, - labelsToUpsert: { - escalated: true, - }, - }, - ], - trigger: { - kind: "waitTime", - thresholdSeconds: 10, - }, - }); - } - - return exceptionRules; -} - -export interface DistributionPolicyRequest { - distributionPolicyId: string; - distributionPolicyIdForCreationAndDeletionTest: string; - distributionPolicyRequest: DistributionPolicy; -} -export function getDistributionPolicyRequest(guid: string): DistributionPolicyRequest { - const id = `${distributionPolicyId}-${guid}`; - const id2 = `${distributionPolicyId2}-${guid}`; - return { - distributionPolicyId: id, - distributionPolicyIdForCreationAndDeletionTest: id2, - distributionPolicyRequest: { - name: distributionPolicyId, - offerExpiresAfterSeconds: 60, - mode: { - kind: "longestIdle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - }, - }; -} - -export interface ClassificationPolicyRequest { - classificationPolicyId: string; - classificationPolicyRequest: ClassificationPolicy; -} -export function getClassificationPolicyRequest(guid: string): ClassificationPolicyRequest { - const id = `${classificationPolicyId}-${guid}`; - return { - classificationPolicyId: id, - classificationPolicyRequest: { - name: classificationPolicyId, - fallbackQueueId: `${queueId}-${guid}`, - }, - }; -} - -export interface JobRequest { - jobId: string; - scheduledJobId: string; - jobRequest: RouterJob; -} -export function getJobRequest(guid: string): JobRequest { - const id = `${jobId}-${guid}`; - const id2 = `${jobId2}-${guid}`; - return { - jobId: id, - scheduledJobId: id2, - jobRequest: { - channelId: "test-channel", - priority: 1, - classificationPolicyId: `${classificationPolicyId}-${guid}`, - queueId: `${queueId}-${guid}`, - labels: {}, - notes: [], - matchingMode: { - kind: "queueAndMatch", - }, - }, - }; -} - -export interface WorkerRequest { - workerId: string; - workerRequest: RouterWorker & WithId; -} -export function getWorkerRequest(guid: string): WorkerRequest { - const id = `${workerId}-${guid}`; - return { - workerId: id, - workerRequest: { - id, - capacity: 1, - availableForOffers: false, - queues: [`${queueId}-${guid}`], - channels: [ - { - channelId: "test-channel", - capacityCostPerJob: 1, - }, - ], - labels: {}, - maxConcurrentOffers: 1, - }, - }; -} diff --git a/sdk/communication/communication-job-router-rest/test/snippets.spec.ts b/sdk/communication/communication-job-router-rest/test/snippets.spec.ts index 6ebf8f50fd28..5d6136453264 100644 --- a/sdk/communication/communication-job-router-rest/test/snippets.spec.ts +++ b/sdk/communication/communication-job-router-rest/test/snippets.spec.ts @@ -1,213 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import JobRouterClient from "../src/index.js"; import { setLogLevel } from "@azure/logger"; import { describe, it } from "vitest"; -import { isUnexpected } from "../generated/isUnexpected.js"; describe("snippets", () => { - it("ReadmeSampleCreateClient", async () => { - const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; - const routerClient = JobRouterClient(connectionString); - }); - - it("ReadmeSampleCreateDistributionPolicy", async () => { - const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; - const routerClient = JobRouterClient(connectionString); - // @ts-preserve-whitespace - const id = "distribution-policy-123"; - const result = await routerClient - .path("/routing/distributionPolicies/{distributionPolicyId}", id) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "distribution-policy-123", - mode: { - kind: "longestIdle", - minConcurrentOffers: 1, - maxConcurrentOffers: 5, - bypassSelectors: false, - }, - offerExpiresAfterSeconds: 120, - }, - }); - }); - - it("ReadmeSampleCreateQueue", async () => { - const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; - const routerClient = JobRouterClient(connectionString); - // @ts-preserve-whitespace - const distributionPolicyId = "distribution-policy-123"; - const queueId = "queue-123"; - const result = await routerClient.path("/routing/queues/{queueId}", queueId).patch({ - contentType: "application/merge-patch+json", - body: { - distributionPolicyId: distributionPolicyId, - name: "Main", - }, - }); - }); - - it("ReadmeSampleCreateWorkers", async () => { - const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; - const routerClient = JobRouterClient(connectionString); - // @ts-preserve-whitespace - const id = "router-worker-123"; - const result = await routerClient.path("/routing/workers/{workerId}", id).patch({ - contentType: "application/merge-patch+json", - body: { - capacity: 100, - queues: ["MainQueue", "SecondaryQueue"], - labels: {}, - channels: [ - { - channelId: "CustomChatChannel", - capacityCostPerJob: 10, - }, - { - channelId: "CustomVoiceChannel", - capacityCostPerJob: 100, - }, - ], - }, - }); - }); - - it("ReadmeSampleCreateJob", async () => { - const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; - const routerClient = JobRouterClient(connectionString); - // @ts-preserve-whitespace - const queueId = "queue-123"; - const jobId = "router-job-123"; - const result = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelId: "ChatChannel", - queueId: queueId, - channelReference: "abc", - priority: 2, - labels: {}, - }, - }); - }); - - it("ReadmeSampleCreateClassificationPolicy", async () => { - const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; - const routerClient = JobRouterClient(connectionString); - // @ts-preserve-whitespace - const classificationPolicyId = "classification-policy-123"; - // @ts-preserve-whitespace - const result = await routerClient - .path("/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId) - .patch({ - contentType: "application/merge-patch+json", - body: { - name: "test-policy", - fallbackQueueId: "queue-123", - queueSelectorAttachments: [ - { - kind: "conditional", - queueSelectors: [ - { - key: "foo", - labelOperator: "equal", - value: { default: 10 }, - }, - ], - condition: { - kind: "direct-map-rule", - }, - }, - ], - prioritizationRule: { - kind: "static", - value: { default: 2 }, - }, - }, - }); - }); - - it("ReadmeSampleCreateJobWithClassificationPolicy", async () => { - const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; - const routerClient = JobRouterClient(connectionString); - // @ts-preserve-whitespace - const jobId = "router-job-123"; - const classificationPolicyId = "classification-policy-123"; - const job = await routerClient.path("/routing/jobs/{jobId}", jobId).patch({ - contentType: "application/merge-patch+json", - body: { - channelReference: "66e4362e-aad5-4d71-bb51-448672ebf492", - channelId: "voice", - classificationPolicyId: classificationPolicyId, - labels: { - department: "xbox", - }, - }, - }); - }); - - it("ReadmeSampleAcceptOrDeclineOffer", async () => { - const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; - const routerClient = JobRouterClient(connectionString); - // @ts-preserve-whitespace - const workerId = "router-worker-123"; - const offerId = "offer-id"; - // @ts-preserve-whitespace - // Accept the job offer - const acceptResponse = await routerClient - .path("/routing/workers/{workerId}/offers/{offerId}:accept", workerId, offerId) - .post(); - // or decline the job offer - const declineResponse = await routerClient - .path("/routing/workers/{workerId}/offers/{offerId}:decline", workerId, offerId) - .post(); - }); - - it("ReadmeSampleCompleteJob", async () => { - const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; - const routerClient = JobRouterClient(connectionString); - // @ts-preserve-whitespace - const workerId = "router-worker-123"; - const jobId = "job-id"; - const assignmentId = "assignment-id"; - // @ts-preserve-whitespace - const completeJob = await routerClient - .path("/routing/jobs/{jobId}/assignments/{assignmentId}:complete", jobId, assignmentId) - .post({ - body: { - note: `Job has been completed by ${workerId} at ${new Date()}`, - }, - }); - }); - - it("ReadmeSampleCloseJob", async () => { - const connectionString = - "endpoint=https://.communication.azure.com/;accesskey="; - const routerClient = JobRouterClient(connectionString); - // @ts-preserve-whitespace - const workerId = "router-worker-123"; - const jobId = "job-id"; - const assignmentId = "assignment-id"; - // @ts-preserve-whitespace - const closeJob = await routerClient - .path("/routing/jobs/{jobId}/assignments/{assignmentId}:close", jobId, assignmentId) - .post({ - body: { - note: `Job has been closed by ${workerId} at ${new Date()}`, - }, - }); - }); - it("SetLogLevel", async () => { setLogLevel("info"); }); diff --git a/sdk/communication/communication-job-router-rest/tsconfig.json b/sdk/communication/communication-job-router-rest/tsconfig.json index 273d9078a24a..59ea83c046bf 100644 --- a/sdk/communication/communication-job-router-rest/tsconfig.json +++ b/sdk/communication/communication-job-router-rest/tsconfig.json @@ -1,7 +1,10 @@ { "references": [ - { "path": "./tsconfig.src.json" }, - { "path": "./tsconfig.samples.json" }, - { "path": "./tsconfig.test.json" } + { + "path": "./tsconfig.src.json" + }, + { + "path": "./tsconfig.test.json" + } ] -} +} \ No newline at end of file diff --git a/sdk/communication/communication-job-router-rest/tsp-location.yaml b/sdk/communication/communication-job-router-rest/tsp-location.yaml index 392b6654ee71..8f1e550f2543 100644 --- a/sdk/communication/communication-job-router-rest/tsp-location.yaml +++ b/sdk/communication/communication-job-router-rest/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/communication/Communication.JobRouter -commit: d85dc63616d14d9790b224d46aad024e3461955b -repo: ../azure-rest-api-specs +commit: 726419b7eba57b9b5888ca11e055c8f82dcaae58 +repo: Azure/azure-rest-api-specs additionalDirectories: diff --git a/sdk/communication/communication-job-router-rest/vitest.browser.config.ts b/sdk/communication/communication-job-router-rest/vitest.browser.config.ts index 50ec2d5489b0..182729ab5ce9 100644 --- a/sdk/communication/communication-job-router-rest/vitest.browser.config.ts +++ b/sdk/communication/communication-job-router-rest/vitest.browser.config.ts @@ -1,3 +1,4 @@ + // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. @@ -8,9 +9,9 @@ export default mergeConfig( viteConfig, defineConfig({ test: { - include: ["dist-test/browser/test/**/*.spec.js"], - hookTimeout: 5000000, - testTimeout: 5000000, + include: ["dist-test/browser/test/**/*.spec.js",], + testTimeout: 1200000, + hookTimeout: 1200000, }, }), ); diff --git a/sdk/communication/communication-job-router-rest/vitest.config.ts b/sdk/communication/communication-job-router-rest/vitest.config.ts index 8849d7428190..40e031385dd8 100644 --- a/sdk/communication/communication-job-router-rest/vitest.config.ts +++ b/sdk/communication/communication-job-router-rest/vitest.config.ts @@ -1,3 +1,4 @@ + // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. @@ -8,8 +9,8 @@ export default mergeConfig( viteConfig, defineConfig({ test: { - hookTimeout: 5000000, - testTimeout: 5000000, + testTimeout: 1200000, + hookTimeout: 1200000, }, }), ); diff --git a/sdk/communication/communication-job-router-rest/vitest.esm.config.ts b/sdk/communication/communication-job-router-rest/vitest.esm.config.ts index 2f6e757a54f7..a70127279fc9 100644 --- a/sdk/communication/communication-job-router-rest/vitest.esm.config.ts +++ b/sdk/communication/communication-job-router-rest/vitest.esm.config.ts @@ -1,3 +1,4 @@ + // Copyright (c) Microsoft Corporation. // Licensed under the MIT License.