ZiWei Chen 2024-08-01 10:48:02 +08:00 коммит произвёл GitHub
Родитель ea4c874241
Коммит d166c6983c
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
49 изменённых файлов: 16787 добавлений и 8 удалений

Просмотреть файл

@ -185,6 +185,9 @@ dependencies:
'@rush-temp/arm-compute-profile-2020-09-01-hybrid':
specifier: file:./projects/arm-compute-profile-2020-09-01-hybrid.tgz
version: file:projects/arm-compute-profile-2020-09-01-hybrid.tgz
'@rush-temp/arm-computefleet':
specifier: file:./projects/arm-computefleet.tgz
version: file:projects/arm-computefleet.tgz
'@rush-temp/arm-confidentialledger':
specifier: file:./projects/arm-confidentialledger.tgz
version: file:projects/arm-confidentialledger.tgz
@ -3477,7 +3480,7 @@ packages:
resolution: {integrity: sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==}
dependencies:
'@types/connect': 3.4.38
'@types/node': 18.19.42
'@types/node': 22.0.2
dev: false
/@types/bunyan@1.8.9:
@ -3505,7 +3508,7 @@ packages:
/@types/connect@3.4.38:
resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==}
dependencies:
'@types/node': 18.19.42
'@types/node': 22.0.2
dev: false
/@types/cookie@0.4.1:
@ -3519,7 +3522,7 @@ packages:
/@types/cors@2.8.17:
resolution: {integrity: sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==}
dependencies:
'@types/node': 18.19.42
'@types/node': 22.0.2
dev: false
/@types/debug@4.1.12:
@ -3629,7 +3632,7 @@ packages:
/@types/jsonfile@6.1.4:
resolution: {integrity: sha512-D5qGUYwjvnNNextdU59/+fI+spnwtTFmyQP0h+PfIOSkNfpU6AOICUOkm4i0OnSk+NyjdPJrxCDro0sJsWlRpQ==}
dependencies:
'@types/node': 18.19.42
'@types/node': 22.0.2
dev: false
/@types/jsonwebtoken@9.0.6:
@ -3755,7 +3758,7 @@ packages:
/@types/readdir-glob@1.1.5:
resolution: {integrity: sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg==}
dependencies:
'@types/node': 18.19.42
'@types/node': 22.0.2
dev: false
/@types/resolve@1.20.2:
@ -3781,7 +3784,7 @@ packages:
resolution: {integrity: sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==}
dependencies:
'@types/http-errors': 2.0.4
'@types/node': 18.19.42
'@types/node': 22.0.2
'@types/send': 0.17.4
dev: false
@ -3875,7 +3878,7 @@ packages:
resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==}
requiresBuild: true
dependencies:
'@types/node': 18.19.42
'@types/node': 22.0.2
dev: false
optional: true
@ -5805,7 +5808,7 @@ packages:
dependencies:
'@types/cookie': 0.4.1
'@types/cors': 2.8.17
'@types/node': 18.19.42
'@types/node': 22.0.2
accepts: 1.3.8
base64id: 2.0.0
cookie: 0.4.2
@ -13935,6 +13938,42 @@ packages:
- utf-8-validate
dev: false
file:projects/arm-computefleet.tgz:
resolution: {integrity: sha512-gmJQjY5CbvJG5u5rNr14RoC8D2ZIntCSD63pFVcPdvQrQUMZMfTWgfd47GsFgkDwDUMzPknwbcF+neX5D3xqQg==, tarball: file:projects/arm-computefleet.tgz}
name: '@rush-temp/arm-computefleet'
version: 0.0.0
dependencies:
'@azure/identity': 4.4.1
'@microsoft/api-extractor': 7.47.4(@types/node@18.19.42)
'@types/node': 18.19.42
'@vitest/browser': 1.6.0(playwright@1.45.3)(vitest@1.6.0)
'@vitest/coverage-istanbul': 1.6.0(vitest@1.6.0)
dotenv: 16.4.5
eslint: 8.57.0
mkdirp: 3.0.1
playwright: 1.45.3
prettier: 3.3.3
rimraf: 5.0.10
tshy: 1.18.0
tslib: 2.6.3
typescript: 5.5.4
vitest: 1.6.0(@types/node@18.19.42)(@vitest/browser@1.6.0)
transitivePeerDependencies:
- '@edge-runtime/vm'
- '@vitest/ui'
- happy-dom
- jsdom
- less
- lightningcss
- safaridriver
- sass
- stylus
- sugarss
- supports-color
- terser
- webdriverio
dev: false
file:projects/arm-confidentialledger.tgz:
resolution: {integrity: sha512-YiL8AaxkgP74LPtjxpFac4G/4jAgT7mRzogI1ZWf6QNoL+6itqxDjOLs7gUsdvY4rNeADrnbt3xu775GPTWZxw==, tarball: file:projects/arm-confidentialledger.tgz}
name: '@rush-temp/arm-confidentialledger'

Просмотреть файл

@ -4,3 +4,4 @@ https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/storage/storage-blob-cha
https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/storage/storage-blob-changefeed/samples/typescript
https://docs.microsoft.com/javascript/api/@azure/arm-servicefabricmanagedclusters?view=azure-node-preview
https://docs.microsoft.com/javascript/api/@azure/arm-redhatopenshift?view=azure-node-preview
https://docs.microsoft.com/javascript/api/@azure/arm-computefleet?view=azure-node-preview

Просмотреть файл

@ -2232,6 +2232,11 @@
"projectFolder": "sdk/ai/ai-inference-rest",
"versionPolicyName": "client"
},
{
"packageName": "@azure/arm-computefleet",
"projectFolder": "sdk/computefleet/arm-computefleet",
"versionPolicyName": "client"
},
{
"packageName": "@azure/arm-edgezones",
"projectFolder": "sdk/edgezones/arm-edgezones",

Просмотреть файл

@ -0,0 +1,14 @@
{
"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",
"@azure/azure-sdk/ts-package-json-module": "off",
"@azure/azure-sdk/ts-package-json-files-required": "off",
"@azure/azure-sdk/ts-package-json-main-is-cjs": "off"
}
}

Просмотреть файл

@ -0,0 +1,7 @@
# Release History
## 1.0.0-beta.1 (2024-07-22)
### Features Added
Initial release of the Azure Compute Fleet package

Просмотреть файл

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2024 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Просмотреть файл

