diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 99321d0907bc..0812340438f3 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -1,7 +1,7 @@ lockfileVersion: '6.0' settings: - autoInstallPeers: true + autoInstallPeers: false excludeLinksFromLockfile: false dependencies: @@ -770,6 +770,9 @@ dependencies: '@rush-temp/container-registry': specifier: file:./projects/container-registry.tgz version: file:projects/container-registry.tgz + '@rush-temp/contoso-widgetmanager-rest': + specifier: file:./projects/contoso-widgetmanager-rest.tgz + version: file:projects/contoso-widgetmanager-rest.tgz '@rush-temp/core-amqp': specifier: file:./projects/core-amqp.tgz version: file:projects/core-amqp.tgz @@ -4495,7 +4498,7 @@ packages: dependencies: semver: 7.5.4 shelljs: 0.8.5 - typescript: 5.3.0-dev.20231030 + typescript: 5.3.0-dev.20231102 dev: false /eastasianwidth@0.2.0: @@ -9261,8 +9264,8 @@ packages: hasBin: true dev: false - /typescript@5.3.0-dev.20231030: - resolution: {integrity: sha512-azWrF0lAiu8cBHNr6yq3RDkU/DtQScvT48ea3Ngq6oXJ/GPO0n96wCFSRQA5UbZlVVf3fAAqsUfvOdohRbrPVg==} + /typescript@5.3.0-dev.20231102: + resolution: {integrity: sha512-M1maLdHyAvE+y4w27IBplkqekR5Lzf2B7XualvF3lXJUC2165swvSmpThFdfHcXxP/+/SYmLI9z2CVvN7pEK+g==} engines: {node: '>=14.17'} hasBin: true dev: false @@ -16914,6 +16917,51 @@ packages: - utf-8-validate dev: false + file:projects/contoso-widgetmanager-rest.tgz: + resolution: {integrity: sha512-jJdgrdbZQSrCXkvEupJQs8eSy6P6bFzLil59iyHCv9ElgNDFkxHM5gUTmkh2igglcOxqO3qiKJJPW6jkmkvITQ==, tarball: file:projects/contoso-widgetmanager-rest.tgz} + name: '@rush-temp/contoso-widgetmanager-rest' + version: 0.0.0 + dependencies: + '@azure/identity': 3.3.2 + '@microsoft/api-extractor': 7.38.0(@types/node@18.18.7) + '@types/chai': 4.3.9 + '@types/mocha': 10.0.3 + '@types/node': 18.18.7 + autorest: 3.6.3 + c8: 8.0.1 + chai: 4.3.10 + cross-env: 7.0.3 + dotenv: 16.3.1 + eslint: 8.52.0 + esm: 3.2.25 + karma: 6.4.2(debug@4.3.4) + karma-chrome-launcher: 3.2.0 + karma-coverage: 2.2.1 + karma-env-preprocessor: 0.1.1 + karma-firefox-launcher: 2.1.2 + karma-junit-reporter: 2.0.1(karma@6.4.2) + karma-mocha: 2.0.1 + karma-mocha-reporter: 2.2.5(karma@6.4.2) + karma-source-map-support: 1.4.0 + karma-sourcemap-loader: 0.4.0 + mkdirp: 2.1.6 + mocha: 10.2.0 + mocha-junit-reporter: 1.23.3(mocha@10.2.0) + prettier: 2.8.8 + rimraf: 5.0.5 + source-map-support: 0.5.21 + ts-node: 10.9.1(@types/node@18.18.7)(typescript@5.2.2) + tslib: 2.6.2 + typescript: 5.2.2 + transitivePeerDependencies: + - '@swc/core' + - '@swc/wasm' + - bufferutil + - debug + - supports-color + - utf-8-validate + dev: false + file:projects/core-amqp.tgz: resolution: {integrity: sha512-1QD4JF9VVwsMjwnmpPHZHWT6/F5f7SUb3GxMcF4zT5vZZ2Lb75z3XI5qeYtzVNmVSmr+8EQvi6PMSuWPWgM5bA==, tarball: file:projects/core-amqp.tgz} name: '@rush-temp/core-amqp' @@ -20375,7 +20423,7 @@ packages: dev: false file:projects/storage-blob-changefeed.tgz: - resolution: {integrity: sha512-2LtIcl6t12irIaBaBSP/ytxkJA5VSRJ2RUg08UJEi/NVLHhjpx+NQQn/a/ebeAwpa2DefdSkfHRhgh7zn8Qzzg==, tarball: file:projects/storage-blob-changefeed.tgz} + resolution: {integrity: sha512-nBVNUHVbjsSyKfoA2uJNvG+jlJEW9Oq12K9Oha1C6GVY1rZhEpcWrkob0RJe/sCDdrMo0MBUnvL7+PkUsvhR8w==, tarball: file:projects/storage-blob-changefeed.tgz} name: '@rush-temp/storage-blob-changefeed' version: 0.0.0 dependencies: diff --git a/rush.json b/rush.json index da234b0c2be2..4308f8ebe8d6 100644 --- a/rush.json +++ b/rush.json @@ -1,7 +1,7 @@ /** * This is the main configuration file for Rush. * For full documentation, please see https://rushjs.io - */ { + */{ "$schema": "https://developer.microsoft.com/json-schemas/rush/v5/rush.schema.json", /** * (Required) This specifies the version of the Rush engine to be used in this repo. @@ -2145,6 +2145,11 @@ "packageName": "@azure/arm-playwrighttesting", "projectFolder": "sdk/playwrighttesting/arm-playwrighttesting", "versionPolicyName": "management" + }, + { + "packageName": "@azure-rest/contoso-widgetmanager-rest", + "projectFolder": "sdk/contosowidgetmanager/contosowidgetmanager-rest", + "versionPolicyName": "client" } ] -} +} \ No newline at end of file diff --git a/sdk/contosowidgetmanager/ci.yml b/sdk/contosowidgetmanager/ci.yml new file mode 100644 index 000000000000..b222395afd43 --- /dev/null +++ b/sdk/contosowidgetmanager/ci.yml @@ -0,0 +1,33 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - feature/* + - release/* + - hotfix/* + exclude: + - feature/v4 + paths: + include: + - sdk/contosowidgetmanager/ +pr: + branches: + include: + - main + - feature/* + - release/* + - hotfix/* + exclude: + - feature/v4 + paths: + include: + - sdk/contosowidgetmanager/ +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: contosowidgetmanager + Artifacts: + - name: azure-rest-contoso-widgetmanager-rest + safeName: azurerestcontosowidgetmanagerrest diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/.eslintrc.json b/sdk/contosowidgetmanager/contosowidgetmanager-rest/.eslintrc.json new file mode 100644 index 000000000000..619797ac39b6 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/.eslintrc.json @@ -0,0 +1,11 @@ +{ + "plugins": ["@azure/azure-sdk"], + "extends": ["plugin:@azure/azure-sdk/azure-sdk-base"], + "rules": { + "@azure/azure-sdk/ts-modules-only-named": "warn", + "@azure/azure-sdk/ts-apiextractor-json-types": "warn", + "@azure/azure-sdk/ts-package-json-types": "warn", + "@azure/azure-sdk/ts-package-json-engine-is-present": "warn", + "tsdoc/syntax": "warn" + } +} diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/CHANGELOG.md b/sdk/contosowidgetmanager/contosowidgetmanager-rest/CHANGELOG.md new file mode 100644 index 000000000000..2a3c906c015f --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/CHANGELOG.md @@ -0,0 +1,3 @@ +## 1.0.0-beta.1 (2023-11-02) + + - Initial Release diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/README.md b/sdk/contosowidgetmanager/contosowidgetmanager-rest/README.md new file mode 100644 index 000000000000..a10b05dfb0a4 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/README.md @@ -0,0 +1,59 @@ +# Azure WidgetManager REST client library for JavaScript + + + +**Please rely heavily on our [REST client docs](https://github.com/Azure/azure-sdk-for-js/blob/main/documentation/rest-clients.md) to use this library** + +Key links: + +- [Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/contosowidgetmanager/contosowidgetmanager-rest) +- [Package (NPM)](https://www.npmjs.com/package/@azure-rest/contoso-widgetmanager-rest) +- [API reference documentation](https://docs.microsoft.com/javascript/api/@azure-rest/contoso-widgetmanager-rest?view=azure-node-preview) +- [Samples](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/contosowidgetmanager/contosowidgetmanager-rest/samples) + +## Getting started + +### Currently supported environments + +- LTS versions of Node.js + +### Prerequisites + +- You must have an [Azure subscription](https://azure.microsoft.com/free/) to use this package. + +### Install the `@azure-rest/contoso-widgetmanager-rest` package + +Install the Azure WidgetManager REST client REST client library for JavaScript with `npm`: + +```bash +npm install @azure-rest/contoso-widgetmanager-rest +``` + +### Create and authenticate a `WidgetManagerClient` + +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) + +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 + +## Troubleshooting + +### Logging + +Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`: + +```javascript +const { setLogLevel } = require("@azure/logger"); + +setLogLevel("info"); +``` + +For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger). diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/api-extractor.json b/sdk/contosowidgetmanager/contosowidgetmanager-rest/api-extractor.json new file mode 100644 index 000000000000..dc29911c410d --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/api-extractor.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "mainEntryPointFilePath": "./types/src/index.d.ts", + "docModel": { + "enabled": true + }, + "apiReport": { + "enabled": true, + "reportFolder": "./review" + }, + "dtsRollup": { + "enabled": true, + "untrimmedFilePath": "", + "publicTrimmedFilePath": "./types/contoso-widgetmanager-rest.d.ts" + }, + "messages": { + "tsdocMessageReporting": { + "default": { + "logLevel": "none" + } + }, + "extractorMessageReporting": { + "ae-missing-release-tag": { + "logLevel": "none" + }, + "ae-unresolved-link": { + "logLevel": "none" + } + } + } +} \ No newline at end of file diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/karma.conf.js b/sdk/contosowidgetmanager/contosowidgetmanager-rest/karma.conf.js new file mode 100644 index 000000000000..a9d5f1b5fc59 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/karma.conf.js @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// https://github.com/karma-runner/karma-chrome-launcher +process.env.CHROME_BIN = require("puppeteer").executablePath(); +require("dotenv").config(); +const { relativeRecordingsPath } = require("@azure-tools/test-recorder"); +process.env.RECORDINGS_RELATIVE_PATH = relativeRecordingsPath(); + +module.exports = function (config) { + config.set({ + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: "./", + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ["source-map-support", "mocha"], + + plugins: [ + "karma-mocha", + "karma-mocha-reporter", + "karma-chrome-launcher", + "karma-firefox-launcher", + "karma-env-preprocessor", + "karma-coverage", + "karma-sourcemap-loader", + "karma-junit-reporter", + "karma-source-map-support", + ], + + // list of files / patterns to load in the browser + files: [ + "dist-test/index.browser.js", + { + pattern: "dist-test/index.browser.js.map", + type: "html", + included: false, + served: true, + }, + ], + + // list of files / patterns to exclude + exclude: [], + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + "**/*.js": ["sourcemap", "env"], + // IMPORTANT: COMMENT following line if you want to debug in your browsers!! + // Preprocess source file to calculate code coverage, however this will make source file unreadable + // "dist-test/index.js": ["coverage"] + }, + + envPreprocessor: [ + "TEST_MODE", + "ENDPOINT", + "AZURE_CLIENT_SECRET", + "AZURE_CLIENT_ID", + "AZURE_TENANT_ID", + "SUBSCRIPTION_ID", + "RECORDINGS_RELATIVE_PATH", + ], + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ["mocha", "coverage", "junit"], + + coverageReporter: { + // specify a common output directory + dir: "coverage-browser/", + reporters: [ + { type: "json", subdir: ".", file: "coverage.json" }, + { type: "lcovonly", subdir: ".", file: "lcov.info" }, + { type: "html", subdir: "html" }, + { type: "cobertura", subdir: ".", file: "cobertura-coverage.xml" }, + ], + }, + + junitReporter: { + outputDir: "", // results will be saved as $outputDir/$browserName.xml + outputFile: "test-results.browser.xml", // if included, results will be saved as $outputDir/$browserName/$outputFile + suite: "", // suite will become the package name attribute in xml testsuite element + useBrowserName: false, // add browser name to report and classes names + nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element + classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element + properties: {}, // key value pair of properties to add to the section of the report + }, + + // web server port + port: 9876, + + // enable / disable colors in the output (reporters and logs) + colors: true, + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: false, + + // --no-sandbox allows our tests to run in Linux without having to change the system. + // --disable-web-security allows us to authenticate from the browser without having to write tests using interactive auth, which would be far more complex. + browsers: ["ChromeHeadlessNoSandbox"], + customLaunchers: { + ChromeHeadlessNoSandbox: { + base: "ChromeHeadless", + flags: ["--no-sandbox", "--disable-web-security"], + }, + }, + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: 1, + + browserNoActivityTimeout: 60000000, + browserDisconnectTimeout: 10000, + browserDisconnectTolerance: 3, + + client: { + mocha: { + // change Karma's debug.html to the mocha web reporter + reporter: "html", + timeout: "600000", + }, + }, + }); +}; diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/package.json b/sdk/contosowidgetmanager/contosowidgetmanager-rest/package.json new file mode 100644 index 000000000000..37f1bab0e3da --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/package.json @@ -0,0 +1,121 @@ +{ + "name": "@azure-rest/contoso-widgetmanager-rest", + "sdk-type": "client", + "author": "Microsoft Corporation", + "version": "1.0.0-beta.1", + "description": "undefined", + "keywords": [ + "node", + "azure", + "cloud", + "typescript", + "browser", + "isomorphic" + ], + "license": "MIT", + "main": "dist/index.js", + "module": "./dist-esm/src/index.js", + "types": "./types/contoso-widgetmanager-rest.d.ts", + "repository": "github:Azure/azure-sdk-for-js", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "files": [ + "dist/", + "dist-esm/src/", + "types/contoso-widgetmanager-rest.d.ts", + "README.md", + "LICENSE", + "review/*" + ], + "engines": { + "node": ">=18.0.0" + }, + "scripts": { + "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", + "build:browser": "tsc -p . && cross-env ONLY_BROWSER=true rollup -c 2>&1", + "build:node": "tsc -p . && cross-env ONLY_NODE=true rollup -c 2>&1", + "build:samples": "echo skipped.", + "build:test": "tsc -p . && dev-tool run bundle", + "build:debug": "tsc -p . && dev-tool run bundle && api-extractor run --local", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"test/**/*.ts\"", + "clean": "rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz *.log", + "execute:samples": "echo skipped", + "extract-api": "rimraf review && mkdirp ./review && api-extractor run --local", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"test/**/*.ts\"", + "generate:client": "echo skipped", + "integration-test:browser": "dev-tool run test:browser", + "integration-test:node": "dev-tool run test:node-js-input -- --timeout 5000000 'dist-esm/test/**/*.spec.js'", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "lint:fix": "eslint package.json api-extractor.json src test --ext .ts --fix --fix-type [problem,suggestion]", + "lint": "eslint package.json api-extractor.json src test --ext .ts", + "pack": "npm pack 2>&1", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser", + "test:node": "npm run clean && npm run build:test && npm run unit-test:node", + "test": "npm run clean && npm run build:test && npm run unit-test", + "unit-test": "npm run unit-test:node && npm run unit-test:browser", + "unit-test:node": "dev-tool run test:node-ts-input -- --timeout 1200000 --exclude 'test/**/browser/*.spec.ts' 'test/**/*.spec.ts'", + "unit-test:browser": "dev-tool run test:browser", + "build": "npm run clean && tsc -p . && dev-tool run bundle && mkdirp ./review && api-extractor run --local" + }, + "sideEffects": false, + "autoPublish": false, + "dependencies": { + "@azure/core-auth": "^1.3.0", + "@azure-rest/core-client": "^1.1.4", + "@azure/core-rest-pipeline": "^1.12.0", + "@azure/logger": "^1.0.0", + "tslib": "^2.2.0", + "@azure/core-paging": "^1.5.0", + "@azure/core-lro": "^2.5.4", + "@azure/abort-controller": "^1.0.0" + }, + "devDependencies": { + "@microsoft/api-extractor": "^7.31.1", + "autorest": "latest", + "@types/node": "^18.0.0", + "dotenv": "^16.0.0", + "eslint": "^8.0.0", + "mkdirp": "^2.1.2", + "prettier": "^2.5.1", + "rimraf": "^5.0.0", + "source-map-support": "^0.5.9", + "typescript": "~5.2.0", + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0", + "@azure-tools/test-credential": "^1.0.0", + "@azure/identity": "^3.3.0", + "@azure-tools/test-recorder": "^3.0.0", + "mocha": "^10.0.0", + "esm": "^3.2.18", + "@types/mocha": "^10.0.0", + "mocha-junit-reporter": "^1.18.0", + "cross-env": "^7.0.2", + "@types/chai": "^4.2.8", + "chai": "^4.2.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-env-preprocessor": "^0.1.1", + "karma-firefox-launcher": "^2.1.2", + "karma-junit-reporter": "^2.0.1", + "karma-mocha-reporter": "^2.2.5", + "karma-mocha": "^2.0.1", + "karma-source-map-support": "~1.4.0", + "karma-sourcemap-loader": "^0.4.0", + "karma": "^6.2.0", + "c8": "^8.0.0", + "ts-node": "^10.0.0" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/contosowidgetmanager/contosowidgetmanager-rest/README.md", + "//metadata": { + "constantPaths": [ + { + "path": "src/widgetManagerClient.ts", + "prefix": "userAgentInfo" + } + ] + }, + "browser": { + "./dist-esm/test/public/utils/env.js": "./dist-esm/test/public/utils/env.browser.js" + } +} \ No newline at end of file diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/review/contoso-widgetmanager-rest.api.md b/sdk/contosowidgetmanager/contosowidgetmanager-rest/review/contoso-widgetmanager-rest.api.md new file mode 100644 index 000000000000..6aea2337aa6a --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/review/contoso-widgetmanager-rest.api.md @@ -0,0 +1,334 @@ +## API Report File for "@azure-rest/contoso-widgetmanager-rest" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { Client } from '@azure-rest/core-client'; +import { ClientOptions } from '@azure-rest/core-client'; +import { CreateHttpPollerOptions } from '@azure/core-lro'; +import { ErrorModel } from '@azure-rest/core-client'; +import { ErrorResponse } from '@azure-rest/core-client'; +import { HttpResponse } from '@azure-rest/core-client'; +import { OperationState } from '@azure/core-lro'; +import { Paged } from '@azure/core-paging'; +import { PagedAsyncIterableIterator } from '@azure/core-paging'; +import { PathUncheckedResponse } from '@azure-rest/core-client'; +import { RawHttpHeaders } from '@azure/core-rest-pipeline'; +import { RequestParameters } from '@azure-rest/core-client'; +import { SimplePollerLike } from '@azure/core-lro'; +import { StreamableMethod } from '@azure-rest/core-client'; +import { TokenCredential } from '@azure/core-auth'; + +// @public +function createClient(endpoint: string, credentials: TokenCredential, options?: ClientOptions): WidgetManagerClient; +export default createClient; + +// @public (undocumented) +export interface CreateOrUpdateWidget200Headers { + "operation-location": string; +} + +// @public +export interface CreateOrUpdateWidget200Response extends HttpResponse { + // (undocumented) + body: WidgetSuiteOutput; + // (undocumented) + headers: RawHttpHeaders & CreateOrUpdateWidget200Headers; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface CreateOrUpdateWidget201Headers { + "operation-location": string; +} + +// @public +export interface CreateOrUpdateWidget201Response extends HttpResponse { + // (undocumented) + body: WidgetSuiteOutput; + // (undocumented) + headers: RawHttpHeaders & CreateOrUpdateWidget201Headers; + // (undocumented) + status: "201"; +} + +// @public (undocumented) +export interface CreateOrUpdateWidgetBodyParam { + body: WidgetSuiteResourceMergeAndPatch; +} + +// @public (undocumented) +export interface CreateOrUpdateWidgetDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface CreateOrUpdateWidgetDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & CreateOrUpdateWidgetDefaultHeaders; + // (undocumented) + status: string; +} + +// @public +export interface CreateOrUpdateWidgetLogicalResponse extends HttpResponse { + // (undocumented) + body: WidgetSuiteOutput; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface CreateOrUpdateWidgetMediaTypesParam { + contentType: "application/merge-patch+json"; +} + +// @public (undocumented) +export type CreateOrUpdateWidgetParameters = CreateOrUpdateWidgetMediaTypesParam & CreateOrUpdateWidgetBodyParam & RequestParameters; + +// @public (undocumented) +export interface DeleteWidget202Headers { + "operation-location": string; +} + +// @public +export interface DeleteWidget202Response extends HttpResponse { + // (undocumented) + body: OperationStatusOutput; + // (undocumented) + headers: RawHttpHeaders & DeleteWidget202Headers; + // (undocumented) + status: "202"; +} + +// @public (undocumented) +export interface DeleteWidgetDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface DeleteWidgetDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & DeleteWidgetDefaultHeaders; + // (undocumented) + status: string; +} + +// @public +export interface DeleteWidgetLogicalResponse extends HttpResponse { + // (undocumented) + body: OperationStatusOutput; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export type DeleteWidgetParameters = RequestParameters; + +// @public +export interface FakedSharedModel { + createdAt: Date | string; + tag: string; +} + +// @public +export interface FakedSharedModelOutput { + createdAt: string; + tag: string; +} + +// @public +export type GetArrayType = T extends Array ? TData : never; + +// @public +export function getLongRunningPoller(client: Client, initialResponse: CreateOrUpdateWidget200Response | CreateOrUpdateWidget201Response | CreateOrUpdateWidgetDefaultResponse, options?: CreateHttpPollerOptions>): Promise, TResult>>; + +// @public (undocumented) +export function getLongRunningPoller(client: Client, initialResponse: DeleteWidget202Response | DeleteWidgetDefaultResponse, options?: CreateHttpPollerOptions>): Promise, TResult>>; + +// @public +export type GetPage = (pageLink: string, maxPageSize?: number) => Promise<{ + page: TPage; + nextPageLink?: string; +}>; + +// @public (undocumented) +export interface GetWidget { + delete(options?: DeleteWidgetParameters): StreamableMethod; + get(options?: GetWidgetParameters): StreamableMethod; + patch(options: CreateOrUpdateWidgetParameters): StreamableMethod; +} + +// @public +export interface GetWidget200Response extends HttpResponse { + // (undocumented) + body: WidgetSuiteOutput; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface GetWidgetDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface GetWidgetDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & GetWidgetDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export interface GetWidgetOperationStatus { + get(options?: GetWidgetOperationStatusParameters): StreamableMethod; +} + +// @public +export interface GetWidgetOperationStatus200Response extends HttpResponse { + // (undocumented) + body: ResourceOperationStatusOutput; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface GetWidgetOperationStatusDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface GetWidgetOperationStatusDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & GetWidgetOperationStatusDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export type GetWidgetOperationStatusParameters = RequestParameters; + +// @public (undocumented) +export type GetWidgetParameters = RequestParameters; + +// @public (undocumented) +export function isUnexpected(response: GetWidget200Response | GetWidgetDefaultResponse): response is GetWidgetDefaultResponse; + +// @public (undocumented) +export function isUnexpected(response: CreateOrUpdateWidget200Response | CreateOrUpdateWidget201Response | CreateOrUpdateWidgetLogicalResponse | CreateOrUpdateWidgetDefaultResponse): response is CreateOrUpdateWidgetDefaultResponse; + +// @public (undocumented) +export function isUnexpected(response: DeleteWidget202Response | DeleteWidgetLogicalResponse | DeleteWidgetDefaultResponse): response is DeleteWidgetDefaultResponse; + +// @public (undocumented) +export function isUnexpected(response: GetWidgetOperationStatus200Response | GetWidgetOperationStatusDefaultResponse): response is GetWidgetOperationStatusDefaultResponse; + +// @public (undocumented) +export function isUnexpected(response: ListWidgets200Response | ListWidgetsDefaultResponse): response is ListWidgetsDefaultResponse; + +// @public (undocumented) +export interface ListWidgets { + get(options?: ListWidgetsParameters): StreamableMethod; +} + +// @public +export interface ListWidgets200Response extends HttpResponse { + // (undocumented) + body: PagedWidgetSuiteOutput; + // (undocumented) + status: "200"; +} + +// @public (undocumented) +export interface ListWidgetsDefaultHeaders { + "x-ms-error-code"?: string; +} + +// @public (undocumented) +export interface ListWidgetsDefaultResponse extends HttpResponse { + // (undocumented) + body: ErrorResponse; + // (undocumented) + headers: RawHttpHeaders & ListWidgetsDefaultHeaders; + // (undocumented) + status: string; +} + +// @public (undocumented) +export type ListWidgetsParameters = RequestParameters; + +// @public +export interface OperationStatusOutput { + error?: ErrorModel; + id: string; + status: string; +} + +// @public +export type PagedWidgetSuiteOutput = Paged; + +// @public +export function paginate(client: Client, initialResponse: TResponse, options?: PagingOptions): PagedAsyncIterableIterator>; + +// @public +export type PaginateReturn = TResult extends { + body: { + value?: infer TPage; + }; +} ? GetArrayType : Array; + +// @public +export interface PagingOptions { + customGetPage?: GetPage[]>; +} + +// @public +export interface ResourceOperationStatusOutput { + error?: ErrorModel; + id: string; + result?: WidgetSuiteOutput; + status: string; +} + +// @public (undocumented) +export interface Routes { + (path: "/widgets/{widgetName}", widgetName: string): GetWidget; + (path: "/widgets/{widgetName}/operations/{operationId}", widgetName: string, operationId: string): GetWidgetOperationStatus; + (path: "/widgets"): ListWidgets; +} + +// @public (undocumented) +export type WidgetManagerClient = Client & { + path: Routes; +}; + +// @public +export interface WidgetSuite { + manufacturerId: string; + sharedModel?: FakedSharedModel; +} + +// @public +export interface WidgetSuiteOutput { + manufacturerId: string; + readonly name: string; + sharedModel?: FakedSharedModelOutput; +} + +// @public +export type WidgetSuiteResourceMergeAndPatch = Partial; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/clientDefinitions.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/clientDefinitions.ts new file mode 100644 index 000000000000..e59ebce1d220 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/clientDefinitions.ts @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + GetWidgetParameters, + CreateOrUpdateWidgetParameters, + DeleteWidgetParameters, + GetWidgetOperationStatusParameters, + ListWidgetsParameters, +} from "./parameters"; +import { + GetWidget200Response, + GetWidgetDefaultResponse, + CreateOrUpdateWidget200Response, + CreateOrUpdateWidget201Response, + CreateOrUpdateWidgetDefaultResponse, + DeleteWidget202Response, + DeleteWidgetDefaultResponse, + GetWidgetOperationStatus200Response, + GetWidgetOperationStatusDefaultResponse, + ListWidgets200Response, + ListWidgetsDefaultResponse, +} from "./responses"; +import { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface GetWidget { + /** Fetch a Widget by name. */ + get( + options?: GetWidgetParameters + ): StreamableMethod; + /** Creates or updates a Widget asynchronously. */ + patch( + options: CreateOrUpdateWidgetParameters + ): StreamableMethod< + | CreateOrUpdateWidget200Response + | CreateOrUpdateWidget201Response + | CreateOrUpdateWidgetDefaultResponse + >; + /** Delete a Widget asynchronously. */ + delete( + options?: DeleteWidgetParameters + ): StreamableMethod; +} + +export interface GetWidgetOperationStatus { + /** Gets status of a Widget operation. */ + get( + options?: GetWidgetOperationStatusParameters + ): StreamableMethod< + | GetWidgetOperationStatus200Response + | GetWidgetOperationStatusDefaultResponse + >; +} + +export interface ListWidgets { + /** List Widget resources */ + get( + options?: ListWidgetsParameters + ): StreamableMethod; +} + +export interface Routes { + /** Resource for '/widgets/\{widgetName\}' has methods for the following verbs: get, patch, delete */ + (path: "/widgets/{widgetName}", widgetName: string): GetWidget; + /** Resource for '/widgets/\{widgetName\}/operations/\{operationId\}' has methods for the following verbs: get */ + ( + path: "/widgets/{widgetName}/operations/{operationId}", + widgetName: string, + operationId: string + ): GetWidgetOperationStatus; + /** Resource for '/widgets' has methods for the following verbs: get */ + (path: "/widgets"): ListWidgets; +} + +export type WidgetManagerClient = Client & { + path: Routes; +}; diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/index.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/index.ts new file mode 100644 index 000000000000..44cc015b2bc1 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/index.ts @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import WidgetManagerClient from "./widgetManagerClient"; + +export * from "./widgetManagerClient"; +export * from "./parameters"; +export * from "./responses"; +export * from "./clientDefinitions"; +export * from "./isUnexpected"; +export * from "./models"; +export * from "./outputModels"; +export * from "./paginateHelper"; +export * from "./pollingHelper"; + +export default WidgetManagerClient; diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/isUnexpected.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/isUnexpected.ts new file mode 100644 index 000000000000..b0f68a77f5c2 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/isUnexpected.ts @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + GetWidget200Response, + GetWidgetDefaultResponse, + CreateOrUpdateWidget200Response, + CreateOrUpdateWidget201Response, + CreateOrUpdateWidgetLogicalResponse, + CreateOrUpdateWidgetDefaultResponse, + DeleteWidget202Response, + DeleteWidgetLogicalResponse, + DeleteWidgetDefaultResponse, + GetWidgetOperationStatus200Response, + GetWidgetOperationStatusDefaultResponse, + ListWidgets200Response, + ListWidgetsDefaultResponse, +} from "./responses"; + +const responseMap: Record = { + "GET /widgets/{widgetName}": ["200"], + "PATCH /widgets/{widgetName}": ["200", "201"], + "DELETE /widgets/{widgetName}": ["202"], + "GET /widgets/{widgetName}/operations/{operationId}": ["200"], + "GET /widgets": ["200"], +}; + +export function isUnexpected( + response: GetWidget200Response | GetWidgetDefaultResponse +): response is GetWidgetDefaultResponse; +export function isUnexpected( + response: + | CreateOrUpdateWidget200Response + | CreateOrUpdateWidget201Response + | CreateOrUpdateWidgetLogicalResponse + | CreateOrUpdateWidgetDefaultResponse +): response is CreateOrUpdateWidgetDefaultResponse; +export function isUnexpected( + response: + | DeleteWidget202Response + | DeleteWidgetLogicalResponse + | DeleteWidgetDefaultResponse +): response is DeleteWidgetDefaultResponse; +export function isUnexpected( + response: + | GetWidgetOperationStatus200Response + | GetWidgetOperationStatusDefaultResponse +): response is GetWidgetOperationStatusDefaultResponse; +export function isUnexpected( + response: ListWidgets200Response | ListWidgetsDefaultResponse +): response is ListWidgetsDefaultResponse; +export function isUnexpected( + response: + | GetWidget200Response + | GetWidgetDefaultResponse + | CreateOrUpdateWidget200Response + | CreateOrUpdateWidget201Response + | CreateOrUpdateWidgetLogicalResponse + | CreateOrUpdateWidgetDefaultResponse + | DeleteWidget202Response + | DeleteWidgetLogicalResponse + | DeleteWidgetDefaultResponse + | GetWidgetOperationStatus200Response + | GetWidgetOperationStatusDefaultResponse + | ListWidgets200Response + | ListWidgetsDefaultResponse +): response is + | GetWidgetDefaultResponse + | CreateOrUpdateWidgetDefaultResponse + | DeleteWidgetDefaultResponse + | GetWidgetOperationStatusDefaultResponse + | ListWidgetsDefaultResponse { + 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/contosowidgetmanager/contosowidgetmanager-rest/src/logger.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/logger.ts new file mode 100644 index 000000000000..454be08a1b87 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/logger.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("contoso-widgetmanager-rest"); diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/models.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/models.ts new file mode 100644 index 000000000000..f99d5eafc7b3 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/models.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** A widget. */ +export interface WidgetSuite { + /** The ID of the widget's manufacturer. */ + manufacturerId: string; + /** The faked shared model. */ + sharedModel?: FakedSharedModel; +} + +/** Faked shared model */ +export interface FakedSharedModel { + /** The tag. */ + tag: string; + /** The created date. */ + createdAt: Date | string; +} diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/outputModels.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/outputModels.ts new file mode 100644 index 000000000000..060f855e3097 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/outputModels.ts @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Paged } from "@azure/core-paging"; +import { ErrorModel } from "@azure-rest/core-client"; + +/** A widget. */ +export interface WidgetSuiteOutput { + /** The widget name. */ + readonly name: string; + /** The ID of the widget's manufacturer. */ + manufacturerId: string; + /** The faked shared model. */ + sharedModel?: FakedSharedModelOutput; +} + +/** Faked shared model */ +export interface FakedSharedModelOutput { + /** The tag. */ + tag: string; + /** The created date. */ + createdAt: string; +} + +/** Provides status details for long running operations. */ +export interface ResourceOperationStatusOutput { + /** The unique ID of the operation. */ + id: string; + /** + * The status of the operation + * + * Possible values: InProgress, Succeeded, Failed, Canceled + */ + status: string; + /** Error object that describes the error when status is "Failed". */ + error?: ErrorModel; + /** The result of the operation. */ + result?: WidgetSuiteOutput; +} + +/** Provides status details for long running operations. */ +export interface OperationStatusOutput { + /** The unique ID of the operation. */ + id: string; + /** + * The status of the operation + * + * Possible values: InProgress, Succeeded, Failed, Canceled + */ + status: string; + /** Error object that describes the error when status is "Failed". */ + error?: ErrorModel; +} + +/** Paged collection of WidgetSuite items */ +export type PagedWidgetSuiteOutput = Paged; diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/paginateHelper.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/paginateHelper.ts new file mode 100644 index 000000000000..1c9af35b1efd --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/paginateHelper.ts @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator, + PagedResult, +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * The type of a custom function that defines how to get a page and a link to the next one if any. + */ +export type GetPage = ( + pageLink: string, + maxPageSize?: number +) => Promise<{ + page: TPage; + nextPageLink?: string; +}>; + +/** + * Options for the paging helper + */ +export interface PagingOptions { + /** + * Custom function to extract pagination details for crating the PagedAsyncIterableIterator + */ + customGetPage?: GetPage[]>; +} + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends { + body: { value?: infer TPage }; +} + ? GetArrayType + : Array; + +/** + * Helper to paginate results from an initial response that follows the specification of Autorest `x-ms-pageable` extension + * @param client - Client to use for sending the next page requests + * @param initialResponse - Initial response containing the nextLink and current page of elements + * @param customGetPage - Optional - Function to define how to extract the page and next link to be used to paginate the results + * @returns - PagedAsyncIterableIterator to iterate the elements + */ +export function paginate( + client: Client, + initialResponse: TResponse, + options: PagingOptions = {} +): PagedAsyncIterableIterator> { + // Extract element type from initial response + type TElement = PaginateReturn; + let firstRun = true; + const itemName = "value"; + const nextLinkName = "nextLink"; + const { customGetPage } = options; + const pagedResult: PagedResult = { + firstPageLink: "", + getPage: + typeof customGetPage === "function" + ? customGetPage + : async (pageLink: string) => { + const result = firstRun + ? initialResponse + : await client.pathUnchecked(pageLink).get(); + firstRun = false; + checkPagingRequest(result); + const nextLink = getNextLink(result.body, nextLinkName); + const values = getElements(result.body, itemName); + return { + page: values, + nextPageLink: nextLink, + }; + }, + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * Gets for the value of nextLink in the body + */ +function getNextLink(body: unknown, nextLinkName?: string): string | undefined { + if (!nextLinkName) { + return undefined; + } + + const nextLink = (body as Record)[nextLinkName]; + + if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + throw new Error( + `Body Property ${nextLinkName} should be a string or undefined` + ); + } + + return nextLink; +} + +/** + * Gets the elements of the current request in the body. + */ +function getElements(body: unknown, itemName: string): T[] { + const value = (body as Record)[itemName] as T[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` + ); + } + + return value ?? []; +} + +/** + * Checks if a request failed + */ +function checkPagingRequest(response: PathUncheckedResponse): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/parameters.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/parameters.ts new file mode 100644 index 000000000000..62b94a7cf739 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/parameters.ts @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RequestParameters } from "@azure-rest/core-client"; +import { WidgetSuite } from "./models"; + +export type GetWidgetParameters = RequestParameters; +export type GetWidgetOperationStatusParameters = RequestParameters; +/** The resource instance. */ +export type WidgetSuiteResourceMergeAndPatch = Partial; + +export interface CreateOrUpdateWidgetBodyParam { + /** The resource instance. */ + body: WidgetSuiteResourceMergeAndPatch; +} + +export interface CreateOrUpdateWidgetMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type CreateOrUpdateWidgetParameters = + CreateOrUpdateWidgetMediaTypesParam & + CreateOrUpdateWidgetBodyParam & + RequestParameters; +export type DeleteWidgetParameters = RequestParameters; +export type ListWidgetsParameters = RequestParameters; diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/pollingHelper.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/pollingHelper.ts new file mode 100644 index 000000000000..6b327461a516 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/pollingHelper.ts @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Client, HttpResponse } from "@azure-rest/core-client"; +import { + CreateHttpPollerOptions, + LongRunningOperation, + LroResponse, + OperationState, + SimplePollerLike, + createHttpPoller, +} from "@azure/core-lro"; +import { + CreateOrUpdateWidget200Response, + CreateOrUpdateWidget201Response, + CreateOrUpdateWidgetDefaultResponse, + CreateOrUpdateWidgetLogicalResponse, + DeleteWidget202Response, + DeleteWidgetDefaultResponse, + DeleteWidgetLogicalResponse, +} from "./responses"; +/** + * Helper function that builds a Poller object to help polling a long running operation. + * @param client - Client to use for sending the request to get additional pages. + * @param initialResponse - The initial response. + * @param options - Options to set a resume state or custom polling interval. + * @returns - A poller object to poll for operation state updates and eventually get the final response. + */ +export async function getLongRunningPoller< + TResult extends + | CreateOrUpdateWidgetLogicalResponse + | CreateOrUpdateWidgetDefaultResponse +>( + client: Client, + initialResponse: + | CreateOrUpdateWidget200Response + | CreateOrUpdateWidget201Response + | CreateOrUpdateWidgetDefaultResponse, + options?: CreateHttpPollerOptions> +): Promise, TResult>>; +export async function getLongRunningPoller< + TResult extends DeleteWidgetLogicalResponse | DeleteWidgetDefaultResponse +>( + client: Client, + initialResponse: DeleteWidget202Response | DeleteWidgetDefaultResponse, + options?: CreateHttpPollerOptions> +): Promise, TResult>>; +export async function getLongRunningPoller( + client: Client, + initialResponse: TResult, + options: CreateHttpPollerOptions> = {} +): Promise, TResult>> { + const poller: LongRunningOperation = { + requestMethod: initialResponse.request.method, + requestPath: initialResponse.request.url, + sendInitialRequest: async () => { + // In the case of Rest Clients we are building the LRO poller object from a response that's the reason + // we are not triggering the initial request here, just extracting the information from the + // response we were provided. + return getLroResponse(initialResponse); + }, + sendPollRequest: async (path) => { + // This is the callback that is going to be called to poll the service + // to get the latest status. We use the client provided and the polling path + // which is an opaque URL provided by caller, the service sends this in one of the following headers: operation-location, azure-asyncoperation or location + // depending on the lro pattern that the service implements. If non is provided we default to the initial path. + const response = await client + .pathUnchecked(path ?? initialResponse.request.url) + .get(); + const lroResponse = getLroResponse(response as TResult); + lroResponse.rawResponse.headers["x-ms-original-url"] = + initialResponse.request.url; + return lroResponse; + }, + }; + + options.resolveOnUnsuccessful = options.resolveOnUnsuccessful ?? true; + return createHttpPoller(poller, options); +} + +/** + * Converts a Rest Client response to a response that the LRO implementation understands + * @param response - a rest client http response + * @returns - An LRO response that the LRO implementation understands + */ +function getLroResponse( + response: TResult +): LroResponse { + if (Number.isNaN(response.status)) { + throw new TypeError( + `Status code of the response is not a number. Value: ${response.status}` + ); + } + + return { + flatResponse: response, + rawResponse: { + ...response, + statusCode: Number.parseInt(response.status), + body: response.body, + }, + }; +} diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/responses.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/responses.ts new file mode 100644 index 000000000000..10f8926719d1 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/responses.ts @@ -0,0 +1,132 @@ +// 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 { + WidgetSuiteOutput, + ResourceOperationStatusOutput, + OperationStatusOutput, + PagedWidgetSuiteOutput, +} from "./outputModels"; + +/** The request has succeeded. */ +export interface GetWidget200Response extends HttpResponse { + status: "200"; + body: WidgetSuiteOutput; +} + +export interface GetWidgetDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetWidgetDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetWidgetDefaultHeaders; +} + +/** The request has succeeded. */ +export interface GetWidgetOperationStatus200Response extends HttpResponse { + status: "200"; + body: ResourceOperationStatusOutput; +} + +export interface GetWidgetOperationStatusDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetWidgetOperationStatusDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetWidgetOperationStatusDefaultHeaders; +} + +export interface CreateOrUpdateWidget200Headers { + /** The location for monitoring the operation state. */ + "operation-location": string; +} + +/** The request has succeeded. */ +export interface CreateOrUpdateWidget200Response extends HttpResponse { + status: "200"; + body: WidgetSuiteOutput; + headers: RawHttpHeaders & CreateOrUpdateWidget200Headers; +} + +export interface CreateOrUpdateWidget201Headers { + /** The location for monitoring the operation state. */ + "operation-location": string; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface CreateOrUpdateWidget201Response extends HttpResponse { + status: "201"; + body: WidgetSuiteOutput; + headers: RawHttpHeaders & CreateOrUpdateWidget201Headers; +} + +export interface CreateOrUpdateWidgetDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface CreateOrUpdateWidgetDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & CreateOrUpdateWidgetDefaultHeaders; +} + +/** The final response for long-running createOrUpdateWidget operation */ +export interface CreateOrUpdateWidgetLogicalResponse extends HttpResponse { + status: "200"; + body: WidgetSuiteOutput; +} + +export interface DeleteWidget202Headers { + /** The location for monitoring the operation state. */ + "operation-location": string; +} + +/** The request has been accepted for processing, but processing has not yet completed. */ +export interface DeleteWidget202Response extends HttpResponse { + status: "202"; + body: OperationStatusOutput; + headers: RawHttpHeaders & DeleteWidget202Headers; +} + +export interface DeleteWidgetDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface DeleteWidgetDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & DeleteWidgetDefaultHeaders; +} + +/** The final response for long-running deleteWidget operation */ +export interface DeleteWidgetLogicalResponse extends HttpResponse { + status: "200"; + body: OperationStatusOutput; +} + +/** The request has succeeded. */ +export interface ListWidgets200Response extends HttpResponse { + status: "200"; + body: PagedWidgetSuiteOutput; +} + +export interface ListWidgetsDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface ListWidgetsDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & ListWidgetsDefaultHeaders; +} diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/widgetManagerClient.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/widgetManagerClient.ts new file mode 100644 index 000000000000..86568c9fae0c --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/src/widgetManagerClient.ts @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "./logger"; +import { TokenCredential } from "@azure/core-auth"; +import { WidgetManagerClient } from "./clientDefinitions"; + +/** + * Initialize a new instance of `WidgetManagerClient` + * @param endpoint - The parameter endpoint + * @param credentials - uniquely identify client credential + * @param options - the parameter for all optional parameters + */ +export default function createClient( + endpoint: string, + credentials: TokenCredential, + options: ClientOptions = {} +): WidgetManagerClient { + const baseUrl = options.baseUrl ?? `${endpoint}`; + options.apiVersion = options.apiVersion ?? "2022-11-01-preview"; + const userAgentInfo = `azsdk-js-contoso-widgetmanager-rest/1.0.0-beta.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + credentials: { + scopes: options.credentials?.scopes ?? [ + "https://contoso.azure.com/.default", + ], + }, + }; + + const client = getClient( + baseUrl, + credentials, + options + ) as WidgetManagerClient; + + return client; +} diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/sampleTest.spec.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/sampleTest.spec.ts new file mode 100644 index 000000000000..bce68e428645 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/sampleTest.spec.ts @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Recorder } from "@azure-tools/test-recorder"; +import { assert } from "chai"; +import { createRecorder } from "./utils/recordedClient"; +import { Context } from "mocha"; + +describe("My test", () => { + let recorder: Recorder; + + beforeEach(async function (this: Context) { + recorder = await createRecorder(this); + }); + + afterEach(async function () { + await recorder.stop(); + }); + + it("sample test", async function () { + assert.equal(1, 1); + }); +}); diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/utils/env.browser.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/utils/env.browser.ts new file mode 100644 index 000000000000..fd2aca680c7b --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/utils/env.browser.ts @@ -0,0 +1,2 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/utils/env.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/utils/env.ts new file mode 100644 index 000000000000..0e06855b73ae --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/utils/env.ts @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import * as dotenv from "dotenv"; + +dotenv.config(); diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/utils/recordedClient.ts b/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/utils/recordedClient.ts new file mode 100644 index 000000000000..6cc58bc15e11 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/test/public/utils/recordedClient.ts @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Context } from "mocha"; +import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import "./env"; + +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", + SUBSCRIPTION_ID: "azure_subscription_id", +}; + +const recorderEnvSetup: RecorderStartOptions = { + envSetupForPlayback, +}; + +/** + * creates the recorder and reads the environment variables from the `.env` file. + * 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: Context): Promise { + const recorder = new Recorder(context.currentTest); + await recorder.start(recorderEnvSetup); + return recorder; +} diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/tsconfig.json b/sdk/contosowidgetmanager/contosowidgetmanager-rest/tsconfig.json new file mode 100644 index 000000000000..d5bf593423c9 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.package", + "compilerOptions": { + "outDir": "./dist-esm", + "declarationDir": "./types" + }, + "include": [ + "src/**/*.ts", + "./test/**/*.ts" + ] +} \ No newline at end of file diff --git a/sdk/contosowidgetmanager/contosowidgetmanager-rest/tsp-location.yaml b/sdk/contosowidgetmanager/contosowidgetmanager-rest/tsp-location.yaml new file mode 100644 index 000000000000..a06ccfe8c893 --- /dev/null +++ b/sdk/contosowidgetmanager/contosowidgetmanager-rest/tsp-location.yaml @@ -0,0 +1,6 @@ +additionalDirectories: +- specification/contosowidgetmanager/Contoso.WidgetManager.Shared/ +repo: Azure/azure-rest-api-specs +commit: ee06a0a4c146d3bc4b2aa3fc93d612d8cbc9bbd4 +directory: specification/contosowidgetmanager/Contoso.WidgetManager +