@ -0,0 +1,101 @@
# AzureFleet client library for JavaScript
This package contains an isomorphic SDK (runs both in Node.js and in browsers) for AzureFleet client.
Azure Fleet Service
[Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/computefleet/arm-computefleet) |
[Package (NPM)](https://www.npmjs.com/package/@azure/arm-computefleet) |
[API reference documentation](https://docs.microsoft.com/javascript/api/@azure/arm-computefleet?view=azure-node-preview) |
## Getting started
### Currently supported environments
- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule)
- Latest versions of Safari, Chrome, Edge and Firefox.
See our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details.
### Prerequisites
- An [Azure subscription][azure_sub].
### Install the `@azure/arm-computefleet` package
Install the AzureFleet client library for JavaScript with `npm`:
```bash
npm install @azure/arm-computefleet
```
### Create and authenticate a `AzureFleetClient`
To create a client object to access the AzureFleet API, you will need the `endpoint` of your AzureFleet resource and a `credential`. The AzureFleet client can use Azure Active Directory credentials to authenticate.
You can find the endpoint for your AzureFleet resource in the [Azure Portal][azure_portal].
You can authenticate with Azure Active Directory using a credential from the [@azure/identity][azure_identity] library or [an existing AAD Token](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-a-pre-fetched-access-token).
To use the [DefaultAzureCredential][defaultazurecredential] provider shown below, or other credential providers provided with the Azure SDK, please install the `@azure/identity` package:
```bash
npm install @azure/identity
```
You will also need to **register a new AAD application and grant access to AzureFleet** by assigning the suitable role to your service principal (note: roles such as `"Owner"` will not grant the necessary permissions).
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`.
For more information about how to create an Azure AD Application check out [this guide](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).
```javascript
const { AzureFleetClient } = require("@azure/arm-computefleet");
const { DefaultAzureCredential } = require("@azure/identity");
// For client-side applications running in the browser, use InteractiveBrowserCredential instead of DefaultAzureCredential. See https://aka.ms/azsdk/js/identity/examples for more details.
const subscriptionId = "00000000-0000-0000-0000-000000000000";
const client = new AzureFleetClient(new DefaultAzureCredential(), subscriptionId);
// For client-side applications running in the browser, use this code instead:
// const credential = new InteractiveBrowserCredential({
// tenantId: "<YOUR_TENANT_ID>",
// clientId: "<YOUR_CLIENT_ID>"
// });
// const client = new AzureFleetClient(credential, subscriptionId);
```
### JavaScript Bundle
To use this client library in the browser, first you need to use a bundler. For details on how to do this, please refer to our [bundling documentation](https://aka.ms/AzureSDKBundling).
## Key concepts
### AzureFleetClient
`AzureFleetClient` is the primary interface for developers using the AzureFleet client library. Explore the methods on this client object to understand the different features of the AzureFleet service that you can access.
## 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).
## Contributing
If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code.
## Related projects
- [Microsoft Azure SDK for JavaScript](https://github.com/Azure/azure-sdk-for-js)
[azure_sub]: https://azure.microsoft.com/free/
[azure_portal]: https://portal.azure.com
[azure_identity]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity
[defaultazurecredential]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential

Просмотреть файл

@ -0,0 +1,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
"mainEntryPointFilePath": "./dist/esm/index.d.ts",
"docModel": { "enabled": true },
"apiReport": { "enabled": true, "reportFolder": "./review" },
"dtsRollup": {
"enabled": true,
"untrimmedFilePath": "",
"publicTrimmedFilePath": "./types/arm-computefleet.d.ts"
},
"messages": {
"tsdocMessageReporting": { "default": { "logLevel": "none" } },
"extractorMessageReporting": {
"ae-missing-release-tag": { "logLevel": "none" },
"ae-unresolved-link": { "logLevel": "none" }
}
}
}

Просмотреть файл

@ -0,0 +1,6 @@
{
"AssetsRepo": "Azure/azure-sdk-assets",
"AssetsRepoPrefixPath": "js",
"TagPrefix": "js/computefleet/arm-computefleet",
"Tag": "js/computefleet/arm-computefleet_e84d79a3e6"
}

Просмотреть файл

@ -0,0 +1,187 @@
{
"name": "@azure/arm-computefleet",
"version": "1.0.0-beta.1",
"description": "Azure Fleet Service",
"engines": {
"node": ">=18.0.0"
},
"sideEffects": false,
"autoPublish": false,
"tshy": {
"exports": {
"./package.json": "./package.json",
".": "./src/index.ts",
"./api": "./src/api/index.ts",
"./models": "./src/models/index.ts"
},
"dialects": [
"esm",
"commonjs"
],
"esmDialects": [
"browser",
"react-native"
],
"selfLink": false
},
"type": "module",
"keywords": [
"node",
"azure",
"cloud",
"typescript",
"browser",
"isomorphic"
],
"author": "Microsoft Corporation",
"license": "MIT",
"files": [
"dist",
"README.md",
"LICENSE",
"review/*",
"CHANGELOG.md"
],
"sdk-type": "mgmt",
"repository": "github:Azure/azure-sdk-for-js",
"bugs": {
"url": "https://github.com/Azure/azure-sdk-for-js/issues"
},
"prettier": "@azure/eslint-plugin-azure-sdk/prettier.json",
"//metadata": {
"constantPaths": [
{
"path": "src/rest/azureFleetClient.ts",
"prefix": "userAgentInfo"
}
]
},
"dependencies": {
"@azure-rest/core-client": "^2.1.0",
"@azure/core-auth": "^1.6.0",
"@azure/core-rest-pipeline": "^1.5.0",
"@azure/logger": "^1.0.0",
"tslib": "^2.6.2",
"@azure/core-lro": "^3.0.0",
"@azure/abort-controller": "^2.1.2",
"@azure/core-paging": "^1.5.0"
},
"devDependencies": {
"dotenv": "^16.0.0",
"@microsoft/api-extractor": "^7.40.3",
"@types/node": "^18.0.0",
"eslint": "^8.55.0",
"prettier": "^3.2.5",
"rimraf": "^5.0.5",
"mkdirp": "^3.0.1",
"typescript": "~5.5.3",
"tshy": "^1.11.1",
"@azure/core-util": "^1.0.0",
"@azure/identity": "^4.2.1",
"@vitest/browser": "^1.3.1",
"@vitest/coverage-istanbul": "^1.3.1",
"playwright": "^1.41.2",
"vitest": "^1.3.1",
"@azure-tools/test-credential": "^2.0.0",
"@azure-tools/test-recorder": "^4.0.0",
"@azure/dev-tool": "^1.0.0",
"@azure/eslint-plugin-azure-sdk": "^3.0.0"
},
"scripts": {
"clean": "rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz *.log",
"extract-api": "rimraf review && mkdirp ./review && dev-tool run extract-api",
"pack": "npm pack 2>&1",
"lint": "echo skipped",
"lint:fix": "echo skipped",
"unit-test": "npm run unit-test:node && npm run unit-test:browser",
"unit-test:browser": "npm run build:test && dev-tool run test:vitest --browser",
"unit-test:node": "dev-tool run test:vitest",
"integration-test": "npm run integration-test:node && npm run integration-test:browser",
"integration-test:browser": "echo skipped",
"integration-test:node": "echo skipped",
"audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit",
"build:samples": "echo skipped",
"check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\"",
"execute:samples": "echo skipped",
"format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\"",
"generate:client": "echo skipped",
"test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser",
"minify": "uglifyjs -c -m --comments --source-map \"content='./dist/index.js.map'\" -o ./dist/index.min.js ./dist/index.js",
"build:test": "npm run clean && tshy && dev-tool run build-test",
"build": "npm run clean && tshy && mkdirp ./review && dev-tool run extract-api",
"test:node": "npm run clean && tshy && npm run unit-test:node && npm run integration-test:node",
"test": "npm run clean && tshy && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test"
},
"exports": {
"./package.json": "./package.json",
".": {
"browser": {
"source": "./src/index.ts",
"types": "./dist/browser/index.d.ts",
"default": "./dist/browser/index.js"
},
"react-native": {
"source": "./src/index.ts",
"types": "./dist/react-native/index.d.ts",
"default": "./dist/react-native/index.js"
},
"import": {
"source": "./src/index.ts",
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"source": "./src/index.ts",
"types": "./dist/commonjs/index.d.ts",
"default": "./dist/commonjs/index.js"
}
},
"./api": {
"browser": {
"source": "./src/api/index.ts",
"types": "./dist/browser/api/index.d.ts",
"default": "./dist/browser/api/index.js"
},
"react-native": {
"source": "./src/api/index.ts",
"types": "./dist/react-native/api/index.d.ts",
"default": "./dist/react-native/api/index.js"
},
"import": {
"source": "./src/api/index.ts",
"types": "./dist/esm/api/index.d.ts",
"default": "./dist/esm/api/index.js"
},
"require": {
"source": "./src/api/index.ts",
"types": "./dist/commonjs/api/index.d.ts",
"default": "./dist/commonjs/api/index.js"
}
},
"./models": {
"browser": {
"source": "./src/models/index.ts",
"types": "./dist/browser/models/index.d.ts",
"default": "./dist/browser/models/index.js"
},
"react-native": {
"source": "./src/models/index.ts",
"types": "./dist/react-native/models/index.d.ts",
"default": "./dist/react-native/models/index.js"
},
"import": {
"source": "./src/models/index.ts",
"types": "./dist/esm/models/index.d.ts",
"default": "./dist/esm/models/index.js"
},
"require": {
"source": "./src/models/index.ts",
"types": "./dist/commonjs/models/index.d.ts",
"default": "./dist/commonjs/models/index.js"
}
}
},
"main": "./dist/commonjs/index.js",
"types": "./dist/commonjs/index.d.ts",
"module": "./dist/esm/index.js"
}

Просмотреть файл

@ -0,0 +1,58 @@
## API Report File for "@azure/arm-computefleet"
> 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 { HttpResponse } from '@azure-rest/core-client';
import { OperationOptions } from '@azure-rest/core-client';
import { OperationState } from '@azure/core-lro';
import { Paged } from '@azure/core-paging';
import { PollerLike } from '@azure/core-lro';
import { RawHttpHeaders } from '@azure/core-rest-pipeline';
import { RequestParameters } from '@azure-rest/core-client';
import { StreamableMethod } from '@azure-rest/core-client';
import { TokenCredential } from '@azure/core-auth';
// @public
export interface AzureFleetClientOptionalParams extends ClientOptions {
apiVersion?: string;
}
// @public (undocumented)
export type AzureFleetContext = Client & {
path: Routes;
};
// @public (undocumented)
export function createAzureFleet(credential: TokenCredential, options?: AzureFleetClientOptionalParams): AzureFleetContext;
// @public
export function fleetsCreateOrUpdate(context: AzureFleetContext, subscriptionId: string, resourceGroupName: string, fleetName: string, resource: Fleet_2, options?: FleetsCreateOrUpdateOptionalParams): PollerLike<OperationState<Fleet_2>, Fleet_2>;
// @public
export function fleetsDelete(context: AzureFleetContext, subscriptionId: string, resourceGroupName: string, fleetName: string, options?: FleetsDeleteOptionalParams): PollerLike<OperationState<void>, void>;
// @public
export function fleetsGet(context: AzureFleetContext, subscriptionId: string, resourceGroupName: string, fleetName: string, options?: FleetsGetOptionalParams): Promise<Fleet_2>;
// @public
export function fleetsListByResourceGroup(context: AzureFleetContext, subscriptionId: string, resourceGroupName: string, options?: FleetsListByResourceGroupOptionalParams): PagedAsyncIterableIterator<Fleet_2>;
// @public
export function fleetsListBySubscription(context: AzureFleetContext, subscriptionId: string, options?: FleetsListBySubscriptionOptionalParams): PagedAsyncIterableIterator<Fleet_2>;
// @public
export function fleetsListVirtualMachineScaleSets(context: AzureFleetContext, subscriptionId: string, resourceGroupName: string, name: string, options?: FleetsListVirtualMachineScaleSetsOptionalParams): PagedAsyncIterableIterator<VirtualMachineScaleSet>;
// @public
export function fleetsUpdate(context: AzureFleetContext, subscriptionId: string, resourceGroupName: string, fleetName: string, properties: FleetUpdate_2, options?: FleetsUpdateOptionalParams): PollerLike<OperationState<Fleet_2>, Fleet_2>;
// @public
export function operationsList(context: AzureFleetContext, options?: OperationsListOptionalParams): PagedAsyncIterableIterator<Operation>;
// (No @packageDocumentation comment for this package)
```

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,29 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { TokenCredential } from "@azure/core-auth";
import { ClientOptions } from "@azure-rest/core-client";
import { AzureFleetContext } from "../rest/index.js";
import getClient from "../rest/index.js";
/** Optional parameters for the client. */
export interface AzureFleetClientOptionalParams extends ClientOptions {
/** The API version to use for this operation. */
apiVersion?: string;
}
export { AzureFleetContext } from "../rest/index.js";
export function createAzureFleet(
credential: TokenCredential,
options: AzureFleetClientOptionalParams = {},
): AzureFleetContext {
const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix;
const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-api` : "azsdk-js-api";
const clientContext = getClient(credential, {
...options,
userAgentOptions: { userAgentPrefix },
});
return clientContext;
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,18 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export {
createAzureFleet,
AzureFleetClientOptionalParams,
AzureFleetContext,
} from "./azureFleetContext.js";
export {
fleetsGet,
fleetsCreateOrUpdate,
fleetsUpdate,
fleetsDelete,
fleetsListByResourceGroup,
fleetsListBySubscription,
fleetsListVirtualMachineScaleSets,
} from "./fleets/index.js";
export { operationsList } from "./operations/index.js";

Просмотреть файл

@ -0,0 +1,68 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { Operation, _OperationListResult } from "../../models/models.js";
import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js";
import { buildPagedAsyncIterator } from "../pagingHelpers.js";
import {
isUnexpected,
AzureFleetContext as Client,
OperationsList200Response,
OperationsListDefaultResponse,
} from "../../rest/index.js";
import {
StreamableMethod,
operationOptionsToRequestParameters,
createRestError,
} from "@azure-rest/core-client";
import { OperationsListOptionalParams } from "../../models/options.js";
export function _operationsListSend(
context: Client,
options: OperationsListOptionalParams = { requestOptions: {} },
): StreamableMethod<OperationsList200Response | OperationsListDefaultResponse> {
return context
.path("/providers/Microsoft.AzureFleet/operations")
.get({ ...operationOptionsToRequestParameters(options) });
}
export async function _operationsListDeserialize(
result: OperationsList200Response | OperationsListDefaultResponse,
): Promise<_OperationListResult> {
if (isUnexpected(result)) {
throw createRestError(result);
}
return {
value: result.body["value"].map((p) => {
return {
name: p["name"],
isDataAction: p["isDataAction"],
display: !p.display
? undefined
: {
provider: p.display?.["provider"],
resource: p.display?.["resource"],
operation: p.display?.["operation"],
description: p.display?.["description"],
},
origin: p["origin"],
actionType: p["actionType"],
};
}),
nextLink: result.body["nextLink"],
};
}
/** List the operations for the provider */
export function operationsList(
context: Client,
options: OperationsListOptionalParams = { requestOptions: {} },
): PagedAsyncIterableIterator<Operation> {
return buildPagedAsyncIterator(
context,
() => _operationsListSend(context, options),
_operationsListDeserialize,
{ itemName: "value", nextLinkName: "nextLink" },
);
}

Просмотреть файл

@ -0,0 +1,171 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { Client, createRestError, PathUncheckedResponse } from "@azure-rest/core-client";
import { RestError } from "@azure/core-rest-pipeline";
import {
BuildPagedAsyncIteratorOptions,
ContinuablePage,
PageSettings,
PagedAsyncIterableIterator,
PagedResult,
} from "../models/pagingTypes.js";
import { isUnexpected } from "../rest/index.js";
/**
* Helper to paginate results in a generic way and return a PagedAsyncIterableIterator
*/
export function buildPagedAsyncIterator<
TElement,
TPage = TElement[],
TPageSettings extends PageSettings = PageSettings,
TResponse extends PathUncheckedResponse = PathUncheckedResponse,
>(
client: Client,
getInitialResponse: () => PromiseLike<TResponse>,
processResponseBody: (result: TResponse) => PromiseLike<unknown>,
options: BuildPagedAsyncIteratorOptions = {},
): PagedAsyncIterableIterator<TElement, TPage, TPageSettings> {
const itemName = options.itemName ?? "value";
const nextLinkName = options.nextLinkName ?? "nextLink";
const pagedResult: PagedResult<TElement, TPage, TPageSettings> = {
getPage: async (pageLink?: string) => {
const result =
pageLink === undefined
? await getInitialResponse()
: await client.pathUnchecked(pageLink).get();
checkPagingRequest(result);
const results = await processResponseBody(result as TResponse);
const nextLink = getNextLink(results, nextLinkName);
const values = getElements<TElement>(results, itemName) as TPage;
return {
page: values,
nextPageLink: nextLink,
};
},
byPage: (settings?: TPageSettings) => {
const { continuationToken } = settings ?? {};
return getPageAsyncIterator(pagedResult, {
pageLink: continuationToken,
});
},
};
return getPagedAsyncIterator(pagedResult);
}
/**
* 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 extends PageSettings = PageSettings,
>(
pagedResult: PagedResult<TElement, TPage, TPageSettings>,
): PagedAsyncIterableIterator<TElement, TPage, TPageSettings> {
const iter = getItemAsyncIterator<TElement, TPage, TPageSettings>(pagedResult);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage:
pagedResult?.byPage ??
((settings?: TPageSettings) => {
const { continuationToken } = settings ?? {};
return getPageAsyncIterator(pagedResult, {
pageLink: continuationToken,
});
}),
};
}
async function* getItemAsyncIterator<TElement, TPage, TPageSettings extends PageSettings>(
pagedResult: PagedResult<TElement, TPage, TPageSettings>,
): AsyncIterableIterator<TElement> {
const pages = getPageAsyncIterator(pagedResult);
for await (const page of pages) {
yield* page as unknown as TElement[];
}
}
async function* getPageAsyncIterator<TElement, TPage, TPageSettings extends PageSettings>(
pagedResult: PagedResult<TElement, TPage, TPageSettings>,
options: {
pageLink?: string;
} = {},
): AsyncIterableIterator<ContinuablePage<TElement, TPage>> {
const { pageLink } = options;
let response = await pagedResult.getPage(pageLink ?? pagedResult.firstPageLink);
if (!response) {
return;
}
let result = response.page as ContinuablePage<TElement, TPage>;
result.continuationToken = response.nextPageLink;
yield result;
while (response.nextPageLink) {
response = await pagedResult.getPage(response.nextPageLink);
if (!response) {
return;
}
result = response.page as ContinuablePage<TElement, TPage>;
result.continuationToken = response.nextPageLink;
yield result;
}
}
/**
* 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<string, unknown>)[nextLinkName];
if (typeof nextLink !== "string" && typeof nextLink !== "undefined" && nextLink !== null) {
throw new RestError(
`Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}`,
);
}
if (nextLink === null) {
return undefined;
}
return nextLink;
}
/**
* Gets the elements of the current request in the body.
*/
function getElements<T = unknown>(body: unknown, itemName: string): T[] {
const value = (body as Record<string, unknown>)[itemName] as T[];
if (!Array.isArray(value)) {
throw new RestError(
`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 {
if (isUnexpected(response)) {
throw createRestError(
`Pagination failed with unexpected statusCode ${response.status}`,
response,
);
}
}

Просмотреть файл

@ -0,0 +1,128 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
PollerLike,
OperationState,
ResourceLocationConfig,
RunningOperation,
createHttpPoller,
OperationResponse,
} from "@azure/core-lro";
import { Client, PathUncheckedResponse, createRestError } from "@azure-rest/core-client";
import { AbortSignalLike } from "@azure/abort-controller";
import { isUnexpected } from "../rest/index.js";
export interface GetLongRunningPollerOptions<TResponse> {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/**
* The signal which can be used to abort requests.
*/
abortSignal?: AbortSignalLike;
/**
* The potential location of the result of the LRO if specified by the LRO extension in the swagger.
*/
resourceLocationConfig?: ResourceLocationConfig;
/**
* The original url of the LRO
* Should not be null when restoreFrom is set
*/
initialRequestUrl?: string;
/**
* A serialized poller which can be used to resume an existing paused Long-Running-Operation.
*/
restoreFrom?: string;
/**
* The function to get the initial response
*/
getInitialResponse?: () => PromiseLike<TResponse>;
}
export function getLongRunningPoller<TResponse extends PathUncheckedResponse, TResult = void>(
client: Client,
processResponseBody: (result: TResponse) => Promise<TResult>,
options: GetLongRunningPollerOptions<TResponse>,
): PollerLike<OperationState<TResult>, TResult> {
const { restoreFrom, getInitialResponse } = options;
if (!restoreFrom && !getInitialResponse) {
throw new Error("Either restoreFrom or getInitialResponse must be specified");
}
let initialResponse: TResponse | undefined = undefined;
const pollAbortController = new AbortController();
const poller: RunningOperation<TResponse> = {
sendInitialRequest: async () => {
if (!getInitialResponse) {
throw new Error("getInitialResponse is required when initializing a new poller");
}
initialResponse = await getInitialResponse();
return getLroResponse(initialResponse);
},
sendPollRequest: async (
path: string,
pollOptions?: {
abortSignal?: AbortSignalLike;
},
) => {
// The poll request would both listen to the user provided abort signal and the poller's own abort signal
function abortListener(): void {
pollAbortController.abort();
}
const abortSignal = pollAbortController.signal;
if (options.abortSignal?.aborted) {
pollAbortController.abort();
} else if (pollOptions?.abortSignal?.aborted) {
pollAbortController.abort();
} else if (!abortSignal.aborted) {
options.abortSignal?.addEventListener("abort", abortListener, {
once: true,
});
pollOptions?.abortSignal?.addEventListener("abort", abortListener, {
once: true,
});
}
let response;
try {
response = await client.pathUnchecked(path).get({ abortSignal });
} finally {
options.abortSignal?.removeEventListener("abort", abortListener);
pollOptions?.abortSignal?.removeEventListener("abort", abortListener);
}
if (options.initialRequestUrl || initialResponse) {
response.headers["x-ms-original-url"] =
options.initialRequestUrl ?? initialResponse!.request.url;
}
return getLroResponse(response as TResponse);
},
};
return createHttpPoller(poller, {
intervalInMs: options?.updateIntervalInMs,
resourceLocationConfig: options?.resourceLocationConfig,
restoreFrom: options?.restoreFrom,
processResult: (result: unknown) => {
return processResponseBody(result as TResponse);
},
});
}
/**
* Converts a Rest Client response to a response that the LRO implementation understands
* @param response - a rest client http response
* @param deserializeFn - deserialize function to convert Rest response to modular output
* @returns - An LRO response that the LRO implementation understands
*/
function getLroResponse<TResponse extends PathUncheckedResponse>(
response: TResponse,
): OperationResponse<TResponse> {
if (isUnexpected(response as PathUncheckedResponse)) {
throw createRestError(response);
}
return {
flatResponse: response,
rawResponse: {
...response,
statusCode: Number.parseInt(response.status),
body: response.body,
},
};
}

Просмотреть файл

@ -0,0 +1,44 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { TokenCredential } from "@azure/core-auth";
import { Pipeline } from "@azure/core-rest-pipeline";
import { getOperationsOperations, OperationsOperations } from "./classic/operations/index.js";
import { getFleetsOperations, FleetsOperations } from "./classic/fleets/index.js";
import {
createAzureFleet,
AzureFleetClientOptionalParams,
AzureFleetContext,
} from "./api/index.js";
export { AzureFleetClientOptionalParams } from "./api/azureFleetContext.js";
export class AzureFleetClient {
private _client: AzureFleetContext;
/** The pipeline used by this client to make requests */
public readonly pipeline: Pipeline;
constructor(
credential: TokenCredential,
subscriptionId: string,
options: AzureFleetClientOptionalParams = {},
) {
const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix;
const userAgentPrefix = prefixFromOptions
? `${prefixFromOptions} azsdk-js-client`
: "azsdk-js-client";
this._client = createAzureFleet(credential, {
...options,
userAgentOptions: { userAgentPrefix },
});
this.pipeline = this._client.pipeline;
this.operations = getOperationsOperations(this._client);
this.fleets = getFleetsOperations(this._client, subscriptionId);
}
/** The operation groups for Operations */
public readonly operations: OperationsOperations;
/** The operation groups for Fleets */
public readonly fleets: FleetsOperations;
}

Просмотреть файл

@ -0,0 +1,120 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { AzureFleetContext } from "../../api/azureFleetContext.js";
import { Fleet, FleetUpdate, VirtualMachineScaleSet } from "../../models/models.js";
import {
fleetsGet,
fleetsCreateOrUpdate,
fleetsUpdate,
fleetsDelete,
fleetsListByResourceGroup,
fleetsListBySubscription,
fleetsListVirtualMachineScaleSets,
} from "../../api/fleets/index.js";
import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js";
import { PollerLike, OperationState } from "@azure/core-lro";
import {
FleetsGetOptionalParams,
FleetsCreateOrUpdateOptionalParams,
FleetsUpdateOptionalParams,
FleetsDeleteOptionalParams,
FleetsListByResourceGroupOptionalParams,
FleetsListBySubscriptionOptionalParams,
FleetsListVirtualMachineScaleSetsOptionalParams,
} from "../../models/options.js";
/** Interface representing a Fleets operations. */
export interface FleetsOperations {
/** Get a Fleet */
get: (
resourceGroupName: string,
fleetName: string,
options?: FleetsGetOptionalParams,
) => Promise<Fleet>;
/** Create a Fleet */
createOrUpdate: (
resourceGroupName: string,
fleetName: string,
resource: Fleet,
options?: FleetsCreateOrUpdateOptionalParams,
) => PollerLike<OperationState<Fleet>, Fleet>;
/** Update a Fleet */
update: (
resourceGroupName: string,
fleetName: string,
properties: FleetUpdate,
options?: FleetsUpdateOptionalParams,
) => PollerLike<OperationState<Fleet>, Fleet>;
/** Delete a Fleet */
delete: (
resourceGroupName: string,
fleetName: string,
options?: FleetsDeleteOptionalParams,
) => PollerLike<OperationState<void>, void>;
/** List Fleet resources by resource group */
listByResourceGroup: (
resourceGroupName: string,
options?: FleetsListByResourceGroupOptionalParams,
) => PagedAsyncIterableIterator<Fleet>;
/** List Fleet resources by subscription ID */
listBySubscription: (
options?: FleetsListBySubscriptionOptionalParams,
) => PagedAsyncIterableIterator<Fleet>;
/** List VirtualMachineScaleSet resources by Fleet */
listVirtualMachineScaleSets: (
resourceGroupName: string,
name: string,
options?: FleetsListVirtualMachineScaleSetsOptionalParams,
) => PagedAsyncIterableIterator<VirtualMachineScaleSet>;
}
export function getFleets(context: AzureFleetContext, subscriptionId: string) {
return {
get: (resourceGroupName: string, fleetName: string, options?: FleetsGetOptionalParams) =>
fleetsGet(context, subscriptionId, resourceGroupName, fleetName, options),
createOrUpdate: (
resourceGroupName: string,
fleetName: string,
resource: Fleet,
options?: FleetsCreateOrUpdateOptionalParams,
) =>
fleetsCreateOrUpdate(
context,
subscriptionId,
resourceGroupName,
fleetName,
resource,
options,
),
update: (
resourceGroupName: string,
fleetName: string,
properties: FleetUpdate,
options?: FleetsUpdateOptionalParams,
) => fleetsUpdate(context, subscriptionId, resourceGroupName, fleetName, properties, options),
delete: (resourceGroupName: string, fleetName: string, options?: FleetsDeleteOptionalParams) =>
fleetsDelete(context, subscriptionId, resourceGroupName, fleetName, options),
listByResourceGroup: (
resourceGroupName: string,
options?: FleetsListByResourceGroupOptionalParams,
) => fleetsListByResourceGroup(context, subscriptionId, resourceGroupName, options),
listBySubscription: (options?: FleetsListBySubscriptionOptionalParams) =>
fleetsListBySubscription(context, subscriptionId, options),
listVirtualMachineScaleSets: (
resourceGroupName: string,
name: string,
options?: FleetsListVirtualMachineScaleSetsOptionalParams,
) =>
fleetsListVirtualMachineScaleSets(context, subscriptionId, resourceGroupName, name, options),
};
}
export function getFleetsOperations(
context: AzureFleetContext,
subscriptionId: string,
): FleetsOperations {
return {
...getFleets(context, subscriptionId),
};
}

Просмотреть файл

@ -0,0 +1,5 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export { FleetsOperations } from "./fleets/index.js";
export { OperationsOperations } from "./operations/index.js";

Просмотреть файл

@ -0,0 +1,26 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { AzureFleetContext } from "../../api/azureFleetContext.js";
import { Operation } from "../../models/models.js";
import { operationsList } from "../../api/operations/index.js";
import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js";
import { OperationsListOptionalParams } from "../../models/options.js";
/** Interface representing a Operations operations. */
export interface OperationsOperations {
/** List the operations for the provider */
list: (options?: OperationsListOptionalParams) => PagedAsyncIterableIterator<Operation>;
}
export function getOperations(context: AzureFleetContext) {
return {
list: (options?: OperationsListOptionalParams) => operationsList(context, options),
};
}
export function getOperationsOperations(context: AzureFleetContext): OperationsOperations {
return {
...getOperations(context),
};
}

Просмотреть файл

@ -0,0 +1,36 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export function serializeRecord<T extends string | number | boolean | Date | null, R>(
item: Record<string, T>,
): Record<string, R>;
export function serializeRecord<T, R>(
item: Record<string, T>,
serializer: (item: T) => R,
): Record<string, R>;
export function serializeRecord<T, R>(
item: Record<string, T>,
serializer?: (item: T) => R,
): Record<string, R> {
return Object.keys(item).reduce(
(acc, key) => {
if (isSupportedRecordType(item[key])) {
acc[key] = item[key] as any;
} else if (serializer) {
const value = item[key];
if (value !== undefined) {
acc[key] = serializer(value);
}
} else {
console.warn(`Don't know how to serialize ${item[key]}`);
acc[key] = item[key] as any;
}
return acc;
},
{} as Record<string, R>,
);
}
function isSupportedRecordType(t: any) {
return ["number", "string", "boolean", "null"].includes(typeof t) || t instanceof Date;
}

Просмотреть файл

@ -0,0 +1,172 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export { AzureFleetClient, AzureFleetClientOptionalParams } from "./azureFleetClient.js";
export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js";
export {
Resource,
SystemData,
KnownCreatedByType,
CreatedByType,
TrackedResource,
Fleet,
FleetProperties,
KnownResourceProvisioningState,
ResourceProvisioningState,
SpotPriorityProfile,
KnownEvictionPolicy,
EvictionPolicy,
KnownSpotAllocationStrategy,
SpotAllocationStrategy,
RegularPriorityProfile,
KnownRegularPriorityAllocationStrategy,
RegularPriorityAllocationStrategy,
VmSizeProfile,
ComputeProfile,
BaseVirtualMachineProfile,
VirtualMachineScaleSetOSProfile,
WindowsConfiguration,
AdditionalUnattendContent,
KnownSettingNames,
SettingNames,
PatchSettings,
KnownWindowsVMGuestPatchMode,
WindowsVMGuestPatchMode,
KnownWindowsPatchAssessmentMode,
WindowsPatchAssessmentMode,
WindowsVMGuestPatchAutomaticByPlatformSettings,
KnownWindowsVMGuestPatchAutomaticByPlatformRebootSetting,
WindowsVMGuestPatchAutomaticByPlatformRebootSetting,
WinRMConfiguration,
WinRMListener,
KnownProtocolTypes,
ProtocolTypes,
LinuxConfiguration,
SshConfiguration,
SshPublicKey,
LinuxPatchSettings,
KnownLinuxVMGuestPatchMode,
LinuxVMGuestPatchMode,
KnownLinuxPatchAssessmentMode,
LinuxPatchAssessmentMode,
LinuxVMGuestPatchAutomaticByPlatformSettings,
KnownLinuxVMGuestPatchAutomaticByPlatformRebootSetting,
LinuxVMGuestPatchAutomaticByPlatformRebootSetting,
VaultSecretGroup,
SubResource,
VaultCertificate,
VirtualMachineScaleSetStorageProfile,
ImageReference,
VirtualMachineScaleSetOSDisk,
KnownCachingTypes,
CachingTypes,
KnownDiskCreateOptionTypes,
DiskCreateOptionTypes,
DiffDiskSettings,
KnownDiffDiskOptions,
DiffDiskOptions,
KnownDiffDiskPlacement,
DiffDiskPlacement,
KnownOperatingSystemTypes,
OperatingSystemTypes,
VirtualHardDisk,
VirtualMachineScaleSetManagedDiskParameters,
KnownStorageAccountTypes,
StorageAccountTypes,
DiskEncryptionSetParameters,
VMDiskSecurityProfile,
KnownSecurityEncryptionTypes,
SecurityEncryptionTypes,
KnownDiskDeleteOptionTypes,
DiskDeleteOptionTypes,
VirtualMachineScaleSetDataDisk,
KnownDiskControllerTypes,
DiskControllerTypes,
VirtualMachineScaleSetNetworkProfile,
ApiEntityReference,
VirtualMachineScaleSetNetworkConfiguration,
VirtualMachineScaleSetNetworkConfigurationProperties,
VirtualMachineScaleSetNetworkConfigurationDnsSettings,
VirtualMachineScaleSetIPConfiguration,
VirtualMachineScaleSetIPConfigurationProperties,
VirtualMachineScaleSetPublicIPAddressConfiguration,
VirtualMachineScaleSetPublicIPAddressConfigurationProperties,
VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings,
KnownDomainNameLabelScopeTypes,
DomainNameLabelScopeTypes,
VirtualMachineScaleSetIpTag,
KnownIPVersion,
IPVersion,
KnownDeleteOptions,
DeleteOptions,
PublicIPAddressSku,
KnownPublicIPAddressSkuName,
PublicIPAddressSkuName,
KnownPublicIPAddressSkuTier,
PublicIPAddressSkuTier,
KnownNetworkInterfaceAuxiliaryMode,
NetworkInterfaceAuxiliaryMode,
KnownNetworkInterfaceAuxiliarySku,
NetworkInterfaceAuxiliarySku,
KnownNetworkApiVersion,
NetworkApiVersion,
SecurityProfile,
UefiSettings,
KnownSecurityTypes,
SecurityTypes,
EncryptionIdentity,
ProxyAgentSettings,
KnownMode,
Mode,
DiagnosticsProfile,
BootDiagnostics,
VirtualMachineScaleSetExtensionProfile,
VirtualMachineScaleSetExtension,
VirtualMachineScaleSetExtensionProperties,
KeyVaultSecretReference,
ScheduledEventsProfile,
TerminateNotificationProfile,
OSImageNotificationProfile,
CapacityReservationProfile,
ApplicationProfile,
VMGalleryApplication,
VirtualMachineScaleSetHardwareProfile,
VMSizeProperties,
ServiceArtifactReference,
SecurityPostureReference,
ManagedServiceIdentity,
KnownManagedServiceIdentityType,
ManagedServiceIdentityType,
UserAssignedIdentity,
Plan,
ErrorResponse,
ErrorDetail,
ErrorAdditionalInfo,
FleetUpdate,
ManagedServiceIdentityUpdate,
ResourcePlanUpdate,
VirtualMachineScaleSet,
ApiError,
ApiErrorBase,
InnerError,
Operation,
OperationDisplay,
KnownOrigin,
Origin,
KnownActionType,
ActionType,
Versions,
ProvisioningState,
OperationsListOptionalParams,
FleetsGetOptionalParams,
FleetsCreateOrUpdateOptionalParams,
FleetsUpdateOptionalParams,
FleetsDeleteOptionalParams,
FleetsListByResourceGroupOptionalParams,
FleetsListBySubscriptionOptionalParams,
FleetsListVirtualMachineScaleSetsOptionalParams,
PageSettings,
ContinuablePage,
PagedAsyncIterableIterator,
} from "./models/index.js";
export { FleetsOperations, OperationsOperations } from "./classic/index.js";

Просмотреть файл

@ -0,0 +1,5 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { createClientLogger } from "@azure/logger";
export const logger = createClientLogger("arm-computefleet");

Просмотреть файл

@ -0,0 +1,169 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export {
Resource,
SystemData,
KnownCreatedByType,
CreatedByType,
TrackedResource,
Fleet,
FleetProperties,
KnownResourceProvisioningState,
ResourceProvisioningState,
SpotPriorityProfile,
KnownEvictionPolicy,
EvictionPolicy,
KnownSpotAllocationStrategy,
SpotAllocationStrategy,
RegularPriorityProfile,
KnownRegularPriorityAllocationStrategy,
RegularPriorityAllocationStrategy,
VmSizeProfile,
ComputeProfile,
BaseVirtualMachineProfile,
VirtualMachineScaleSetOSProfile,
WindowsConfiguration,
AdditionalUnattendContent,
KnownSettingNames,
SettingNames,
PatchSettings,
KnownWindowsVMGuestPatchMode,
WindowsVMGuestPatchMode,
KnownWindowsPatchAssessmentMode,
WindowsPatchAssessmentMode,
WindowsVMGuestPatchAutomaticByPlatformSettings,
KnownWindowsVMGuestPatchAutomaticByPlatformRebootSetting,
WindowsVMGuestPatchAutomaticByPlatformRebootSetting,
WinRMConfiguration,
WinRMListener,
KnownProtocolTypes,
ProtocolTypes,
LinuxConfiguration,
SshConfiguration,
SshPublicKey,
LinuxPatchSettings,
KnownLinuxVMGuestPatchMode,
LinuxVMGuestPatchMode,
KnownLinuxPatchAssessmentMode,
LinuxPatchAssessmentMode,
LinuxVMGuestPatchAutomaticByPlatformSettings,
KnownLinuxVMGuestPatchAutomaticByPlatformRebootSetting,
LinuxVMGuestPatchAutomaticByPlatformRebootSetting,
VaultSecretGroup,
SubResource,
VaultCertificate,
VirtualMachineScaleSetStorageProfile,
ImageReference,
VirtualMachineScaleSetOSDisk,
KnownCachingTypes,
CachingTypes,
KnownDiskCreateOptionTypes,
DiskCreateOptionTypes,
DiffDiskSettings,
KnownDiffDiskOptions,
DiffDiskOptions,
KnownDiffDiskPlacement,
DiffDiskPlacement,
KnownOperatingSystemTypes,
OperatingSystemTypes,
VirtualHardDisk,
VirtualMachineScaleSetManagedDiskParameters,
KnownStorageAccountTypes,
StorageAccountTypes,
DiskEncryptionSetParameters,
VMDiskSecurityProfile,
KnownSecurityEncryptionTypes,
SecurityEncryptionTypes,
KnownDiskDeleteOptionTypes,
DiskDeleteOptionTypes,
VirtualMachineScaleSetDataDisk,
KnownDiskControllerTypes,
DiskControllerTypes,
VirtualMachineScaleSetNetworkProfile,
ApiEntityReference,
VirtualMachineScaleSetNetworkConfiguration,
VirtualMachineScaleSetNetworkConfigurationProperties,
VirtualMachineScaleSetNetworkConfigurationDnsSettings,
VirtualMachineScaleSetIPConfiguration,
VirtualMachineScaleSetIPConfigurationProperties,
VirtualMachineScaleSetPublicIPAddressConfiguration,
VirtualMachineScaleSetPublicIPAddressConfigurationProperties,
VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings,
KnownDomainNameLabelScopeTypes,
DomainNameLabelScopeTypes,
VirtualMachineScaleSetIpTag,
KnownIPVersion,
IPVersion,
KnownDeleteOptions,
DeleteOptions,
PublicIPAddressSku,
KnownPublicIPAddressSkuName,
PublicIPAddressSkuName,
KnownPublicIPAddressSkuTier,
PublicIPAddressSkuTier,
KnownNetworkInterfaceAuxiliaryMode,
NetworkInterfaceAuxiliaryMode,
KnownNetworkInterfaceAuxiliarySku,
NetworkInterfaceAuxiliarySku,
KnownNetworkApiVersion,
NetworkApiVersion,
SecurityProfile,
UefiSettings,
KnownSecurityTypes,
SecurityTypes,
EncryptionIdentity,
ProxyAgentSettings,
KnownMode,
Mode,
DiagnosticsProfile,
BootDiagnostics,
VirtualMachineScaleSetExtensionProfile,
VirtualMachineScaleSetExtension,
VirtualMachineScaleSetExtensionProperties,
KeyVaultSecretReference,
ScheduledEventsProfile,
TerminateNotificationProfile,
OSImageNotificationProfile,
CapacityReservationProfile,
ApplicationProfile,
VMGalleryApplication,
VirtualMachineScaleSetHardwareProfile,
VMSizeProperties,
ServiceArtifactReference,
SecurityPostureReference,
ManagedServiceIdentity,
KnownManagedServiceIdentityType,
ManagedServiceIdentityType,
UserAssignedIdentity,
Plan,
ErrorResponse,
ErrorDetail,
ErrorAdditionalInfo,
FleetUpdate,
ManagedServiceIdentityUpdate,
ResourcePlanUpdate,
VirtualMachineScaleSet,
ApiError,
ApiErrorBase,
InnerError,
Operation,
OperationDisplay,
KnownOrigin,
Origin,
KnownActionType,
ActionType,
Versions,
ProvisioningState,
} from "./models.js";
export {
OperationsListOptionalParams,
FleetsGetOptionalParams,
FleetsCreateOrUpdateOptionalParams,
FleetsUpdateOptionalParams,
FleetsDeleteOptionalParams,
FleetsListByResourceGroupOptionalParams,
FleetsListBySubscriptionOptionalParams,
FleetsListVirtualMachineScaleSetsOptionalParams,
} from "./options.js";
export { PageSettings, ContinuablePage, PagedAsyncIterableIterator } from "./pagingTypes.js";

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,37 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { OperationOptions } from "@azure-rest/core-client";
/** Optional parameters. */
export interface OperationsListOptionalParams extends OperationOptions {}
/** Optional parameters. */
export interface FleetsGetOptionalParams extends OperationOptions {}
/** Optional parameters. */
export interface FleetsCreateOrUpdateOptionalParams extends OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
}
/** Optional parameters. */
export interface FleetsUpdateOptionalParams extends OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
}
/** Optional parameters. */
export interface FleetsDeleteOptionalParams extends OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
}
/** Optional parameters. */
export interface FleetsListByResourceGroupOptionalParams extends OperationOptions {}
/** Optional parameters. */
export interface FleetsListBySubscriptionOptionalParams extends OperationOptions {}
/** Optional parameters. */
export interface FleetsListVirtualMachineScaleSetsOptionalParams extends OperationOptions {}

Просмотреть файл

@ -0,0 +1,79 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* Options for the byPage method
*/
export interface PageSettings {
/**
* A reference to a specific page to start iterating from.
*/
continuationToken?: string;
}
/**
* An interface that describes a page of results.
*/
export type ContinuablePage<TElement, TPage = TElement[]> = TPage & {
/**
* 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 extends PageSettings = PageSettings,
> {
/**
* The next method, part of the iteration protocol
*/
next(): Promise<IteratorResult<TElement>>;
/**
* 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<ContinuablePage<TElement, TPage>>;
}
/**
* An interface that describes how to communicate with the service.
*/
export interface PagedResult<
TElement,
TPage = TElement[],
TPageSettings extends PageSettings = PageSettings,
> {
/**
* Link to the first page of results.
*/
firstPageLink?: string;
/**
* A method that returns a page of results.
*/
getPage: (pageLink?: string) => Promise<{ page: TPage; nextPageLink?: string } | undefined>;
/**
* a function to implement the `byPage` method on the paged async iterator.
*/
byPage?: (settings?: TPageSettings) => AsyncIterableIterator<ContinuablePage<TElement, TPage>>;
/**
* A function to extract elements from a page.
*/
toElements?: (page: TPage) => TElement[];
}
/**
* Options for the paging helper
*/
export interface BuildPagedAsyncIteratorOptions {
itemName?: string;
nextLinkName?: string;
}

Просмотреть файл

@ -0,0 +1,61 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { getClient, ClientOptions } from "@azure-rest/core-client";
import { logger } from "../logger.js";
import { TokenCredential } from "@azure/core-auth";
import { AzureFleetContext } from "./clientDefinitions.js";
/** The optional parameters for the client */
export interface AzureFleetContextOptions extends ClientOptions {
/** The api version option of the client */
apiVersion?: string;
}
/**
* Initialize a new instance of `AzureFleetContext`
* @param credentials - uniquely identify client credential
* @param options - the parameter for all optional parameters
*/
export default function createClient(
credentials: TokenCredential,
{ apiVersion = "2024-05-01-preview", ...options }: AzureFleetContextOptions = {},
): AzureFleetContext {
const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://management.azure.com`;
const userAgentInfo = `azsdk-js-arm-computefleet/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 ?? [`${endpointUrl}/.default`],
},
};
const client = getClient(endpointUrl, credentials, options) as AzureFleetContext;
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;
}

Просмотреть файл

@ -0,0 +1,130 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
OperationsListParameters,
FleetsGetParameters,
FleetsCreateOrUpdateParameters,
FleetsUpdateParameters,
FleetsDeleteParameters,
FleetsListByResourceGroupParameters,
FleetsListBySubscriptionParameters,
FleetsListVirtualMachineScaleSetsParameters,
} from "./parameters.js";
import {
OperationsList200Response,
OperationsListDefaultResponse,
FleetsGet200Response,
FleetsGetDefaultResponse,
FleetsCreateOrUpdate200Response,
FleetsCreateOrUpdate201Response,
FleetsCreateOrUpdateDefaultResponse,
FleetsUpdate200Response,
FleetsUpdate202Response,
FleetsUpdateDefaultResponse,
FleetsDelete202Response,
FleetsDelete204Response,
FleetsDeleteDefaultResponse,
FleetsListByResourceGroup200Response,
FleetsListByResourceGroupDefaultResponse,
FleetsListBySubscription200Response,
FleetsListBySubscriptionDefaultResponse,
FleetsListVirtualMachineScaleSets200Response,
FleetsListVirtualMachineScaleSetsDefaultResponse,
} from "./responses.js";
import { Client, StreamableMethod } from "@azure-rest/core-client";
export interface OperationsList {
/** List the operations for the provider */
get(
options?: OperationsListParameters,
): StreamableMethod<OperationsList200Response | OperationsListDefaultResponse>;
}
export interface FleetsGet {
/** Get a Fleet */
get(
options?: FleetsGetParameters,
): StreamableMethod<FleetsGet200Response | FleetsGetDefaultResponse>;
/** Create a Fleet */
put(
options: FleetsCreateOrUpdateParameters,
): StreamableMethod<
| FleetsCreateOrUpdate200Response
| FleetsCreateOrUpdate201Response
| FleetsCreateOrUpdateDefaultResponse
>;
/** Update a Fleet */
patch(
options: FleetsUpdateParameters,
): StreamableMethod<
FleetsUpdate200Response | FleetsUpdate202Response | FleetsUpdateDefaultResponse
>;
/** Delete a Fleet */
delete(
options?: FleetsDeleteParameters,
): StreamableMethod<
FleetsDelete202Response | FleetsDelete204Response | FleetsDeleteDefaultResponse
>;
}
export interface FleetsListByResourceGroup {
/** List Fleet resources by resource group */
get(
options?: FleetsListByResourceGroupParameters,
): StreamableMethod<
FleetsListByResourceGroup200Response | FleetsListByResourceGroupDefaultResponse
>;
}
export interface FleetsListBySubscription {
/** List Fleet resources by subscription ID */
get(
options?: FleetsListBySubscriptionParameters,
): StreamableMethod<
FleetsListBySubscription200Response | FleetsListBySubscriptionDefaultResponse
>;
}
export interface FleetsListVirtualMachineScaleSets {
/** List VirtualMachineScaleSet resources by Fleet */
get(
options?: FleetsListVirtualMachineScaleSetsParameters,
): StreamableMethod<
FleetsListVirtualMachineScaleSets200Response | FleetsListVirtualMachineScaleSetsDefaultResponse
>;
}
export interface Routes {
/** Resource for '/providers/Microsoft.AzureFleet/operations' has methods for the following verbs: get */
(path: "/providers/Microsoft.AzureFleet/operations"): OperationsList;
/** Resource for '/subscriptions/\{subscriptionId\}/resourceGroups/\{resourceGroupName\}/providers/Microsoft.AzureFleet/fleets/\{fleetName\}' has methods for the following verbs: get, put, patch, delete */
(
path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}",
subscriptionId: string,
resourceGroupName: string,
fleetName: string,
): FleetsGet;
/** Resource for '/subscriptions/\{subscriptionId\}/resourceGroups/\{resourceGroupName\}/providers/Microsoft.AzureFleet/fleets' has methods for the following verbs: get */
(
path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets",
subscriptionId: string,
resourceGroupName: string,
): FleetsListByResourceGroup;
/** Resource for '/subscriptions/\{subscriptionId\}/providers/Microsoft.AzureFleet/fleets' has methods for the following verbs: get */
(
path: "/subscriptions/{subscriptionId}/providers/Microsoft.AzureFleet/fleets",
subscriptionId: string,
): FleetsListBySubscription;
/** Resource for '/subscriptions/\{subscriptionId\}/resourceGroups/\{resourceGroupName\}/providers/Microsoft.AzureFleet/fleets/\{name\}/virtualMachineScaleSets' has methods for the following verbs: get */
(
path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{name}/virtualMachineScaleSets",
subscriptionId: string,
resourceGroupName: string,
name: string,
): FleetsListVirtualMachineScaleSets;
}
export type AzureFleetContext = Client & {
path: Routes;
};

Просмотреть файл

@ -0,0 +1,16 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import AzureFleetClient from "./azureFleetClient.js";
export * from "./azureFleetClient.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 * from "./pollingHelper.js";
export default AzureFleetClient;

Просмотреть файл

@ -0,0 +1,191 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
OperationsList200Response,
OperationsListDefaultResponse,
FleetsGet200Response,
FleetsGetDefaultResponse,
FleetsCreateOrUpdate200Response,
FleetsCreateOrUpdate201Response,
FleetsCreateOrUpdateLogicalResponse,
FleetsCreateOrUpdateDefaultResponse,
FleetsUpdate200Response,
FleetsUpdate202Response,
FleetsUpdateLogicalResponse,
FleetsUpdateDefaultResponse,
FleetsDelete202Response,
FleetsDelete204Response,
FleetsDeleteLogicalResponse,
FleetsDeleteDefaultResponse,
FleetsListByResourceGroup200Response,
FleetsListByResourceGroupDefaultResponse,
FleetsListBySubscription200Response,
FleetsListBySubscriptionDefaultResponse,
FleetsListVirtualMachineScaleSets200Response,
FleetsListVirtualMachineScaleSetsDefaultResponse,
} from "./responses.js";
const responseMap: Record<string, string[]> = {
"GET /providers/Microsoft.AzureFleet/operations": ["200"],
"GET /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}":
["200"],
"PUT /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}":
["200", "201"],
"PATCH /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}":
["200", "202"],
"DELETE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}":
["202", "204"],
"GET /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets":
["200"],
"GET /subscriptions/{subscriptionId}/providers/Microsoft.AzureFleet/fleets": ["200"],
"GET /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{name}/virtualMachineScaleSets":
["200"],
};
export function isUnexpected(
response: OperationsList200Response | OperationsListDefaultResponse,
): response is OperationsListDefaultResponse;
export function isUnexpected(
response: FleetsGet200Response | FleetsGetDefaultResponse,
): response is FleetsGetDefaultResponse;
export function isUnexpected(
response:
| FleetsCreateOrUpdate200Response
| FleetsCreateOrUpdate201Response
| FleetsCreateOrUpdateLogicalResponse
| FleetsCreateOrUpdateDefaultResponse,
): response is FleetsCreateOrUpdateDefaultResponse;
export function isUnexpected(
response:
| FleetsUpdate200Response
| FleetsUpdate202Response
| FleetsUpdateLogicalResponse
| FleetsUpdateDefaultResponse,
): response is FleetsUpdateDefaultResponse;
export function isUnexpected(
response:
| FleetsDelete202Response
| FleetsDelete204Response
| FleetsDeleteLogicalResponse
| FleetsDeleteDefaultResponse,
): response is FleetsDeleteDefaultResponse;
export function isUnexpected(
response: FleetsListByResourceGroup200Response | FleetsListByResourceGroupDefaultResponse,
): response is FleetsListByResourceGroupDefaultResponse;
export function isUnexpected(
response: FleetsListBySubscription200Response | FleetsListBySubscriptionDefaultResponse,
): response is FleetsListBySubscriptionDefaultResponse;
export function isUnexpected(
response:
| FleetsListVirtualMachineScaleSets200Response
| FleetsListVirtualMachineScaleSetsDefaultResponse,
): response is FleetsListVirtualMachineScaleSetsDefaultResponse;
export function isUnexpected(
response:
| OperationsList200Response
| OperationsListDefaultResponse
| FleetsGet200Response
| FleetsGetDefaultResponse
| FleetsCreateOrUpdate200Response
| FleetsCreateOrUpdate201Response
| FleetsCreateOrUpdateLogicalResponse
| FleetsCreateOrUpdateDefaultResponse
| FleetsUpdate200Response
| FleetsUpdate202Response
| FleetsUpdateLogicalResponse
| FleetsUpdateDefaultResponse
| FleetsDelete202Response
| FleetsDelete204Response
| FleetsDeleteLogicalResponse
| FleetsDeleteDefaultResponse
| FleetsListByResourceGroup200Response
| FleetsListByResourceGroupDefaultResponse
| FleetsListBySubscription200Response
| FleetsListBySubscriptionDefaultResponse
| FleetsListVirtualMachineScaleSets200Response
| FleetsListVirtualMachineScaleSetsDefaultResponse,
): response is
| OperationsListDefaultResponse
| FleetsGetDefaultResponse
| FleetsCreateOrUpdateDefaultResponse
| FleetsUpdateDefaultResponse
| FleetsDeleteDefaultResponse
| FleetsListByResourceGroupDefaultResponse
| FleetsListBySubscriptionDefaultResponse
| FleetsListVirtualMachineScaleSetsDefaultResponse {
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);
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,131 @@
// 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> = T extends Array<infer TData> ? 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<TPage> = (
pageLink: string,
maxPageSize?: number,
) => Promise<{
page: TPage;
nextPageLink?: string;
}>;
/**
* Options for the paging helper
*/
export interface PagingOptions<TResponse> {
/**
* Custom function to extract pagination details for crating the PagedAsyncIterableIterator
*/
customGetPage?: GetPage<PaginateReturn<TResponse>[]>;
}
/**
* 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> = TResult extends {
body: { value?: infer TPage };
}
? GetArrayType<TPage>
: Array<unknown>;
/**
* 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<TResponse extends PathUncheckedResponse>(
client: Client,
initialResponse: TResponse,
options: PagingOptions<TResponse> = {},
): PagedAsyncIterableIterator<PaginateReturn<TResponse>> {
// Extract element type from initial response
type TElement = PaginateReturn<TResponse>;
let firstRun = true;
const itemName = "value";
const nextLinkName = "nextLink";
const { customGetPage } = options;
const pagedResult: PagedResult<TElement[]> = {
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<TElement>(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<string, unknown>)[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<T = unknown>(body: unknown, itemName: string): T[] {
const value = (body as Record<string, unknown>)[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,
);
}
}

Просмотреть файл

@ -0,0 +1,26 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { RequestParameters } from "@azure-rest/core-client";
import { Fleet, FleetUpdate } from "./models.js";
export type OperationsListParameters = RequestParameters;
export type FleetsGetParameters = RequestParameters;
export interface FleetsCreateOrUpdateBodyParam {
/** Resource create parameters. */
body: Fleet;
}
export type FleetsCreateOrUpdateParameters = FleetsCreateOrUpdateBodyParam & RequestParameters;
export interface FleetsUpdateBodyParam {
/** The resource properties to be updated. */
body: FleetUpdate;
}
export type FleetsUpdateParameters = FleetsUpdateBodyParam & RequestParameters;
export type FleetsDeleteParameters = RequestParameters;
export type FleetsListByResourceGroupParameters = RequestParameters;
export type FleetsListBySubscriptionParameters = RequestParameters;
export type FleetsListVirtualMachineScaleSetsParameters = RequestParameters;

Просмотреть файл

@ -0,0 +1,232 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { Client, HttpResponse } from "@azure-rest/core-client";
import { AbortSignalLike } from "@azure/abort-controller";
import {
CancelOnProgress,
CreateHttpPollerOptions,
RunningOperation,
OperationResponse,
OperationState,
createHttpPoller,
} from "@azure/core-lro";
import {
FleetsCreateOrUpdate200Response,
FleetsCreateOrUpdate201Response,
FleetsCreateOrUpdateDefaultResponse,
FleetsCreateOrUpdateLogicalResponse,
FleetsUpdate200Response,
FleetsUpdate202Response,
FleetsUpdateDefaultResponse,
FleetsUpdateLogicalResponse,
FleetsDelete202Response,
FleetsDelete204Response,
FleetsDeleteDefaultResponse,
FleetsDeleteLogicalResponse,
} from "./responses.js";
/**
* A simple poller that can be used to poll a long running operation.
*/
export interface SimplePollerLike<TState extends OperationState<TResult>, TResult> {
/**
* Returns true if the poller has finished polling.
*/
isDone(): boolean;
/**
* Returns the state of the operation.
*/
getOperationState(): TState;
/**
* Returns the result value of the operation,
* regardless of the state of the poller.
* It can return undefined or an incomplete form of the final TResult value
* depending on the implementation.
*/
getResult(): TResult | undefined;
/**
* Returns a promise that will resolve once a single polling request finishes.
* It does this by calling the update method of the Poller's operation.
*/
poll(options?: { abortSignal?: AbortSignalLike }): Promise<TState>;
/**
* Returns a promise that will resolve once the underlying operation is completed.
*/
pollUntilDone(pollOptions?: { abortSignal?: AbortSignalLike }): Promise<TResult>;
/**
* Invokes the provided callback after each polling is completed,
* sending the current state of the poller's operation.
*
* It returns a method that can be used to stop receiving updates on the given callback function.
*/
onProgress(callback: (state: TState) => void): CancelOnProgress;
/**
* Returns a promise that could be used for serialized version of the poller's operation
* by invoking the operation's serialize method.
*/
serialize(): Promise<string>;
/**
* Wait the poller to be submitted.
*/
submitted(): Promise<void>;
/**
* Returns a string representation of the poller's operation. Similar to serialize but returns a string.
* @deprecated Use serialize() instead.
*/
toString(): string;
/**
* Stops the poller from continuing to poll. Please note this will only stop the client-side polling
* @deprecated Use abortSignal to stop polling instead.
*/
stopPolling(): void;
/**
* Returns true if the poller is stopped.
* @deprecated Use abortSignal status to track this instead.
*/
isStopped(): boolean;
}
/**
* 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 FleetsCreateOrUpdateLogicalResponse | FleetsCreateOrUpdateDefaultResponse,
>(
client: Client,
initialResponse:
| FleetsCreateOrUpdate200Response
| FleetsCreateOrUpdate201Response
| FleetsCreateOrUpdateDefaultResponse,
options?: CreateHttpPollerOptions<TResult, OperationState<TResult>>,
): Promise<SimplePollerLike<OperationState<TResult>, TResult>>;
export async function getLongRunningPoller<
TResult extends FleetsUpdateLogicalResponse | FleetsUpdateDefaultResponse,
>(
client: Client,
initialResponse: FleetsUpdate200Response | FleetsUpdate202Response | FleetsUpdateDefaultResponse,
options?: CreateHttpPollerOptions<TResult, OperationState<TResult>>,
): Promise<SimplePollerLike<OperationState<TResult>, TResult>>;
export async function getLongRunningPoller<
TResult extends FleetsDeleteLogicalResponse | FleetsDeleteDefaultResponse,
>(
client: Client,
initialResponse: FleetsDelete202Response | FleetsDelete204Response | FleetsDeleteDefaultResponse,
options?: CreateHttpPollerOptions<TResult, OperationState<TResult>>,
): Promise<SimplePollerLike<OperationState<TResult>, TResult>>;
export async function getLongRunningPoller<TResult extends HttpResponse>(
client: Client,
initialResponse: TResult,
options: CreateHttpPollerOptions<TResult, OperationState<TResult>> = {},
): Promise<SimplePollerLike<OperationState<TResult>, TResult>> {
const abortController = new AbortController();
const poller: RunningOperation<TResult> = {
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: string, pollOptions?: { abortSignal?: AbortSignalLike }) => {
// 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.
function abortListener(): void {
abortController.abort();
}
const inputAbortSignal = pollOptions?.abortSignal;
const abortSignal = abortController.signal;
if (inputAbortSignal?.aborted) {
abortController.abort();
} else if (!abortSignal.aborted) {
inputAbortSignal?.addEventListener("abort", abortListener, {
once: true,
});
}
let response;
try {
response = await client
.pathUnchecked(path ?? initialResponse.request.url)
.get({ abortSignal });
} finally {
inputAbortSignal?.removeEventListener("abort", abortListener);
}
const lroResponse = getLroResponse(response as TResult);
lroResponse.rawResponse.headers["x-ms-original-url"] = initialResponse.request.url;
return lroResponse;
},
};
options.resolveOnUnsuccessful = options.resolveOnUnsuccessful ?? true;
const httpPoller = createHttpPoller(poller, options);
const simplePoller: SimplePollerLike<OperationState<TResult>, TResult> = {
isDone() {
return httpPoller.isDone;
},
isStopped() {
return abortController.signal.aborted;
},
getOperationState() {
if (!httpPoller.operationState) {
throw new Error(
"Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().",
);
}
return httpPoller.operationState;
},
getResult() {
return httpPoller.result;
},
toString() {
if (!httpPoller.operationState) {
throw new Error(
"Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().",
);
}
return JSON.stringify({
state: httpPoller.operationState,
});
},
stopPolling() {
abortController.abort();
},
onProgress: httpPoller.onProgress,
poll: httpPoller.poll,
pollUntilDone: httpPoller.pollUntilDone,
serialize: httpPoller.serialize,
submitted: httpPoller.submitted,
};
return simplePoller;
}
/**
* 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<TResult extends HttpResponse>(
response: TResult,
): OperationResponse<TResult> {
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,
},
};
}

Просмотреть файл

@ -0,0 +1,154 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { RawHttpHeaders } from "@azure/core-rest-pipeline";
import { HttpResponse } from "@azure-rest/core-client";
import {
OperationListResultOutput,
ErrorResponseOutput,
FleetOutput,
FleetListResultOutput,
VirtualMachineScaleSetListResultOutput,
} from "./outputModels.js";
/** Azure operation completed successfully. */
export interface OperationsList200Response extends HttpResponse {
status: "200";
body: OperationListResultOutput;
}
export interface OperationsListDefaultResponse extends HttpResponse {
status: string;
body: ErrorResponseOutput;
}
/** Azure operation completed successfully. */
export interface FleetsGet200Response extends HttpResponse {
status: "200";
body: FleetOutput;
}
export interface FleetsGetDefaultResponse extends HttpResponse {
status: string;
body: ErrorResponseOutput;
}
/** Resource 'Fleet' update operation succeeded */
export interface FleetsCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: FleetOutput;
}
export interface FleetsCreateOrUpdate201Headers {
/** The Retry-After header can indicate how long the client should wait before polling the operation status. */
"retry-after"?: number;
}
/** Resource 'Fleet' create operation succeeded */
export interface FleetsCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: FleetOutput;
headers: RawHttpHeaders & FleetsCreateOrUpdate201Headers;
}
export interface FleetsCreateOrUpdateDefaultResponse extends HttpResponse {
status: string;
body: ErrorResponseOutput;
}
/** The final response for long-running createOrUpdate operation */
export interface FleetsCreateOrUpdateLogicalResponse extends HttpResponse {
status: "200";
body: FleetOutput;
}
/** Azure operation completed successfully. */
export interface FleetsUpdate200Response extends HttpResponse {
status: "200";
body: FleetOutput;
}
export interface FleetsUpdate202Headers {
/** The Location header contains the URL where the status of the long running operation can be checked. */
location?: string;
/** The Retry-After header can indicate how long the client should wait before polling the operation status. */
"retry-after"?: number;
}
/** Resource update request accepted. */
export interface FleetsUpdate202Response extends HttpResponse {
status: "202";
headers: RawHttpHeaders & FleetsUpdate202Headers;
}
export interface FleetsUpdateDefaultResponse extends HttpResponse {
status: string;
body: ErrorResponseOutput;
}
/** The final response for long-running update operation */
export interface FleetsUpdateLogicalResponse extends HttpResponse {
status: "200";
body: FleetOutput;
}
export interface FleetsDelete202Headers {
/** The Location header contains the URL where the status of the long running operation can be checked. */
location?: string;
/** The Retry-After header can indicate how long the client should wait before polling the operation status. */
"retry-after"?: number;
}
/** Resource deletion accepted. */
export interface FleetsDelete202Response extends HttpResponse {
status: "202";
headers: RawHttpHeaders & FleetsDelete202Headers;
}
/** Resource does not exist. */
export interface FleetsDelete204Response extends HttpResponse {
status: "204";
}
export interface FleetsDeleteDefaultResponse extends HttpResponse {
status: string;
body: ErrorResponseOutput;
}
/** The final response for long-running delete operation */
export interface FleetsDeleteLogicalResponse extends HttpResponse {
status: "200";
}
/** Azure operation completed successfully. */
export interface FleetsListByResourceGroup200Response extends HttpResponse {
status: "200";
body: FleetListResultOutput;
}
export interface FleetsListByResourceGroupDefaultResponse extends HttpResponse {
status: string;
body: ErrorResponseOutput;
}
/** Azure operation completed successfully. */
export interface FleetsListBySubscription200Response extends HttpResponse {
status: "200";
body: FleetListResultOutput;
}
export interface FleetsListBySubscriptionDefaultResponse extends HttpResponse {
status: string;
body: ErrorResponseOutput;
}
/** Azure operation completed successfully. */
export interface FleetsListVirtualMachineScaleSets200Response extends HttpResponse {
status: "200";
body: VirtualMachineScaleSetListResultOutput;
}
export interface FleetsListVirtualMachineScaleSetsDefaultResponse extends HttpResponse {
status: string;
body: ErrorResponseOutput;
}

Просмотреть файл

@ -0,0 +1,152 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
PollerLike,
OperationState,
deserializeState,
ResourceLocationConfig,
} from "@azure/core-lro";
import { AzureFleetClient } from "./azureFleetClient.js";
import { getLongRunningPoller } from "./api/pollingHelpers.js";
import {
_fleetsCreateOrUpdateDeserialize,
_fleetsUpdateDeserialize,
_fleetsDeleteDeserialize,
} from "./api/fleets/index.js";
import { PathUncheckedResponse, OperationOptions } from "@azure-rest/core-client";
import { AbortSignalLike } from "@azure/abort-controller";
export interface RestorePollerOptions<
TResult,
TResponse extends PathUncheckedResponse = PathUncheckedResponse,
> extends OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/**
* The signal which can be used to abort requests.
*/
abortSignal?: AbortSignalLike;
/** Deserialization function for raw response body */
processResponseBody?: (result: TResponse) => Promise<TResult>;
}
/**
* Creates a poller from the serialized state of another poller. This can be
* useful when you want to create pollers on a different host or a poller
* needs to be constructed after the original one is not in scope.
*/
export function restorePoller<TResponse extends PathUncheckedResponse, TResult>(
client: AzureFleetClient,
serializedState: string,
sourceOperation: (...args: any[]) => PollerLike<OperationState<TResult>, TResult>,
options?: RestorePollerOptions<TResult>,
): PollerLike<OperationState<TResult>, TResult> {
const pollerConfig = deserializeState(serializedState).config;
const { initialRequestUrl, requestMethod, metadata } = pollerConfig;
if (!initialRequestUrl || !requestMethod) {
throw new Error(
`Invalid serialized state: ${serializedState} for sourceOperation ${sourceOperation?.name}`,
);
}
const resourceLocationConfig = metadata?.["resourceLocationConfig"] as
| ResourceLocationConfig
| undefined;
const deserializeHelper =
options?.processResponseBody ?? getDeserializationHelper(initialRequestUrl, requestMethod);
if (!deserializeHelper) {
throw new Error(
`Please ensure the operation is in this client! We can't find its deserializeHelper for ${sourceOperation?.name}.`,
);
}
return getLongRunningPoller(
(client as any)["_client"] ?? client,
deserializeHelper as (result: TResponse) => Promise<TResult>,
{
updateIntervalInMs: options?.updateIntervalInMs,
abortSignal: options?.abortSignal,
resourceLocationConfig,
restoreFrom: serializedState,
initialRequestUrl,
},
);
}
const deserializeMap: Record<string, Function> = {
"PUT /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}":
_fleetsCreateOrUpdateDeserialize,
"PATCH /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}":
_fleetsUpdateDeserialize,
"DELETE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureFleet/fleets/{fleetName}":
_fleetsDeleteDeserialize,
};
function getDeserializationHelper(
urlStr: string,
method: string,
): ((result: unknown) => Promise<unknown>) | undefined {
const path = new URL(urlStr).pathname;
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: ((result: unknown) => Promise<unknown>) | undefined;
// Iterate the responseMap to find a match
for (const [key, value] of Object.entries(deserializeMap)) {
// 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 as (result: unknown) => Promise<unknown>;
}
}
return matchedValue;
}
function getPathFromMapKey(mapKey: string): string {
const pathStart = mapKey.indexOf("/");
return mapKey.slice(pathStart);
}

Просмотреть файл

@ -0,0 +1,176 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import { env, Recorder, isPlaybackMode } from "@azure-tools/test-recorder";
import { createTestCredential } from "@azure-tools/test-credential";
import { assert, beforeEach, afterEach, it, describe } from "vitest";
import { createRecorder } from "./utils/recordedClient.js";
import { AzureFleetClient } from "../../src/azureFleetClient.js";
export const testPollingOptions = {
updateIntervalInMs: isPlaybackMode() ? 0 : undefined,
};
describe("AzureFleet test", () => {
let recorder: Recorder;
let subscriptionId: string;
let client: AzureFleetClient;
let location: string;
let resourceGroup: string;
let resourcename: string;
beforeEach(async (context) => {
process.env.SystemRoot = process.env.SystemRoot || "C:\\Windows";
recorder = await createRecorder(context);
subscriptionId = env.SUBSCRIPTION_ID || "";
// This is an example of how the environment variables are used
const credential = createTestCredential();
client = new AzureFleetClient(credential, subscriptionId, recorder.configureClientOptions({}));
location = "eastus2euap";
resourceGroup = "myjstest";
resourcename = "resourcetest";
});
afterEach(async function () {
if (recorder?.recordingId) {
await recorder.stop();
}
});
// first create a networkSecurityGroups named "testnsg" with eastus2euap on portal
// second create a virtual network named "czwtestvn" with eastus2euap and config the ip address as 172.16.0.0/16 when creating a vitrual network on portal
// third create a subnet named "testsub" and before click add button, enable private subnet and link to networkSecurityGroups
it("fleets create test", async function () {
const res = await client.fleets.createOrUpdate(
resourceGroup,
resourcename,
{
location,
properties: {
spotPriorityProfile: {
maxPricePerVM: 1,
evictionPolicy: "Delete",
allocationStrategy: "LowestPrice",
maintain: true,
capacity: 1,
},
vmSizesProfile: [
{
name: "Standard_D2s_v3",
},
{
name: "Standard_D4s_v3",
},
{
name: "Standard_E2s_v3",
},
],
computeProfile: {
baseVirtualMachineProfile: {
storageProfile: {
imageReference: {
publisher: "canonical",
offer: "0001-com-ubuntu-server-focal",
sku: "20_04-lts-gen2",
version: "latest",
},
osDisk: {
createOption: "fromImage",
caching: "ReadWrite",
osType: "Linux",
managedDisk: {
storageAccountType: "Premium_LRS",
},
},
},
licenseType: "None",
osProfile: {
adminUsername: "azureuser",
adminPassword: "testComputefleet01",
computerNamePrefix: "testfleet",
},
securityProfile: {
securityType: "TrustedLaunch",
uefiSettings: {
secureBootEnabled: true,
vTpmEnabled: false,
},
},
networkProfile: {
networkApiVersion: "2020-11-01",
networkInterfaceConfigurations: [
{
name: "testnsg",
properties: {
primary: true,
enableAcceleratedNetworking: false,
networkSecurityGroup: {
id:
"/subscriptions/" +
subscriptionId +
"/resourceGroups/myjstest/providers/Microsoft.Network/networkSecurityGroups/testnsg",
},
ipConfigurations: [
{
name: "testvn-ipConfig",
properties: {
primary: true,
subnet: {
id:
"/subscriptions/" +
subscriptionId +
"/resourceGroups/myjstest/providers/Microsoft.Network/virtualNetworks/czwtestvn/subnets/testsub",
},
},
},
],
},
},
],
},
},
platformFaultDomainCount: 1,
computeApiVersion: "2023-09-01",
},
},
},
testPollingOptions,
);
assert.equal(res.name, resourcename);
});
it("fleets get test", async function () {
const res = await client.fleets.get(resourceGroup, resourcename);
assert.equal(res.name, resourcename);
});
it("fleets list test", async function () {
const resArray = new Array();
for await (let item of client.fleets.listByResourceGroup(resourceGroup)) {
resArray.push(item);
}
assert.equal(resArray.length, 1);
});
it("fleets delete test", async function () {
const resArray = new Array();
const res = await client.fleets.delete(resourceGroup, resourcename);
for await (let item of client.fleets.listByResourceGroup(resourceGroup)) {
resArray.push(item);
}
assert.equal(resArray.length, 0);
});
it("operation list test", async function () {
const resArray = new Array();
for await (let item of client.operations.list()) {
resArray.push(item);
}
assert.notEqual(resArray.length, 0);
});
});

Просмотреть файл

@ -0,0 +1,27 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { Recorder, RecorderStartOptions, VitestTestContext } from "@azure-tools/test-recorder";
const replaceableVariables: Record<string, string> = {
SUBSCRIPTION_ID: "azure_subscription_id",
};
const recorderEnvSetup: RecorderStartOptions = {
envSetupForPlayback: replaceableVariables,
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
],
};
/**
* 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: VitestTestContext): Promise<Recorder> {
const recorder = new Recorder(context);
await recorder.start(recorderEnvSetup);
return recorder;
}

Просмотреть файл

@ -0,0 +1,10 @@
{
"extends": "./.tshy/build.json",
"include": ["./src/**/*.ts", "./src/**/*.mts", "./test/**/*.spec.ts"],
"exclude": ["./test/**/node/**/*.ts"],
"compilerOptions": {
"outDir": "./dist-test/browser",
"rootDir": ".",
"skipLibCheck": true
}
}

Просмотреть файл

@ -0,0 +1,9 @@
{
"extends": "../../../tsconfig",
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "."
},
"include": ["./src/**/*.ts", "./src/**/*.mts", "./src/**/*.cts", "test/**/*.ts", "./test/**/*.ts"]
}

Просмотреть файл

@ -0,0 +1,3 @@
directory: specification/azurefleet/AzureFleet.Management
commit: b75726f11c9af676feef91a67ea7e5365b3b111d
repo: Azure/azure-rest-api-specs

Просмотреть файл

@ -0,0 +1,37 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { defineConfig } from "vitest/config";
import { relativeRecordingsPath } from "@azure-tools/test-recorder";
process.env.RECORDINGS_RELATIVE_PATH = relativeRecordingsPath();
export default defineConfig({
define: {
"process.env": process.env,
},
test: {
reporters: ["basic", "junit"],
outputFile: {
junit: "test-results.browser.xml",
},
browser: {
enabled: true,
headless: true,
name: "chromium",
provider: "playwright",
},
fakeTimers: {
toFake: ["setTimeout", "Date"],
},
watch: false,
include: ["dist-test/browser/**/*.spec.js"],
coverage: {
include: ["dist-test/browser/**/*.spec.js"],
provider: "istanbul",
reporter: ["text", "json", "html"],
reportsDirectory: "coverage-browser",
},
testTimeout: 1200000,
},
});

Просмотреть файл

@ -0,0 +1,33 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { defineConfig } from "vitest/config";
import { relativeRecordingsPath } from "@azure-tools/test-recorder";
export default defineConfig({
test: {
reporters: ["basic", "junit"],
outputFile: {
junit: "test-results.browser.xml",
},
fakeTimers: {
toFake: ["setTimeout", "Date"],
},
watch: false,
include: ["test/**/*.spec.ts"],
exclude: ["test/**/browser/*.spec.ts"],
coverage: {
include: ["src/**/*.ts"],
exclude: [
"src/**/*-browser.mts",
"src/**/*-react-native.mts",
"vitest*.config.ts",
"samples-dev/**/*.ts",
],
provider: "istanbul",
reporter: ["text", "json", "html"],
reportsDirectory: "coverage",
},
testTimeout: 1200000,
},
});

Просмотреть файл

@ -0,0 +1,37 @@
# 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/computefleet/arm-computefleet
- sdk/computefleet/ci.mgmt.yml
pr:
branches:
include:
- main
- feature/*
- release/*
- hotfix/*
exclude:
- feature/v4
paths:
include:
- sdk/computefleet/arm-computefleet
- sdk/computefleet/ci.mgmt.yml
extends:
template: /eng/pipelines/templates/stages/archetype-sdk-client.yml
parameters:
ServiceDirectory: computefleet
Artifacts:
- name: azure-arm-computefleet
safeName: azurearmcomputefleet