diff --git a/.vscode/settings.json b/.vscode/settings.json index 7789a2fa74..cf58813aac 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -10,9 +10,12 @@ } }, "[typescript]": { - "editor.defaultFormatter": "esbenp.prettier-vscode" + "editor.defaultFormatter": "vscode.typescript-language-features" }, "[powershell]": { "editor.defaultFormatter": "ms-vscode.powershell" + }, + "[javascript]": { + "editor.defaultFormatter": "rvest.vs-code-prettier-eslint" } } diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index b95b0321aa..2385643ce9 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -271,7 +271,7 @@ importers: mkdirp: ^3.0.1 mocha: ^10.4.0 npm-run-all: ~4.1.5 - prettier: ^3.1.0 + prettier: ^3.3.3 rimraf: ^5.0.0 ts-morph: ^23.0.0 ts-node: ~10.9.1 @@ -283,7 +283,7 @@ importers: '@azure-tools/rlc-common': link:../rlc-common fs-extra: 11.1.1 lodash: 4.17.21 - prettier: 3.1.1 + prettier: 3.3.3 ts-morph: 23.0.0 tslib: 2.6.2 devDependencies: diff --git a/packages/rlc-common/src/helpers/nameConstructors.ts b/packages/rlc-common/src/helpers/nameConstructors.ts index fe0a70449d..08e0f9e66d 100644 --- a/packages/rlc-common/src/helpers/nameConstructors.ts +++ b/packages/rlc-common/src/helpers/nameConstructors.ts @@ -124,14 +124,10 @@ export function getImportModuleName(name: ModuleName, codeModel: RLCModel) { export function getClientName(model: RLCModel) { const clientName = model.libraryName; - let clientInterfaceName = clientName.endsWith("Client") + const clientInterfaceName = clientName.endsWith("Client") ? `${clientName}` : `${clientName}Client`; - if (model.options?.isModularLibrary) { - clientInterfaceName = `${clientName.replace("Client", "")}Context`; - } - return clientInterfaceName; } diff --git a/packages/rlc-common/src/helpers/nameUtils.ts b/packages/rlc-common/src/helpers/nameUtils.ts index 66d94e5e63..9a02df4ee1 100644 --- a/packages/rlc-common/src/helpers/nameUtils.ts +++ b/packages/rlc-common/src/helpers/nameUtils.ts @@ -87,6 +87,7 @@ export const ReservedModelNames: ReservedName[] = [ { name: "with", reservedFor: [NameType.Parameter] }, { name: "yield", reservedFor: [NameType.Parameter] }, { name: "arguments", reservedFor: [NameType.Parameter] }, + { name: "global", reservedFor: [...Newable] }, // reserve client for codegen { name: "client", reservedFor: [NameType.Parameter] }, { name: "endpoint", reservedFor: [NameType.Parameter] }, diff --git a/packages/rlc-common/src/metadata/buildReadmeFile.ts b/packages/rlc-common/src/metadata/buildReadmeFile.ts index 8366c61e78..9f947ea770 100644 --- a/packages/rlc-common/src/metadata/buildReadmeFile.ts +++ b/packages/rlc-common/src/metadata/buildReadmeFile.ts @@ -7,6 +7,7 @@ import { RLCModel } from "../interfaces.js"; import hbs from "handlebars"; import { NameType, normalizeName } from "../helpers/nameUtils.js"; import { isAzurePackage } from "../helpers/packageUtil.js"; +import { getClientName } from "../helpers/nameConstructors.js"; const azureReadmeRLCTemplate = `# {{ clientDescriptiveName }} library for JavaScript @@ -430,10 +431,3 @@ function getServiceName(model: RLCModel) { : `Azure ${simpleServiceName}` : simpleServiceName; } - -function getClientName(model: RLCModel) { - const clientName = model.libraryName; - return clientName.endsWith("Client") - ? `${clientName}` - : `${clientName}Client`; -} diff --git a/packages/typespec-test/eng/smoke-test.js b/packages/typespec-test/eng/smoke-test.js index a19e14546e..e16fee4135 100644 --- a/packages/typespec-test/eng/smoke-test.js +++ b/packages/typespec-test/eng/smoke-test.js @@ -74,8 +74,11 @@ async function generate(path, logger) { // Clean up the folder before generation if (await exists(join(path, "generated", "typespec-ts"))) { - const pathToRemove = join(path, "generated", "typespec-ts"); - await rm(pathToRemove, { recursive: true, force: true }); + fstat.readdirSync(join(path, "generated", "typespec-ts")).forEach((file) => { + if(file !== "node_modules") { + rm(join(path, "generated", "typespec-ts", file), { recursive: true, force: true }); + } + }); } } catch (e) { // do nothing diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/review/arm-networkanalytics.api.md b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/review/arm-networkanalytics.api.md index a37c77e0b8..a8c9a0a0d4 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/review/arm-networkanalytics.api.md +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/review/arm-networkanalytics.api.md @@ -554,9 +554,6 @@ export interface UserAssignedIdentity { readonly principalId?: string; } -// @public -export type Versions = "2023-11-15"; - // @public export interface VirtualNetworkRule { action?: string; diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProducts/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProducts/index.ts index 7f6fe75fcf..8618b2b551 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProducts/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProducts/index.ts @@ -2,46 +2,54 @@ // Licensed under the MIT License. import { - dataProductPropertiesSerializer, - managedServiceIdentityV4Serializer, - dataProductUpdatePropertiesSerializer, + NetworkAnalyticsContext as Client, + DataProductsAddUserRoleOptionalParams, + DataProductsCreateOptionalParams, + DataProductsDeleteOptionalParams, + DataProductsGenerateStorageAccountSasTokenOptionalParams, + DataProductsGetOptionalParams, + DataProductsListByResourceGroupOptionalParams, + DataProductsListBySubscriptionOptionalParams, + DataProductsListRolesAssignmentsOptionalParams, + DataProductsRemoveUserRoleOptionalParams, + DataProductsRotateKeyOptionalParams, + DataProductsUpdateOptionalParams, +} from "../index.js"; +import { DataProduct, + dataProductSerializer, + dataProductDeserializer, DataProductUpdate, + dataProductUpdateSerializer, AccountSas, + accountSasSerializer, AccountSasToken, + accountSasTokenDeserializer, KeyVaultInfo, + keyVaultInfoSerializer, RoleAssignmentCommonProperties, + roleAssignmentCommonPropertiesSerializer, RoleAssignmentDetail, + roleAssignmentDetailSerializer, + roleAssignmentDetailDeserializer, + _listRolesAssignmentsRequestSerializer, ListRoleAssignments, + listRoleAssignmentsDeserializer, _DataProductListResult, + _dataProductListResultDeserializer, } from "../../models/models.js"; -import { NetworkAnalyticsContext as Client } from "../index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; -import { serializeRecord } from "../../helpers/serializerHelpers.js"; import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../../static-helpers/pagingHelpers.js"; import { getLongRunningPoller } from "../../static-helpers/pollingHelpers.js"; -import { PollerLike, OperationState } from "@azure/core-lro"; import { - DataProductsCreateOptionalParams, - DataProductsGetOptionalParams, - DataProductsUpdateOptionalParams, - DataProductsDeleteOptionalParams, - DataProductsGenerateStorageAccountSasTokenOptionalParams, - DataProductsRotateKeyOptionalParams, - DataProductsAddUserRoleOptionalParams, - DataProductsRemoveUserRoleOptionalParams, - DataProductsListRolesAssignmentsOptionalParams, - DataProductsListByResourceGroupOptionalParams, - DataProductsListBySubscriptionOptionalParams, -} from "../../models/options.js"; + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { PollerLike, OperationState } from "@azure/core-lro"; export function _createSend( context: Client, @@ -60,18 +68,7 @@ export function _createSend( ) .put({ ...operationOptionsToRequestParameters(options), - body: { - tags: !resource.tags - ? resource.tags - : (serializeRecord(resource.tags as any) as any), - location: resource["location"], - properties: !resource.properties - ? resource.properties - : dataProductPropertiesSerializer(resource.properties), - identity: !resource.identity - ? resource.identity - : managedServiceIdentityV4Serializer(resource.identity), - }, + body: dataProductSerializer(resource), }); } @@ -83,133 +80,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - tags: result.body["tags"], - location: result.body["location"], - id: result.body["id"], - name: result.body["name"], - type: result.body["type"], - systemData: !result.body.systemData - ? undefined - : { - createdBy: result.body.systemData?.["createdBy"], - createdByType: result.body.systemData?.["createdByType"], - createdAt: - result.body.systemData?.["createdAt"] !== undefined - ? new Date(result.body.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: result.body.systemData?.["lastModifiedBy"], - lastModifiedByType: result.body.systemData?.["lastModifiedByType"], - lastModifiedAt: - result.body.systemData?.["lastModifiedAt"] !== undefined - ? new Date(result.body.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !result.body.properties - ? undefined - : { - resourceGuid: result.body.properties?.["resourceGuid"], - provisioningState: result.body.properties?.["provisioningState"], - publisher: result.body.properties?.["publisher"], - product: result.body.properties?.["product"], - majorVersion: result.body.properties?.["majorVersion"], - owners: result.body.properties?.["owners"], - redundancy: result.body.properties?.["redundancy"], - purviewAccount: result.body.properties?.["purviewAccount"], - purviewCollection: result.body.properties?.["purviewCollection"], - privateLinksEnabled: result.body.properties?.["privateLinksEnabled"], - publicNetworkAccess: result.body.properties?.["publicNetworkAccess"], - customerManagedKeyEncryptionEnabled: - result.body.properties?.["customerManagedKeyEncryptionEnabled"], - customerEncryptionKey: !result.body.properties?.customerEncryptionKey - ? undefined - : { - keyVaultUri: - result.body.properties?.customerEncryptionKey?.[ - "keyVaultUri" - ], - keyName: - result.body.properties?.customerEncryptionKey?.["keyName"], - keyVersion: - result.body.properties?.customerEncryptionKey?.["keyVersion"], - }, - networkacls: !result.body.properties?.networkacls - ? undefined - : { - virtualNetworkRule: result.body.properties?.networkacls?.[ - "virtualNetworkRule" - ].map((p: any) => { - return { - id: p["id"], - action: p["action"], - state: p["state"], - }; - }), - ipRules: result.body.properties?.networkacls?.["ipRules"].map( - (p: any) => { - return { value: p["value"], action: p["action"] }; - }, - ), - allowedQueryIpRangeList: - result.body.properties?.networkacls?.[ - "allowedQueryIpRangeList" - ], - defaultAction: - result.body.properties?.networkacls?.["defaultAction"], - }, - managedResourceGroupConfiguration: !result.body.properties - ?.managedResourceGroupConfiguration - ? undefined - : { - name: result.body.properties - ?.managedResourceGroupConfiguration?.["name"], - location: - result.body.properties?.managedResourceGroupConfiguration?.[ - "location" - ], - }, - availableMinorVersions: - result.body.properties?.["availableMinorVersions"], - currentMinorVersion: result.body.properties?.["currentMinorVersion"], - documentation: result.body.properties?.["documentation"], - consumptionEndpoints: !result.body.properties?.consumptionEndpoints - ? undefined - : { - ingestionUrl: - result.body.properties?.consumptionEndpoints?.[ - "ingestionUrl" - ], - ingestionResourceId: - result.body.properties?.consumptionEndpoints?.[ - "ingestionResourceId" - ], - fileAccessUrl: - result.body.properties?.consumptionEndpoints?.[ - "fileAccessUrl" - ], - fileAccessResourceId: - result.body.properties?.consumptionEndpoints?.[ - "fileAccessResourceId" - ], - queryUrl: - result.body.properties?.consumptionEndpoints?.["queryUrl"], - queryResourceId: - result.body.properties?.consumptionEndpoints?.[ - "queryResourceId" - ], - }, - keyVaultUrl: result.body.properties?.["keyVaultUrl"], - }, - identity: !result.body.identity - ? undefined - : { - principalId: result.body.identity?.["principalId"], - tenantId: result.body.identity?.["tenantId"], - type: result.body.identity?.["type"], - userAssignedIdentities: - result.body.identity?.["userAssignedIdentities"], - }, - }; + return dataProductDeserializer(result.body); } /** Create data product resource. */ @@ -262,133 +133,7 @@ export async function _getDeserialize( throw createRestError(result); } - return { - tags: result.body["tags"], - location: result.body["location"], - id: result.body["id"], - name: result.body["name"], - type: result.body["type"], - systemData: !result.body.systemData - ? undefined - : { - createdBy: result.body.systemData?.["createdBy"], - createdByType: result.body.systemData?.["createdByType"], - createdAt: - result.body.systemData?.["createdAt"] !== undefined - ? new Date(result.body.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: result.body.systemData?.["lastModifiedBy"], - lastModifiedByType: result.body.systemData?.["lastModifiedByType"], - lastModifiedAt: - result.body.systemData?.["lastModifiedAt"] !== undefined - ? new Date(result.body.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !result.body.properties - ? undefined - : { - resourceGuid: result.body.properties?.["resourceGuid"], - provisioningState: result.body.properties?.["provisioningState"], - publisher: result.body.properties?.["publisher"], - product: result.body.properties?.["product"], - majorVersion: result.body.properties?.["majorVersion"], - owners: result.body.properties?.["owners"], - redundancy: result.body.properties?.["redundancy"], - purviewAccount: result.body.properties?.["purviewAccount"], - purviewCollection: result.body.properties?.["purviewCollection"], - privateLinksEnabled: result.body.properties?.["privateLinksEnabled"], - publicNetworkAccess: result.body.properties?.["publicNetworkAccess"], - customerManagedKeyEncryptionEnabled: - result.body.properties?.["customerManagedKeyEncryptionEnabled"], - customerEncryptionKey: !result.body.properties?.customerEncryptionKey - ? undefined - : { - keyVaultUri: - result.body.properties?.customerEncryptionKey?.[ - "keyVaultUri" - ], - keyName: - result.body.properties?.customerEncryptionKey?.["keyName"], - keyVersion: - result.body.properties?.customerEncryptionKey?.["keyVersion"], - }, - networkacls: !result.body.properties?.networkacls - ? undefined - : { - virtualNetworkRule: result.body.properties?.networkacls?.[ - "virtualNetworkRule" - ].map((p: any) => { - return { - id: p["id"], - action: p["action"], - state: p["state"], - }; - }), - ipRules: result.body.properties?.networkacls?.["ipRules"].map( - (p: any) => { - return { value: p["value"], action: p["action"] }; - }, - ), - allowedQueryIpRangeList: - result.body.properties?.networkacls?.[ - "allowedQueryIpRangeList" - ], - defaultAction: - result.body.properties?.networkacls?.["defaultAction"], - }, - managedResourceGroupConfiguration: !result.body.properties - ?.managedResourceGroupConfiguration - ? undefined - : { - name: result.body.properties - ?.managedResourceGroupConfiguration?.["name"], - location: - result.body.properties?.managedResourceGroupConfiguration?.[ - "location" - ], - }, - availableMinorVersions: - result.body.properties?.["availableMinorVersions"], - currentMinorVersion: result.body.properties?.["currentMinorVersion"], - documentation: result.body.properties?.["documentation"], - consumptionEndpoints: !result.body.properties?.consumptionEndpoints - ? undefined - : { - ingestionUrl: - result.body.properties?.consumptionEndpoints?.[ - "ingestionUrl" - ], - ingestionResourceId: - result.body.properties?.consumptionEndpoints?.[ - "ingestionResourceId" - ], - fileAccessUrl: - result.body.properties?.consumptionEndpoints?.[ - "fileAccessUrl" - ], - fileAccessResourceId: - result.body.properties?.consumptionEndpoints?.[ - "fileAccessResourceId" - ], - queryUrl: - result.body.properties?.consumptionEndpoints?.["queryUrl"], - queryResourceId: - result.body.properties?.consumptionEndpoints?.[ - "queryResourceId" - ], - }, - keyVaultUrl: result.body.properties?.["keyVaultUrl"], - }, - identity: !result.body.identity - ? undefined - : { - principalId: result.body.identity?.["principalId"], - tenantId: result.body.identity?.["tenantId"], - type: result.body.identity?.["type"], - userAssignedIdentities: - result.body.identity?.["userAssignedIdentities"], - }, - }; + return dataProductDeserializer(result.body); } /** Retrieve data product resource. */ @@ -426,17 +171,7 @@ export function _updateSend( ) .patch({ ...operationOptionsToRequestParameters(options), - body: { - identity: !properties.identity - ? properties.identity - : managedServiceIdentityV4Serializer(properties.identity), - tags: !properties.tags - ? properties.tags - : (serializeRecord(properties.tags as any) as any), - properties: !properties.properties - ? properties.properties - : dataProductUpdatePropertiesSerializer(properties.properties), - }, + body: dataProductUpdateSerializer(properties), }); } @@ -448,133 +183,7 @@ export async function _updateDeserialize( throw createRestError(result); } - return { - tags: result.body["tags"], - location: result.body["location"], - id: result.body["id"], - name: result.body["name"], - type: result.body["type"], - systemData: !result.body.systemData - ? undefined - : { - createdBy: result.body.systemData?.["createdBy"], - createdByType: result.body.systemData?.["createdByType"], - createdAt: - result.body.systemData?.["createdAt"] !== undefined - ? new Date(result.body.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: result.body.systemData?.["lastModifiedBy"], - lastModifiedByType: result.body.systemData?.["lastModifiedByType"], - lastModifiedAt: - result.body.systemData?.["lastModifiedAt"] !== undefined - ? new Date(result.body.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !result.body.properties - ? undefined - : { - resourceGuid: result.body.properties?.["resourceGuid"], - provisioningState: result.body.properties?.["provisioningState"], - publisher: result.body.properties?.["publisher"], - product: result.body.properties?.["product"], - majorVersion: result.body.properties?.["majorVersion"], - owners: result.body.properties?.["owners"], - redundancy: result.body.properties?.["redundancy"], - purviewAccount: result.body.properties?.["purviewAccount"], - purviewCollection: result.body.properties?.["purviewCollection"], - privateLinksEnabled: result.body.properties?.["privateLinksEnabled"], - publicNetworkAccess: result.body.properties?.["publicNetworkAccess"], - customerManagedKeyEncryptionEnabled: - result.body.properties?.["customerManagedKeyEncryptionEnabled"], - customerEncryptionKey: !result.body.properties?.customerEncryptionKey - ? undefined - : { - keyVaultUri: - result.body.properties?.customerEncryptionKey?.[ - "keyVaultUri" - ], - keyName: - result.body.properties?.customerEncryptionKey?.["keyName"], - keyVersion: - result.body.properties?.customerEncryptionKey?.["keyVersion"], - }, - networkacls: !result.body.properties?.networkacls - ? undefined - : { - virtualNetworkRule: result.body.properties?.networkacls?.[ - "virtualNetworkRule" - ].map((p: any) => { - return { - id: p["id"], - action: p["action"], - state: p["state"], - }; - }), - ipRules: result.body.properties?.networkacls?.["ipRules"].map( - (p: any) => { - return { value: p["value"], action: p["action"] }; - }, - ), - allowedQueryIpRangeList: - result.body.properties?.networkacls?.[ - "allowedQueryIpRangeList" - ], - defaultAction: - result.body.properties?.networkacls?.["defaultAction"], - }, - managedResourceGroupConfiguration: !result.body.properties - ?.managedResourceGroupConfiguration - ? undefined - : { - name: result.body.properties - ?.managedResourceGroupConfiguration?.["name"], - location: - result.body.properties?.managedResourceGroupConfiguration?.[ - "location" - ], - }, - availableMinorVersions: - result.body.properties?.["availableMinorVersions"], - currentMinorVersion: result.body.properties?.["currentMinorVersion"], - documentation: result.body.properties?.["documentation"], - consumptionEndpoints: !result.body.properties?.consumptionEndpoints - ? undefined - : { - ingestionUrl: - result.body.properties?.consumptionEndpoints?.[ - "ingestionUrl" - ], - ingestionResourceId: - result.body.properties?.consumptionEndpoints?.[ - "ingestionResourceId" - ], - fileAccessUrl: - result.body.properties?.consumptionEndpoints?.[ - "fileAccessUrl" - ], - fileAccessResourceId: - result.body.properties?.consumptionEndpoints?.[ - "fileAccessResourceId" - ], - queryUrl: - result.body.properties?.consumptionEndpoints?.["queryUrl"], - queryResourceId: - result.body.properties?.consumptionEndpoints?.[ - "queryResourceId" - ], - }, - keyVaultUrl: result.body.properties?.["keyVaultUrl"], - }, - identity: !result.body.identity - ? undefined - : { - principalId: result.body.identity?.["principalId"], - tenantId: result.body.identity?.["tenantId"], - type: result.body.identity?.["type"], - userAssignedIdentities: - result.body.identity?.["userAssignedIdentities"], - }, - }; + return dataProductDeserializer(result.body); } /** Update data product resource. */ @@ -682,11 +291,7 @@ export function _generateStorageAccountSasTokenSend( ) .post({ ...operationOptionsToRequestParameters(options), - body: { - startTimeStamp: body["startTimeStamp"].toISOString(), - expiryTimeStamp: body["expiryTimeStamp"].toISOString(), - ipAddress: body["ipAddress"], - }, + body: accountSasSerializer(body), }); } @@ -698,9 +303,7 @@ export async function _generateStorageAccountSasTokenDeserialize( throw createRestError(result); } - return { - storageAccountSasToken: result.body["storageAccountSasToken"], - }; + return accountSasTokenDeserializer(result.body); } /** Generate sas token for storage account. */ @@ -742,7 +345,7 @@ export function _rotateKeySend( ) .post({ ...operationOptionsToRequestParameters(options), - body: { keyVaultUrl: body["keyVaultUrl"] }, + body: keyVaultInfoSerializer(body), }); } @@ -794,14 +397,7 @@ export function _addUserRoleSend( ) .post({ ...operationOptionsToRequestParameters(options), - body: { - roleId: body["roleId"], - principalId: body["principalId"], - userName: body["userName"], - dataTypeScope: body["dataTypeScope"], - principalType: body["principalType"], - role: body["role"], - }, + body: roleAssignmentCommonPropertiesSerializer(body), }); } @@ -813,15 +409,7 @@ export async function _addUserRoleDeserialize( throw createRestError(result); } - return { - roleId: result.body["roleId"], - principalId: result.body["principalId"], - userName: result.body["userName"], - dataTypeScope: result.body["dataTypeScope"], - principalType: result.body["principalType"], - role: result.body["role"], - roleAssignmentId: result.body["roleAssignmentId"], - }; + return roleAssignmentDetailDeserializer(result.body); } /** Assign role to the data product. */ @@ -861,15 +449,7 @@ export function _removeUserRoleSend( ) .post({ ...operationOptionsToRequestParameters(options), - body: { - roleId: body["roleId"], - principalId: body["principalId"], - userName: body["userName"], - dataTypeScope: body["dataTypeScope"], - principalType: body["principalType"], - role: body["role"], - roleAssignmentId: body["roleAssignmentId"], - }, + body: roleAssignmentDetailSerializer(body), }); } @@ -921,7 +501,10 @@ export function _listRolesAssignmentsSend( resourceGroupName, dataProductName, ) - .post({ ...operationOptionsToRequestParameters(options), body: body }); + .post({ + ...operationOptionsToRequestParameters(options), + body: _listRolesAssignmentsRequestSerializer(body), + }); } export async function _listRolesAssignmentsDeserialize( @@ -932,22 +515,7 @@ export async function _listRolesAssignmentsDeserialize( throw createRestError(result); } - return { - count: result.body["count"], - roleAssignmentResponse: result.body["roleAssignmentResponse"].map( - (p: any) => { - return { - roleId: p["roleId"], - principalId: p["principalId"], - userName: p["userName"], - dataTypeScope: p["dataTypeScope"], - principalType: p["principalType"], - role: p["role"], - roleAssignmentId: p["roleAssignmentId"], - }; - }, - ), - }; + return listRoleAssignmentsDeserializer(result.body); } /** List user roles associated with the data product. */ @@ -997,124 +565,7 @@ export async function _listByResourceGroupDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - tags: p["tags"], - location: p["location"], - id: p["id"], - name: p["name"], - type: p["type"], - systemData: !p.systemData - ? undefined - : { - createdBy: p.systemData?.["createdBy"], - createdByType: p.systemData?.["createdByType"], - createdAt: - p.systemData?.["createdAt"] !== undefined - ? new Date(p.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: p.systemData?.["lastModifiedBy"], - lastModifiedByType: p.systemData?.["lastModifiedByType"], - lastModifiedAt: - p.systemData?.["lastModifiedAt"] !== undefined - ? new Date(p.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !p.properties - ? undefined - : { - resourceGuid: p.properties?.["resourceGuid"], - provisioningState: p.properties?.["provisioningState"], - publisher: p.properties?.["publisher"], - product: p.properties?.["product"], - majorVersion: p.properties?.["majorVersion"], - owners: p.properties?.["owners"], - redundancy: p.properties?.["redundancy"], - purviewAccount: p.properties?.["purviewAccount"], - purviewCollection: p.properties?.["purviewCollection"], - privateLinksEnabled: p.properties?.["privateLinksEnabled"], - publicNetworkAccess: p.properties?.["publicNetworkAccess"], - customerManagedKeyEncryptionEnabled: - p.properties?.["customerManagedKeyEncryptionEnabled"], - customerEncryptionKey: !p.properties?.customerEncryptionKey - ? undefined - : { - keyVaultUri: - p.properties?.customerEncryptionKey?.["keyVaultUri"], - keyName: p.properties?.customerEncryptionKey?.["keyName"], - keyVersion: - p.properties?.customerEncryptionKey?.["keyVersion"], - }, - networkacls: !p.properties?.networkacls - ? undefined - : { - virtualNetworkRule: p.properties?.networkacls?.[ - "virtualNetworkRule" - ].map((p: any) => { - return { - id: p["id"], - action: p["action"], - state: p["state"], - }; - }), - ipRules: p.properties?.networkacls?.["ipRules"].map( - (p: any) => { - return { value: p["value"], action: p["action"] }; - }, - ), - allowedQueryIpRangeList: - p.properties?.networkacls?.["allowedQueryIpRangeList"], - defaultAction: p.properties?.networkacls?.["defaultAction"], - }, - managedResourceGroupConfiguration: !p.properties - ?.managedResourceGroupConfiguration - ? undefined - : { - name: p.properties?.managedResourceGroupConfiguration?.[ - "name" - ], - location: - p.properties?.managedResourceGroupConfiguration?.[ - "location" - ], - }, - availableMinorVersions: p.properties?.["availableMinorVersions"], - currentMinorVersion: p.properties?.["currentMinorVersion"], - documentation: p.properties?.["documentation"], - consumptionEndpoints: !p.properties?.consumptionEndpoints - ? undefined - : { - ingestionUrl: - p.properties?.consumptionEndpoints?.["ingestionUrl"], - ingestionResourceId: - p.properties?.consumptionEndpoints?.[ - "ingestionResourceId" - ], - fileAccessUrl: - p.properties?.consumptionEndpoints?.["fileAccessUrl"], - fileAccessResourceId: - p.properties?.consumptionEndpoints?.[ - "fileAccessResourceId" - ], - queryUrl: p.properties?.consumptionEndpoints?.["queryUrl"], - queryResourceId: - p.properties?.consumptionEndpoints?.["queryResourceId"], - }, - keyVaultUrl: p.properties?.["keyVaultUrl"], - }, - identity: !p.identity - ? undefined - : { - principalId: p.identity?.["principalId"], - tenantId: p.identity?.["tenantId"], - type: p.identity?.["type"], - userAssignedIdentities: p.identity?.["userAssignedIdentities"], - }, - }; - }), - nextLink: result.body["nextLink"], - }; + return _dataProductListResultDeserializer(result.body); } /** List data products by resource group. */ @@ -1164,124 +615,7 @@ export async function _listBySubscriptionDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - tags: p["tags"], - location: p["location"], - id: p["id"], - name: p["name"], - type: p["type"], - systemData: !p.systemData - ? undefined - : { - createdBy: p.systemData?.["createdBy"], - createdByType: p.systemData?.["createdByType"], - createdAt: - p.systemData?.["createdAt"] !== undefined - ? new Date(p.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: p.systemData?.["lastModifiedBy"], - lastModifiedByType: p.systemData?.["lastModifiedByType"], - lastModifiedAt: - p.systemData?.["lastModifiedAt"] !== undefined - ? new Date(p.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !p.properties - ? undefined - : { - resourceGuid: p.properties?.["resourceGuid"], - provisioningState: p.properties?.["provisioningState"], - publisher: p.properties?.["publisher"], - product: p.properties?.["product"], - majorVersion: p.properties?.["majorVersion"], - owners: p.properties?.["owners"], - redundancy: p.properties?.["redundancy"], - purviewAccount: p.properties?.["purviewAccount"], - purviewCollection: p.properties?.["purviewCollection"], - privateLinksEnabled: p.properties?.["privateLinksEnabled"], - publicNetworkAccess: p.properties?.["publicNetworkAccess"], - customerManagedKeyEncryptionEnabled: - p.properties?.["customerManagedKeyEncryptionEnabled"], - customerEncryptionKey: !p.properties?.customerEncryptionKey - ? undefined - : { - keyVaultUri: - p.properties?.customerEncryptionKey?.["keyVaultUri"], - keyName: p.properties?.customerEncryptionKey?.["keyName"], - keyVersion: - p.properties?.customerEncryptionKey?.["keyVersion"], - }, - networkacls: !p.properties?.networkacls - ? undefined - : { - virtualNetworkRule: p.properties?.networkacls?.[ - "virtualNetworkRule" - ].map((p: any) => { - return { - id: p["id"], - action: p["action"], - state: p["state"], - }; - }), - ipRules: p.properties?.networkacls?.["ipRules"].map( - (p: any) => { - return { value: p["value"], action: p["action"] }; - }, - ), - allowedQueryIpRangeList: - p.properties?.networkacls?.["allowedQueryIpRangeList"], - defaultAction: p.properties?.networkacls?.["defaultAction"], - }, - managedResourceGroupConfiguration: !p.properties - ?.managedResourceGroupConfiguration - ? undefined - : { - name: p.properties?.managedResourceGroupConfiguration?.[ - "name" - ], - location: - p.properties?.managedResourceGroupConfiguration?.[ - "location" - ], - }, - availableMinorVersions: p.properties?.["availableMinorVersions"], - currentMinorVersion: p.properties?.["currentMinorVersion"], - documentation: p.properties?.["documentation"], - consumptionEndpoints: !p.properties?.consumptionEndpoints - ? undefined - : { - ingestionUrl: - p.properties?.consumptionEndpoints?.["ingestionUrl"], - ingestionResourceId: - p.properties?.consumptionEndpoints?.[ - "ingestionResourceId" - ], - fileAccessUrl: - p.properties?.consumptionEndpoints?.["fileAccessUrl"], - fileAccessResourceId: - p.properties?.consumptionEndpoints?.[ - "fileAccessResourceId" - ], - queryUrl: p.properties?.consumptionEndpoints?.["queryUrl"], - queryResourceId: - p.properties?.consumptionEndpoints?.["queryResourceId"], - }, - keyVaultUrl: p.properties?.["keyVaultUrl"], - }, - identity: !p.identity - ? undefined - : { - principalId: p.identity?.["principalId"], - tenantId: p.identity?.["tenantId"], - type: p.identity?.["type"], - userAssignedIdentities: p.identity?.["userAssignedIdentities"], - }, - }; - }), - nextLink: result.body["nextLink"], - }; + return _dataProductListResultDeserializer(result.body); } /** List data products by subscription. */ diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProductsCatalogs/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProductsCatalogs/index.ts index 19dc8507f0..832580feac 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProductsCatalogs/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProductsCatalogs/index.ts @@ -1,26 +1,28 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + NetworkAnalyticsContext as Client, + DataProductsCatalogsGetOptionalParams, + DataProductsCatalogsListByResourceGroupOptionalParams, + DataProductsCatalogsListBySubscriptionOptionalParams, +} from "../index.js"; import { DataProductsCatalog, + dataProductsCatalogDeserializer, _DataProductsCatalogListResult, + _dataProductsCatalogListResultDeserializer, } from "../../models/models.js"; -import { NetworkAnalyticsContext as Client } from "../index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../../static-helpers/pagingHelpers.js"; import { - DataProductsCatalogsGetOptionalParams, - DataProductsCatalogsListByResourceGroupOptionalParams, - DataProductsCatalogsListBySubscriptionOptionalParams, -} from "../../models/options.js"; + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; export function _getSend( context: Client, @@ -45,48 +47,7 @@ export async function _getDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - name: result.body["name"], - type: result.body["type"], - systemData: !result.body.systemData - ? undefined - : { - createdBy: result.body.systemData?.["createdBy"], - createdByType: result.body.systemData?.["createdByType"], - createdAt: - result.body.systemData?.["createdAt"] !== undefined - ? new Date(result.body.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: result.body.systemData?.["lastModifiedBy"], - lastModifiedByType: result.body.systemData?.["lastModifiedByType"], - lastModifiedAt: - result.body.systemData?.["lastModifiedAt"] !== undefined - ? new Date(result.body.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !result.body.properties - ? undefined - : { - provisioningState: result.body.properties?.["provisioningState"], - publishers: result.body.properties?.["publishers"].map((p: any) => { - return { - publisherName: p["publisherName"], - dataProducts: p["dataProducts"].map((p: any) => { - return { - dataProductName: p["dataProductName"], - description: p["description"], - dataProductVersions: p["dataProductVersions"].map( - (p: any) => { - return { version: p["version"] }; - }, - ), - }; - }), - }; - }), - }, - }; + return dataProductsCatalogDeserializer(result.body); } /** Retrieve data type resource. */ @@ -130,53 +91,7 @@ export async function _listByResourceGroupDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - id: p["id"], - name: p["name"], - type: p["type"], - systemData: !p.systemData - ? undefined - : { - createdBy: p.systemData?.["createdBy"], - createdByType: p.systemData?.["createdByType"], - createdAt: - p.systemData?.["createdAt"] !== undefined - ? new Date(p.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: p.systemData?.["lastModifiedBy"], - lastModifiedByType: p.systemData?.["lastModifiedByType"], - lastModifiedAt: - p.systemData?.["lastModifiedAt"] !== undefined - ? new Date(p.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !p.properties - ? undefined - : { - provisioningState: p.properties?.["provisioningState"], - publishers: p.properties?.["publishers"].map((p: any) => { - return { - publisherName: p["publisherName"], - dataProducts: p["dataProducts"].map((p: any) => { - return { - dataProductName: p["dataProductName"], - description: p["description"], - dataProductVersions: p["dataProductVersions"].map( - (p: any) => { - return { version: p["version"] }; - }, - ), - }; - }), - }; - }), - }, - }; - }), - nextLink: result.body["nextLink"], - }; + return _dataProductsCatalogListResultDeserializer(result.body); } /** List data catalog by resource group. */ @@ -226,53 +141,7 @@ export async function _listBySubscriptionDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - id: p["id"], - name: p["name"], - type: p["type"], - systemData: !p.systemData - ? undefined - : { - createdBy: p.systemData?.["createdBy"], - createdByType: p.systemData?.["createdByType"], - createdAt: - p.systemData?.["createdAt"] !== undefined - ? new Date(p.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: p.systemData?.["lastModifiedBy"], - lastModifiedByType: p.systemData?.["lastModifiedByType"], - lastModifiedAt: - p.systemData?.["lastModifiedAt"] !== undefined - ? new Date(p.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !p.properties - ? undefined - : { - provisioningState: p.properties?.["provisioningState"], - publishers: p.properties?.["publishers"].map((p: any) => { - return { - publisherName: p["publisherName"], - dataProducts: p["dataProducts"].map((p: any) => { - return { - dataProductName: p["dataProductName"], - description: p["description"], - dataProductVersions: p["dataProductVersions"].map( - (p: any) => { - return { version: p["version"] }; - }, - ), - }; - }), - }; - }), - }, - }; - }), - nextLink: result.body["nextLink"], - }; + return _dataProductsCatalogListResultDeserializer(result.body); } /** List data catalog by subscription. */ diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataTypes/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataTypes/index.ts index 12140c6c6f..0e1f70a78f 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataTypes/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataTypes/index.ts @@ -2,36 +2,41 @@ // Licensed under the MIT License. import { - dataTypePropertiesSerializer, - dataTypeUpdatePropertiesSerializer, + NetworkAnalyticsContext as Client, + DataTypesCreateOptionalParams, + DataTypesDeleteDataOptionalParams, + DataTypesDeleteOptionalParams, + DataTypesGenerateStorageContainerSasTokenOptionalParams, + DataTypesGetOptionalParams, + DataTypesListByDataProductOptionalParams, + DataTypesUpdateOptionalParams, +} from "../index.js"; +import { DataType, + dataTypeSerializer, + dataTypeDeserializer, DataTypeUpdate, + dataTypeUpdateSerializer, + _deleteDataRequestSerializer, ContainerSaS, + containerSaSSerializer, ContainerSasToken, + containerSasTokenDeserializer, _DataTypeListResult, + _dataTypeListResultDeserializer, } from "../../models/models.js"; -import { NetworkAnalyticsContext as Client } from "../index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../../static-helpers/pagingHelpers.js"; import { getLongRunningPoller } from "../../static-helpers/pollingHelpers.js"; -import { PollerLike, OperationState } from "@azure/core-lro"; import { - DataTypesCreateOptionalParams, - DataTypesGetOptionalParams, - DataTypesUpdateOptionalParams, - DataTypesDeleteOptionalParams, - DataTypesDeleteDataOptionalParams, - DataTypesGenerateStorageContainerSasTokenOptionalParams, - DataTypesListByDataProductOptionalParams, -} from "../../models/options.js"; + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { PollerLike, OperationState } from "@azure/core-lro"; export function _createSend( context: Client, @@ -52,11 +57,7 @@ export function _createSend( ) .put({ ...operationOptionsToRequestParameters(options), - body: { - properties: !resource.properties - ? resource.properties - : dataTypePropertiesSerializer(resource.properties), - }, + body: dataTypeSerializer(resource), }); } @@ -68,40 +69,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - name: result.body["name"], - type: result.body["type"], - systemData: !result.body.systemData - ? undefined - : { - createdBy: result.body.systemData?.["createdBy"], - createdByType: result.body.systemData?.["createdByType"], - createdAt: - result.body.systemData?.["createdAt"] !== undefined - ? new Date(result.body.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: result.body.systemData?.["lastModifiedBy"], - lastModifiedByType: result.body.systemData?.["lastModifiedByType"], - lastModifiedAt: - result.body.systemData?.["lastModifiedAt"] !== undefined - ? new Date(result.body.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !result.body.properties - ? undefined - : { - provisioningState: result.body.properties?.["provisioningState"], - state: result.body.properties?.["state"], - stateReason: result.body.properties?.["stateReason"], - storageOutputRetention: - result.body.properties?.["storageOutputRetention"], - databaseCacheRetention: - result.body.properties?.["databaseCacheRetention"], - databaseRetention: result.body.properties?.["databaseRetention"], - visualizationUrl: result.body.properties?.["visualizationUrl"], - }, - }; + return dataTypeDeserializer(result.body); } /** Create data type resource. */ @@ -158,40 +126,7 @@ export async function _getDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - name: result.body["name"], - type: result.body["type"], - systemData: !result.body.systemData - ? undefined - : { - createdBy: result.body.systemData?.["createdBy"], - createdByType: result.body.systemData?.["createdByType"], - createdAt: - result.body.systemData?.["createdAt"] !== undefined - ? new Date(result.body.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: result.body.systemData?.["lastModifiedBy"], - lastModifiedByType: result.body.systemData?.["lastModifiedByType"], - lastModifiedAt: - result.body.systemData?.["lastModifiedAt"] !== undefined - ? new Date(result.body.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !result.body.properties - ? undefined - : { - provisioningState: result.body.properties?.["provisioningState"], - state: result.body.properties?.["state"], - stateReason: result.body.properties?.["stateReason"], - storageOutputRetention: - result.body.properties?.["storageOutputRetention"], - databaseCacheRetention: - result.body.properties?.["databaseCacheRetention"], - databaseRetention: result.body.properties?.["databaseRetention"], - visualizationUrl: result.body.properties?.["visualizationUrl"], - }, - }; + return dataTypeDeserializer(result.body); } /** Retrieve data type resource. */ @@ -233,11 +168,7 @@ export function _updateSend( ) .patch({ ...operationOptionsToRequestParameters(options), - body: { - properties: !properties.properties - ? properties.properties - : dataTypeUpdatePropertiesSerializer(properties.properties), - }, + body: dataTypeUpdateSerializer(properties), }); } @@ -249,40 +180,7 @@ export async function _updateDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - name: result.body["name"], - type: result.body["type"], - systemData: !result.body.systemData - ? undefined - : { - createdBy: result.body.systemData?.["createdBy"], - createdByType: result.body.systemData?.["createdByType"], - createdAt: - result.body.systemData?.["createdAt"] !== undefined - ? new Date(result.body.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: result.body.systemData?.["lastModifiedBy"], - lastModifiedByType: result.body.systemData?.["lastModifiedByType"], - lastModifiedAt: - result.body.systemData?.["lastModifiedAt"] !== undefined - ? new Date(result.body.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !result.body.properties - ? undefined - : { - provisioningState: result.body.properties?.["provisioningState"], - state: result.body.properties?.["state"], - stateReason: result.body.properties?.["stateReason"], - storageOutputRetention: - result.body.properties?.["storageOutputRetention"], - databaseCacheRetention: - result.body.properties?.["databaseCacheRetention"], - databaseRetention: result.body.properties?.["databaseRetention"], - visualizationUrl: result.body.properties?.["visualizationUrl"], - }, - }; + return dataTypeDeserializer(result.body); } /** Update data type resource. */ @@ -394,7 +292,10 @@ export function _deleteDataSend( dataProductName, dataTypeName, ) - .post({ ...operationOptionsToRequestParameters(options), body: body }); + .post({ + ...operationOptionsToRequestParameters(options), + body: _deleteDataRequestSerializer(body), + }); } export async function _deleteDataDeserialize( @@ -461,11 +362,7 @@ export function _generateStorageContainerSasTokenSend( ) .post({ ...operationOptionsToRequestParameters(options), - body: { - startTimeStamp: body["startTimeStamp"].toISOString(), - expiryTimeStamp: body["expiryTimeStamp"].toISOString(), - ipAddress: body["ipAddress"], - }, + body: containerSaSSerializer(body), }); } @@ -477,9 +374,7 @@ export async function _generateStorageContainerSasTokenDeserialize( throw createRestError(result); } - return { - storageContainerSasToken: result.body["storageContainerSasToken"], - }; + return containerSasTokenDeserializer(result.body); } /** Generate sas token for storage container. */ @@ -531,43 +426,7 @@ export async function _listByDataProductDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - id: p["id"], - name: p["name"], - type: p["type"], - systemData: !p.systemData - ? undefined - : { - createdBy: p.systemData?.["createdBy"], - createdByType: p.systemData?.["createdByType"], - createdAt: - p.systemData?.["createdAt"] !== undefined - ? new Date(p.systemData?.["createdAt"]) - : undefined, - lastModifiedBy: p.systemData?.["lastModifiedBy"], - lastModifiedByType: p.systemData?.["lastModifiedByType"], - lastModifiedAt: - p.systemData?.["lastModifiedAt"] !== undefined - ? new Date(p.systemData?.["lastModifiedAt"]) - : undefined, - }, - properties: !p.properties - ? undefined - : { - provisioningState: p.properties?.["provisioningState"], - state: p.properties?.["state"], - stateReason: p.properties?.["stateReason"], - storageOutputRetention: p.properties?.["storageOutputRetention"], - databaseCacheRetention: p.properties?.["databaseCacheRetention"], - databaseRetention: p.properties?.["databaseRetention"], - visualizationUrl: p.properties?.["visualizationUrl"], - }, - }; - }), - nextLink: result.body["nextLink"], - }; + return _dataTypeListResultDeserializer(result.body); } /** List data type by parent resource. */ diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/index.ts index 770fdf29dd..40148cb69c 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/index.ts @@ -6,3 +6,27 @@ export { NetworkAnalyticsContext, NetworkAnalyticsClientOptionalParams, } from "./networkAnalyticsContext.js"; +export { + OperationsListOptionalParams, + DataProductsCatalogsGetOptionalParams, + DataProductsCatalogsListByResourceGroupOptionalParams, + DataProductsCatalogsListBySubscriptionOptionalParams, + DataTypesCreateOptionalParams, + DataTypesGetOptionalParams, + DataTypesUpdateOptionalParams, + DataTypesDeleteOptionalParams, + DataTypesDeleteDataOptionalParams, + DataTypesGenerateStorageContainerSasTokenOptionalParams, + DataTypesListByDataProductOptionalParams, + DataProductsCreateOptionalParams, + DataProductsGetOptionalParams, + DataProductsUpdateOptionalParams, + DataProductsDeleteOptionalParams, + DataProductsGenerateStorageAccountSasTokenOptionalParams, + DataProductsRotateKeyOptionalParams, + DataProductsAddUserRoleOptionalParams, + DataProductsRemoveUserRoleOptionalParams, + DataProductsListRolesAssignmentsOptionalParams, + DataProductsListByResourceGroupOptionalParams, + DataProductsListBySubscriptionOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/networkAnalyticsContext.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/networkAnalyticsContext.ts index 3b6fdf64cf..c6ca534a14 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/networkAnalyticsContext.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/networkAnalyticsContext.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { TokenCredential } from "@azure/core-auth"; export interface NetworkAnalyticsContext extends Client {} diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/operations/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/operations/index.ts index 9e77fc8cd7..7b12dfd9dc 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/operations/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/operations/index.ts @@ -1,19 +1,25 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { Operation, _OperationListResult } from "../../models/models.js"; -import { NetworkAnalyticsContext as Client } from "../index.js"; import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; + NetworkAnalyticsContext as Client, + OperationsListOptionalParams, +} from "../index.js"; +import { + _OperationListResult, + _operationListResultDeserializer, + Operation, +} from "../../models/models.js"; import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../../static-helpers/pagingHelpers.js"; -import { OperationsListOptionalParams } from "../../models/options.js"; +import { + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; export function _listSend( context: Client, @@ -32,25 +38,7 @@ export async function _listDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - 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"], - }; + return _operationListResultDeserializer(result.body); } /** List the operations for the provider */ diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProducts/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProducts/index.ts index 3f2c4f734b..5c31e36ded 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProducts/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProducts/index.ts @@ -2,16 +2,6 @@ // Licensed under the MIT License. import { NetworkAnalyticsContext } from "../../api/networkAnalyticsContext.js"; -import { - DataProduct, - DataProductUpdate, - AccountSas, - AccountSasToken, - KeyVaultInfo, - RoleAssignmentCommonProperties, - RoleAssignmentDetail, - ListRoleAssignments, -} from "../../models/models.js"; import { create, get, @@ -25,6 +15,16 @@ import { listByResourceGroup, listBySubscription, } from "../../api/dataProducts/index.js"; +import { + DataProduct, + DataProductUpdate, + AccountSas, + AccountSasToken, + KeyVaultInfo, + RoleAssignmentCommonProperties, + RoleAssignmentDetail, + ListRoleAssignments, +} from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; import { PollerLike, OperationState } from "@azure/core-lro"; import { @@ -39,7 +39,7 @@ import { DataProductsListRolesAssignmentsOptionalParams, DataProductsListByResourceGroupOptionalParams, DataProductsListBySubscriptionOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; /** Interface representing a DataProducts operations. */ export interface DataProductsOperations { diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProductsCatalogs/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProductsCatalogs/index.ts index de43cb67a9..d7048a6b20 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProductsCatalogs/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProductsCatalogs/index.ts @@ -2,18 +2,18 @@ // Licensed under the MIT License. import { NetworkAnalyticsContext } from "../../api/networkAnalyticsContext.js"; -import { DataProductsCatalog } from "../../models/models.js"; import { get, listByResourceGroup, listBySubscription, } from "../../api/dataProductsCatalogs/index.js"; +import { DataProductsCatalog } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; import { DataProductsCatalogsGetOptionalParams, DataProductsCatalogsListByResourceGroupOptionalParams, DataProductsCatalogsListBySubscriptionOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; /** Interface representing a DataProductsCatalogs operations. */ export interface DataProductsCatalogsOperations { diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataTypes/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataTypes/index.ts index e1975bd2ed..ee6fad5bd4 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataTypes/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataTypes/index.ts @@ -2,12 +2,6 @@ // Licensed under the MIT License. import { NetworkAnalyticsContext } from "../../api/networkAnalyticsContext.js"; -import { - DataType, - DataTypeUpdate, - ContainerSaS, - ContainerSasToken, -} from "../../models/models.js"; import { create, get, @@ -17,6 +11,12 @@ import { generateStorageContainerSasToken, listByDataProduct, } from "../../api/dataTypes/index.js"; +import { + DataType, + DataTypeUpdate, + ContainerSaS, + ContainerSasToken, +} from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; import { PollerLike, OperationState } from "@azure/core-lro"; import { @@ -27,7 +27,7 @@ import { DataTypesDeleteDataOptionalParams, DataTypesGenerateStorageContainerSasTokenOptionalParams, DataTypesListByDataProductOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; /** Interface representing a DataTypes operations. */ export interface DataTypesOperations { diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/operations/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/operations/index.ts index aac7b1b524..acc9cd598b 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/operations/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/operations/index.ts @@ -2,10 +2,10 @@ // Licensed under the MIT License. import { NetworkAnalyticsContext } from "../../api/networkAnalyticsContext.js"; -import { Operation } from "../../models/models.js"; import { list } from "../../api/operations/index.js"; +import { OperationsListOptionalParams } from "../../api/options.js"; +import { Operation } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; -import { OperationsListOptionalParams } from "../../models/options.js"; /** Interface representing a Operations operations. */ export interface OperationsOperations { diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/index.ts index f200f3b133..1207d6385b 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/index.ts @@ -7,17 +7,9 @@ import { PagedAsyncIterableIterator, } from "./static-helpers/pagingHelpers.js"; -export { - NetworkAnalyticsClient, - NetworkAnalyticsClientOptionalParams, -} from "./networkAnalyticsClient.js"; +export { NetworkAnalyticsClient } from "./networkAnalyticsClient.js"; export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js"; export { - Resource, - SystemData, - KnownCreatedByType, - CreatedByType, - TrackedResource, DataProduct, DataProductProperties, KnownProvisioningState, @@ -36,6 +28,11 @@ export { KnownManagedServiceIdentityType, ManagedServiceIdentityType, UserAssignedIdentity, + TrackedResource, + Resource, + SystemData, + KnownCreatedByType, + CreatedByType, ErrorResponse, ErrorDetail, ErrorAdditionalInfo, @@ -49,11 +46,11 @@ export { DataProductUserRole, RoleAssignmentDetail, ListRoleAssignments, - ProxyResource, DataType, DataTypeProperties, KnownDataTypeState, DataTypeState, + ProxyResource, DataTypeUpdate, DataTypeUpdateProperties, ContainerSaS, @@ -69,7 +66,9 @@ export { Origin, KnownActionType, ActionType, - Versions, +} from "./models/index.js"; +export { + NetworkAnalyticsClientOptionalParams, OperationsListOptionalParams, DataProductsCatalogsGetOptionalParams, DataProductsCatalogsListByResourceGroupOptionalParams, @@ -92,7 +91,7 @@ export { DataProductsListRolesAssignmentsOptionalParams, DataProductsListByResourceGroupOptionalParams, DataProductsListBySubscriptionOptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; export { DataProductsOperations, DataProductsCatalogsOperations, diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/index.ts index cf435ca752..63a064b63e 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/index.ts @@ -2,11 +2,6 @@ // Licensed under the MIT License. export { - Resource, - SystemData, - KnownCreatedByType, - CreatedByType, - TrackedResource, DataProduct, DataProductProperties, KnownProvisioningState, @@ -25,6 +20,11 @@ export { KnownManagedServiceIdentityType, ManagedServiceIdentityType, UserAssignedIdentity, + TrackedResource, + Resource, + SystemData, + KnownCreatedByType, + CreatedByType, ErrorResponse, ErrorDetail, ErrorAdditionalInfo, @@ -38,11 +38,11 @@ export { DataProductUserRole, RoleAssignmentDetail, ListRoleAssignments, - ProxyResource, DataType, DataTypeProperties, KnownDataTypeState, DataTypeState, + ProxyResource, DataTypeUpdate, DataTypeUpdateProperties, ContainerSaS, @@ -58,29 +58,4 @@ export { Origin, KnownActionType, ActionType, - Versions, } from "./models.js"; -export { - OperationsListOptionalParams, - DataProductsCatalogsGetOptionalParams, - DataProductsCatalogsListByResourceGroupOptionalParams, - DataProductsCatalogsListBySubscriptionOptionalParams, - DataTypesCreateOptionalParams, - DataTypesGetOptionalParams, - DataTypesUpdateOptionalParams, - DataTypesDeleteOptionalParams, - DataTypesDeleteDataOptionalParams, - DataTypesGenerateStorageContainerSasTokenOptionalParams, - DataTypesListByDataProductOptionalParams, - DataProductsCreateOptionalParams, - DataProductsGetOptionalParams, - DataProductsUpdateOptionalParams, - DataProductsDeleteOptionalParams, - DataProductsGenerateStorageAccountSasTokenOptionalParams, - DataProductsRotateKeyOptionalParams, - DataProductsAddUserRoleOptionalParams, - DataProductsRemoveUserRoleOptionalParams, - DataProductsListRolesAssignmentsOptionalParams, - DataProductsListByResourceGroupOptionalParams, - DataProductsListBySubscriptionOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/models.ts index 622aefdb1c..f762cbee21 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/models.ts @@ -1,81 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { serializeRecord } from "../helpers/serializerHelpers.js"; - -/** Common fields that are returned in the response for all Azure Resource Manager resources */ -export interface Resource { - /** Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} */ - readonly id?: string; - /** The name of the resource */ - readonly name?: string; - /** The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" */ - readonly type?: string; - /** Azure Resource Manager metadata containing createdBy and modifiedBy information. */ - readonly systemData?: SystemData; -} - -export function resourceSerializer(item: Resource) { - return item as any; -} - -/** Metadata pertaining to creation and last modification of the resource. */ -export interface SystemData { - /** The identity that created the resource. */ - createdBy?: string; - /** The type of identity that created the resource. */ - createdByType?: CreatedByType; - /** The timestamp of resource creation (UTC). */ - createdAt?: Date; - /** The identity that last modified the resource. */ - lastModifiedBy?: string; - /** The type of identity that last modified the resource. */ - lastModifiedByType?: CreatedByType; - /** The timestamp of resource last modification (UTC) */ - lastModifiedAt?: Date; -} - -/** Known values of {@link CreatedByType} that the service accepts. */ -export enum KnownCreatedByType { - /** User */ - User = "User", - /** Application */ - Application = "Application", - /** ManagedIdentity */ - ManagedIdentity = "ManagedIdentity", - /** Key */ - Key = "Key", -} - -/** - * The kind of entity that created the resource. \ - * {@link KnownCreatedByType} can be used interchangeably with CreatedByType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **User** \ - * **Application** \ - * **ManagedIdentity** \ - * **Key** - */ -export type CreatedByType = string; - -/** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ -export interface TrackedResource extends Resource { - /** Resource tags. */ - tags?: Record; - /** The geo-location where the resource lives */ - location: string; -} - -export function trackedResourceSerializer( - item: TrackedResource, -): Record { - return { - tags: !item.tags ? item.tags : (serializeRecord(item.tags as any) as any), - location: item["location"], - }; -} - /** The data product resource. */ export interface DataProduct extends TrackedResource { /** The resource-specific properties for this resource. */ @@ -84,18 +9,35 @@ export interface DataProduct extends TrackedResource { identity?: ManagedServiceIdentityV4; } -export function dataProductSerializer( - item: DataProduct, -): Record { +export function dataProductSerializer(item: DataProduct): any { return { - tags: !item.tags ? item.tags : (serializeRecord(item.tags as any) as any), + tags: item["tags"], location: item["location"], - properties: !item.properties - ? item.properties - : dataProductPropertiesSerializer(item.properties), - identity: !item.identity - ? item.identity - : managedServiceIdentityV4Serializer(item.identity), + properties: !item["properties"] + ? item["properties"] + : dataProductPropertiesSerializer(item["properties"]), + identity: !item["identity"] + ? item["identity"] + : managedServiceIdentityV4Serializer(item["identity"]), + }; +} + +export function dataProductDeserializer(item: any): DataProduct { + return { + tags: item["tags"], + location: item["location"], + id: item["id"], + name: item["name"], + type: item["type"], + systemData: !item["systemData"] + ? item["systemData"] + : systemDataDeserializer(item["systemData"]), + properties: !item["properties"] + ? item["properties"] + : dataProductPropertiesDeserializer(item["properties"]), + identity: !item["identity"] + ? item["identity"] + : managedServiceIdentityV4Deserializer(item["identity"]), }; } @@ -145,12 +87,16 @@ export interface DataProductProperties { export function dataProductPropertiesSerializer( item: DataProductProperties, -): Record { +): any { return { publisher: item["publisher"], product: item["product"], majorVersion: item["majorVersion"], - owners: item["owners"], + owners: !item["owners"] + ? item["owners"] + : item["owners"].map((p: any) => { + return p; + }), redundancy: item["redundancy"], purviewAccount: item["purviewAccount"], purviewCollection: item["purviewCollection"], @@ -158,36 +104,88 @@ export function dataProductPropertiesSerializer( publicNetworkAccess: item["publicNetworkAccess"], customerManagedKeyEncryptionEnabled: item["customerManagedKeyEncryptionEnabled"], - customerEncryptionKey: !item.customerEncryptionKey - ? item.customerEncryptionKey - : encryptionKeyDetailsSerializer(item.customerEncryptionKey), - networkacls: !item.networkacls - ? item.networkacls - : dataProductNetworkAclsSerializer(item.networkacls), - managedResourceGroupConfiguration: !item.managedResourceGroupConfiguration - ? item.managedResourceGroupConfiguration + customerEncryptionKey: !item["customerEncryptionKey"] + ? item["customerEncryptionKey"] + : encryptionKeyDetailsSerializer(item["customerEncryptionKey"]), + networkacls: !item["networkacls"] + ? item["networkacls"] + : dataProductNetworkAclsSerializer(item["networkacls"]), + managedResourceGroupConfiguration: !item[ + "managedResourceGroupConfiguration" + ] + ? item["managedResourceGroupConfiguration"] : managedResourceGroupConfigurationSerializer( - item.managedResourceGroupConfiguration, + item["managedResourceGroupConfiguration"], ), currentMinorVersion: item["currentMinorVersion"], }; } -/** Known values of {@link ProvisioningState} that the service accepts. */ +export function dataProductPropertiesDeserializer( + item: any, +): DataProductProperties { + return { + resourceGuid: item["resourceGuid"], + provisioningState: item["provisioningState"], + publisher: item["publisher"], + product: item["product"], + majorVersion: item["majorVersion"], + owners: !item["owners"] + ? item["owners"] + : item["owners"].map((p: any) => { + return p; + }), + redundancy: item["redundancy"], + purviewAccount: item["purviewAccount"], + purviewCollection: item["purviewCollection"], + privateLinksEnabled: item["privateLinksEnabled"], + publicNetworkAccess: item["publicNetworkAccess"], + customerManagedKeyEncryptionEnabled: + item["customerManagedKeyEncryptionEnabled"], + customerEncryptionKey: !item["customerEncryptionKey"] + ? item["customerEncryptionKey"] + : encryptionKeyDetailsDeserializer(item["customerEncryptionKey"]), + networkacls: !item["networkacls"] + ? item["networkacls"] + : dataProductNetworkAclsDeserializer(item["networkacls"]), + managedResourceGroupConfiguration: !item[ + "managedResourceGroupConfiguration" + ] + ? item["managedResourceGroupConfiguration"] + : managedResourceGroupConfigurationDeserializer( + item["managedResourceGroupConfiguration"], + ), + availableMinorVersions: !item["availableMinorVersions"] + ? item["availableMinorVersions"] + : item["availableMinorVersions"].map((p: any) => { + return p; + }), + currentMinorVersion: item["currentMinorVersion"], + documentation: item["documentation"], + consumptionEndpoints: !item["consumptionEndpoints"] + ? item["consumptionEndpoints"] + : consumptionEndpointsPropertiesDeserializer( + item["consumptionEndpoints"], + ), + keyVaultUrl: item["keyVaultUrl"], + }; +} + +/** The status of the current operation. */ export enum KnownProvisioningState { - /** Succeeded */ + /** Represents a succeeded operation. */ Succeeded = "Succeeded", - /** Failed */ + /** Represents a failed operation. */ Failed = "Failed", - /** Canceled */ + /** Represents a canceled operation. */ Canceled = "Canceled", - /** Provisioning */ + /** Represents a pending operation. */ Provisioning = "Provisioning", - /** Updating */ + /** Represents a pending operation. */ Updating = "Updating", - /** Deleting */ + /** Represents an operation under deletion. */ Deleting = "Deleting", - /** Accepted */ + /** Represents an accepted operation. */ Accepted = "Accepted", } @@ -196,21 +194,21 @@ export enum KnownProvisioningState { * {@link KnownProvisioningState} can be used interchangeably with ProvisioningState, * this enum contains the known values that the service supports. * ### Known values supported by the service - * **Succeeded** \ - * **Failed** \ - * **Canceled** \ - * **Provisioning** \ - * **Updating** \ - * **Deleting** \ - * **Accepted** + * **Succeeded**: Represents a succeeded operation. \ + * **Failed**: Represents a failed operation. \ + * **Canceled**: Represents a canceled operation. \ + * **Provisioning**: Represents a pending operation. \ + * **Updating**: Represents a pending operation. \ + * **Deleting**: Represents an operation under deletion. \ + * **Accepted**: Represents an accepted operation. */ export type ProvisioningState = string; -/** Known values of {@link ControlState} that the service accepts. */ +/** The data type state */ export enum KnownControlState { - /** Enabled */ + /** Field to enable a setting. */ Enabled = "Enabled", - /** Disabled */ + /** Field to disable a setting. */ Disabled = "Disabled", } @@ -219,8 +217,8 @@ export enum KnownControlState { * {@link KnownControlState} can be used interchangeably with ControlState, * this enum contains the known values that the service supports. * ### Known values supported by the service - * **Enabled** \ - * **Disabled** + * **Enabled**: Field to enable a setting. \ + * **Disabled**: Field to disable a setting. */ export type ControlState = string; @@ -236,7 +234,17 @@ export interface EncryptionKeyDetails { export function encryptionKeyDetailsSerializer( item: EncryptionKeyDetails, -): Record { +): any { + return { + keyVaultUri: item["keyVaultUri"], + keyName: item["keyName"], + keyVersion: item["keyVersion"], + }; +} + +export function encryptionKeyDetailsDeserializer( + item: any, +): EncryptionKeyDetails { return { keyVaultUri: item["keyVaultUri"], keyName: item["keyName"], @@ -258,13 +266,30 @@ export interface DataProductNetworkAcls { export function dataProductNetworkAclsSerializer( item: DataProductNetworkAcls, -): Record { +): any { + return { + virtualNetworkRule: virtualNetworkRuleArraySerializer( + item["virtualNetworkRule"], + ), + ipRules: iPRulesArraySerializer(item["ipRules"]), + allowedQueryIpRangeList: item["allowedQueryIpRangeList"].map((p: any) => { + return p; + }), + defaultAction: item["defaultAction"], + }; +} + +export function dataProductNetworkAclsDeserializer( + item: any, +): DataProductNetworkAcls { return { - virtualNetworkRule: item["virtualNetworkRule"].map( - virtualNetworkRuleSerializer, + virtualNetworkRule: virtualNetworkRuleArrayDeserializer( + item["virtualNetworkRule"], ), - ipRules: item["ipRules"].map(iPRulesSerializer), - allowedQueryIpRangeList: item["allowedQueryIpRangeList"], + ipRules: iPRulesArrayDeserializer(item["ipRules"]), + allowedQueryIpRangeList: item["allowedQueryIpRangeList"].map((p: any) => { + return p; + }), defaultAction: item["defaultAction"], }; } @@ -279,9 +304,11 @@ export interface VirtualNetworkRule { state?: string; } -export function virtualNetworkRuleSerializer( - item: VirtualNetworkRule, -): Record { +export function virtualNetworkRuleSerializer(item: VirtualNetworkRule): any { + return { id: item["id"], action: item["action"], state: item["state"] }; +} + +export function virtualNetworkRuleDeserializer(item: any): VirtualNetworkRule { return { id: item["id"], action: item["action"], @@ -289,6 +316,22 @@ export function virtualNetworkRuleSerializer( }; } +export function virtualNetworkRuleArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return virtualNetworkRuleSerializer(item); + }); +} + +export function virtualNetworkRuleArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return virtualNetworkRuleDeserializer(item); + }); +} + /** IP rule with specific IP or IP range in CIDR format. */ export interface IPRules { /** IP Rules Value */ @@ -297,18 +340,34 @@ export interface IPRules { action: string; } -export function iPRulesSerializer(item: IPRules): Record { +export function iPRulesSerializer(item: IPRules): any { + return { value: item["value"], action: item["action"] }; +} + +export function iPRulesDeserializer(item: any): IPRules { return { value: item["value"], action: item["action"], }; } -/** Known values of {@link DefaultAction} that the service accepts. */ +export function iPRulesArraySerializer(result: Array): any[] { + return result.map((item) => { + return iPRulesSerializer(item); + }); +} + +export function iPRulesArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return iPRulesDeserializer(item); + }); +} + +/** Specifies the default action of allow or deny when no other rules match. */ export enum KnownDefaultAction { - /** Allow */ + /** Represents allow action. */ Allow = "Allow", - /** Deny */ + /** Represents deny action. */ Deny = "Deny", } @@ -317,8 +376,8 @@ export enum KnownDefaultAction { * {@link KnownDefaultAction} can be used interchangeably with DefaultAction, * this enum contains the known values that the service supports. * ### Known values supported by the service - * **Allow** \ - * **Deny** + * **Allow**: Represents allow action. \ + * **Deny**: Represents deny action. */ export type DefaultAction = string; @@ -332,7 +391,13 @@ export interface ManagedResourceGroupConfiguration { export function managedResourceGroupConfigurationSerializer( item: ManagedResourceGroupConfiguration, -): Record { +): any { + return { name: item["name"], location: item["location"] }; +} + +export function managedResourceGroupConfigurationDeserializer( + item: any, +): ManagedResourceGroupConfiguration { return { name: item["name"], location: item["location"], @@ -355,6 +420,19 @@ export interface ConsumptionEndpointsProperties { readonly queryResourceId?: string; } +export function consumptionEndpointsPropertiesDeserializer( + item: any, +): ConsumptionEndpointsProperties { + return { + ingestionUrl: item["ingestionUrl"], + ingestionResourceId: item["ingestionResourceId"], + fileAccessUrl: item["fileAccessUrl"], + fileAccessResourceId: item["fileAccessResourceId"], + queryUrl: item["queryUrl"], + queryResourceId: item["queryResourceId"], + }; +} + /** Managed service identity (system assigned and/or user assigned identities) */ export interface ManagedServiceIdentityV4 { /** The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. */ @@ -369,27 +447,37 @@ export interface ManagedServiceIdentityV4 { export function managedServiceIdentityV4Serializer( item: ManagedServiceIdentityV4, -): Record { +): any { return { type: item["type"], - userAssignedIdentities: !item.userAssignedIdentities - ? item.userAssignedIdentities - : (serializeRecord( - item.userAssignedIdentities as any, - userAssignedIdentitySerializer, - ) as any), + userAssignedIdentities: !item["userAssignedIdentities"] + ? item["userAssignedIdentities"] + : userAssignedIdentityRecordSerializer(item["userAssignedIdentities"]), }; } -/** Known values of {@link ManagedServiceIdentityType} that the service accepts. */ +export function managedServiceIdentityV4Deserializer( + item: any, +): ManagedServiceIdentityV4 { + return { + principalId: item["principalId"], + tenantId: item["tenantId"], + type: item["type"], + userAssignedIdentities: !item["userAssignedIdentities"] + ? item["userAssignedIdentities"] + : userAssignedIdentityRecordDeserializer(item["userAssignedIdentities"]), + }; +} + +/** Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). */ export enum KnownManagedServiceIdentityType { - /** None */ + /** No managed identity. */ None = "None", - /** SystemAssigned */ + /** System assigned managed identity. */ SystemAssigned = "SystemAssigned", - /** UserAssigned */ + /** User assigned managed identity. */ UserAssigned = "UserAssigned", - /** SystemAndUserAssigned */ + /** System and user assigned managed identity. */ SystemAndUserAssigned = "SystemAssigned, UserAssigned", } @@ -398,10 +486,10 @@ export enum KnownManagedServiceIdentityType { * {@link KnownManagedServiceIdentityType} can be used interchangeably with ManagedServiceIdentityType, * this enum contains the known values that the service supports. * ### Known values supported by the service - * **None** \ - * **SystemAssigned** \ - * **UserAssigned** \ - * **SystemAssigned, UserAssigned** + * **None**: No managed identity. \ + * **SystemAssigned**: System assigned managed identity. \ + * **UserAssigned**: User assigned managed identity. \ + * **SystemAssigned, UserAssigned**: System and user assigned managed identity. */ export type ManagedServiceIdentityType = string; @@ -413,16 +501,166 @@ export interface UserAssignedIdentity { readonly clientId?: string; } -export function userAssignedIdentitySerializer(item: UserAssignedIdentity) { +export function userAssignedIdentitySerializer( + item: UserAssignedIdentity, +): any { + return item as any; +} + +export function userAssignedIdentityDeserializer( + item: any, +): UserAssignedIdentity { + return { + principalId: item["principalId"], + clientId: item["clientId"], + }; +} + +export function userAssignedIdentityRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : userAssignedIdentitySerializer(item[key]); + }); + return result; +} + +export function userAssignedIdentityRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : userAssignedIdentityDeserializer(item[key]); + }); + return result; +} + +/** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ +export interface TrackedResource extends Resource { + /** Resource tags. */ + tags?: Record; + /** The geo-location where the resource lives */ + location: string; +} + +export function trackedResourceSerializer(item: TrackedResource): any { + return { tags: item["tags"], location: item["location"] }; +} + +export function trackedResourceDeserializer(item: any): TrackedResource { + return { + id: item["id"], + name: item["name"], + type: item["type"], + systemData: !item["systemData"] + ? item["systemData"] + : systemDataDeserializer(item["systemData"]), + tags: item["tags"], + location: item["location"], + }; +} + +/** Common fields that are returned in the response for all Azure Resource Manager resources */ +export interface Resource { + /** Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} */ + readonly id?: string; + /** The name of the resource */ + readonly name?: string; + /** The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" */ + readonly type?: string; + /** Azure Resource Manager metadata containing createdBy and modifiedBy information. */ + readonly systemData?: SystemData; +} + +export function resourceSerializer(item: Resource): any { return item as any; } +export function resourceDeserializer(item: any): Resource { + return { + id: item["id"], + name: item["name"], + type: item["type"], + systemData: !item["systemData"] + ? item["systemData"] + : systemDataDeserializer(item["systemData"]), + }; +} + +/** Metadata pertaining to creation and last modification of the resource. */ +export interface SystemData { + /** The identity that created the resource. */ + createdBy?: string; + /** The type of identity that created the resource. */ + createdByType?: CreatedByType; + /** The timestamp of resource creation (UTC). */ + createdAt?: Date; + /** The identity that last modified the resource. */ + lastModifiedBy?: string; + /** The type of identity that last modified the resource. */ + lastModifiedByType?: CreatedByType; + /** The timestamp of resource last modification (UTC) */ + lastModifiedAt?: Date; +} + +export function systemDataDeserializer(item: any): SystemData { + return { + createdBy: item["createdBy"], + createdByType: item["createdByType"], + createdAt: !item["createdAt"] + ? item["createdAt"] + : new Date(item["createdAt"]), + lastModifiedBy: item["lastModifiedBy"], + lastModifiedByType: item["lastModifiedByType"], + lastModifiedAt: !item["lastModifiedAt"] + ? item["lastModifiedAt"] + : new Date(item["lastModifiedAt"]), + }; +} + +/** The kind of entity that created the resource. */ +export enum KnownCreatedByType { + /** The entity was created by a user. */ + User = "User", + /** The entity was created by an application. */ + Application = "Application", + /** The entity was created by a managed identity. */ + ManagedIdentity = "ManagedIdentity", + /** The entity was created by a key. */ + Key = "Key", +} + +/** + * The kind of entity that created the resource. \ + * {@link KnowncreatedByType} can be used interchangeably with createdByType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **User**: The entity was created by a user. \ + * **Application**: The entity was created by an application. \ + * **ManagedIdentity**: The entity was created by a managed identity. \ + * **Key**: The entity was created by a key. + */ +export type CreatedByType = string; + /** Common error response for all Azure Resource Manager APIs to return error details for failed operations. */ export interface ErrorResponse { /** The error object. */ error?: ErrorDetail; } +export function errorResponseDeserializer(item: any): ErrorResponse { + return { + error: !item["error"] + ? item["error"] + : errorDetailDeserializer(item["error"]), + }; +} + /** The error detail. */ export interface ErrorDetail { /** The error code. */ @@ -437,6 +675,28 @@ export interface ErrorDetail { readonly additionalInfo?: ErrorAdditionalInfo[]; } +export function errorDetailDeserializer(item: any): ErrorDetail { + return { + code: item["code"], + message: item["message"], + target: item["target"], + details: !item["details"] + ? item["details"] + : errorDetailArrayDeserializer(item["details"]), + additionalInfo: !item["additionalInfo"] + ? item["additionalInfo"] + : errorAdditionalInfoArrayDeserializer(item["additionalInfo"]), + }; +} + +export function errorDetailArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return errorDetailDeserializer(item); + }); +} + /** The resource management error additional info. */ export interface ErrorAdditionalInfo { /** The additional info type. */ @@ -445,6 +705,34 @@ export interface ErrorAdditionalInfo { readonly info?: Record; } +export function errorAdditionalInfoDeserializer( + item: any, +): ErrorAdditionalInfo { + return { + type: item["type"], + info: !item["info"] + ? item["info"] + : _errorAdditionalInfoInfoDeserializer(item["info"]), + }; +} + +/** model interface _ErrorAdditionalInfoInfo */ +export interface _ErrorAdditionalInfoInfo {} + +export function _errorAdditionalInfoInfoDeserializer( + item: any, +): _ErrorAdditionalInfoInfo { + return item as any; +} + +export function errorAdditionalInfoArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return errorAdditionalInfoDeserializer(item); + }); +} + /** The type used for update operations of the DataProduct. */ export interface DataProductUpdate { /** The managed service identities assigned to this resource. */ @@ -455,17 +743,15 @@ export interface DataProductUpdate { properties?: DataProductUpdateProperties; } -export function dataProductUpdateSerializer( - item: DataProductUpdate, -): Record { +export function dataProductUpdateSerializer(item: DataProductUpdate): any { return { - identity: !item.identity - ? item.identity - : managedServiceIdentityV4Serializer(item.identity), - tags: !item.tags ? item.tags : (serializeRecord(item.tags as any) as any), - properties: !item.properties - ? item.properties - : dataProductUpdatePropertiesSerializer(item.properties), + identity: !item["identity"] + ? item["identity"] + : managedServiceIdentityV4Serializer(item["identity"]), + tags: item["tags"], + properties: !item["properties"] + ? item["properties"] + : dataProductUpdatePropertiesSerializer(item["properties"]), }; } @@ -485,9 +771,13 @@ export interface DataProductUpdateProperties { export function dataProductUpdatePropertiesSerializer( item: DataProductUpdateProperties, -): Record { +): any { return { - owners: item["owners"], + owners: !item["owners"] + ? item["owners"] + : item["owners"].map((p: any) => { + return p; + }), purviewAccount: item["purviewAccount"], purviewCollection: item["purviewCollection"], privateLinksEnabled: item["privateLinksEnabled"], @@ -505,9 +795,7 @@ export interface AccountSas { ipAddress: string; } -export function accountSasSerializer( - item: AccountSas, -): Record { +export function accountSasSerializer(item: AccountSas): any { return { startTimeStamp: item["startTimeStamp"].toISOString(), expiryTimeStamp: item["expiryTimeStamp"].toISOString(), @@ -521,18 +809,20 @@ export interface AccountSasToken { storageAccountSasToken: string; } +export function accountSasTokenDeserializer(item: any): AccountSasToken { + return { + storageAccountSasToken: item["storageAccountSasToken"], + }; +} + /** Details for KeyVault. */ export interface KeyVaultInfo { /** key vault url. */ keyVaultUrl: string; } -export function keyVaultInfoSerializer( - item: KeyVaultInfo, -): Record { - return { - keyVaultUrl: item["keyVaultUrl"], - }; +export function keyVaultInfoSerializer(item: KeyVaultInfo): any { + return { keyVaultUrl: item["keyVaultUrl"] }; } /** The details for role assignment common properties. */ @@ -553,22 +843,27 @@ export interface RoleAssignmentCommonProperties { export function roleAssignmentCommonPropertiesSerializer( item: RoleAssignmentCommonProperties, -): Record { +): any { return { roleId: item["roleId"], principalId: item["principalId"], userName: item["userName"], - dataTypeScope: item["dataTypeScope"], + dataTypeScope: item["dataTypeScope"].map((p: any) => { + return p; + }), principalType: item["principalType"], role: item["role"], }; } -/** Known values of {@link DataProductUserRole} that the service accepts. */ +/** The data type state */ export enum KnownDataProductUserRole { - /** Reader */ + /** Field to specify user of type Reader. */ Reader = "Reader", - /** SensitiveReader */ + /** + * Field to specify user of type SensitiveReader. + * This user has privileged access to read sensitive data of a data product. + */ SensitiveReader = "SensitiveReader", } @@ -577,8 +872,9 @@ export enum KnownDataProductUserRole { * {@link KnownDataProductUserRole} can be used interchangeably with DataProductUserRole, * this enum contains the known values that the service supports. * ### Known values supported by the service - * **Reader** \ - * **SensitiveReader** + * **Reader**: Field to specify user of type Reader. \ + * **SensitiveReader**: Field to specify user of type SensitiveReader. + * This user has privileged access to read sensitive data of a data product. */ export type DataProductUserRole = string; @@ -602,18 +898,45 @@ export interface RoleAssignmentDetail { export function roleAssignmentDetailSerializer( item: RoleAssignmentDetail, -): Record { +): any { return { roleId: item["roleId"], principalId: item["principalId"], userName: item["userName"], - dataTypeScope: item["dataTypeScope"], + dataTypeScope: item["dataTypeScope"].map((p: any) => { + return p; + }), principalType: item["principalType"], role: item["role"], roleAssignmentId: item["roleAssignmentId"], }; } +export function roleAssignmentDetailDeserializer( + item: any, +): RoleAssignmentDetail { + return { + roleId: item["roleId"], + principalId: item["principalId"], + userName: item["userName"], + dataTypeScope: item["dataTypeScope"].map((p: any) => { + return p; + }), + principalType: item["principalType"], + role: item["role"], + roleAssignmentId: item["roleAssignmentId"], + }; +} + +/** model interface _ListRolesAssignmentsRequest */ +export interface _ListRolesAssignmentsRequest {} + +export function _listRolesAssignmentsRequestSerializer( + item: _ListRolesAssignmentsRequest, +): any { + return item as any; +} + /** list role assignments. */ export interface ListRoleAssignments { /** Count of role assignments. */ @@ -622,6 +945,33 @@ export interface ListRoleAssignments { roleAssignmentResponse: RoleAssignmentDetail[]; } +export function listRoleAssignmentsDeserializer( + item: any, +): ListRoleAssignments { + return { + count: item["count"], + roleAssignmentResponse: roleAssignmentDetailArrayDeserializer( + item["roleAssignmentResponse"], + ), + }; +} + +export function roleAssignmentDetailArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return roleAssignmentDetailSerializer(item); + }); +} + +export function roleAssignmentDetailArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return roleAssignmentDetailDeserializer(item); + }); +} + /** The response of a DataProduct list operation. */ export interface _DataProductListResult { /** The DataProduct items on this page */ @@ -630,11 +980,27 @@ export interface _DataProductListResult { nextLink?: string; } -/** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */ -export interface ProxyResource extends Resource {} +export function _dataProductListResultDeserializer( + item: any, +): _DataProductListResult { + return { + value: dataProductArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} -export function proxyResourceSerializer(item: ProxyResource) { - return item as any; +export function dataProductArraySerializer(result: Array): any[] { + return result.map((item) => { + return dataProductSerializer(item); + }); +} + +export function dataProductArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return dataProductDeserializer(item); + }); } /** The data type resource. */ @@ -643,11 +1009,25 @@ export interface DataType extends ProxyResource { properties?: DataTypeProperties; } -export function dataTypeSerializer(item: DataType): Record { +export function dataTypeSerializer(item: DataType): any { return { - properties: !item.properties - ? item.properties - : dataTypePropertiesSerializer(item.properties), + properties: !item["properties"] + ? item["properties"] + : dataTypePropertiesSerializer(item["properties"]), + }; +} + +export function dataTypeDeserializer(item: any): DataType { + return { + id: item["id"], + name: item["name"], + type: item["type"], + systemData: !item["systemData"] + ? item["systemData"] + : systemDataDeserializer(item["systemData"]), + properties: !item["properties"] + ? item["properties"] + : dataTypePropertiesDeserializer(item["properties"]), }; } @@ -669,22 +1049,32 @@ export interface DataTypeProperties { readonly visualizationUrl?: string; } -export function dataTypePropertiesSerializer( - item: DataTypeProperties, -): Record { +export function dataTypePropertiesSerializer(item: DataTypeProperties): any { + return { + state: item["state"], + storageOutputRetention: item["storageOutputRetention"], + databaseCacheRetention: item["databaseCacheRetention"], + databaseRetention: item["databaseRetention"], + }; +} + +export function dataTypePropertiesDeserializer(item: any): DataTypeProperties { return { + provisioningState: item["provisioningState"], state: item["state"], + stateReason: item["stateReason"], storageOutputRetention: item["storageOutputRetention"], databaseCacheRetention: item["databaseCacheRetention"], databaseRetention: item["databaseRetention"], + visualizationUrl: item["visualizationUrl"], }; } -/** Known values of {@link DataTypeState} that the service accepts. */ +/** The data type state */ export enum KnownDataTypeState { - /** Stopped */ + /** Field to specify stopped state. */ Stopped = "Stopped", - /** Running */ + /** Field to specify running state. */ Running = "Running", } @@ -693,24 +1083,40 @@ export enum KnownDataTypeState { * {@link KnownDataTypeState} can be used interchangeably with DataTypeState, * this enum contains the known values that the service supports. * ### Known values supported by the service - * **Stopped** \ - * **Running** + * **Stopped**: Field to specify stopped state. \ + * **Running**: Field to specify running state. */ export type DataTypeState = string; +/** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */ +export interface ProxyResource extends Resource {} + +export function proxyResourceSerializer(item: ProxyResource): any { + return item as any; +} + +export function proxyResourceDeserializer(item: any): ProxyResource { + return { + id: item["id"], + name: item["name"], + type: item["type"], + systemData: !item["systemData"] + ? item["systemData"] + : systemDataDeserializer(item["systemData"]), + }; +} + /** The type used for update operations of the DataType. */ export interface DataTypeUpdate { /** The resource-specific properties for this resource. */ properties?: DataTypeUpdateProperties; } -export function dataTypeUpdateSerializer( - item: DataTypeUpdate, -): Record { +export function dataTypeUpdateSerializer(item: DataTypeUpdate): any { return { - properties: !item.properties - ? item.properties - : dataTypeUpdatePropertiesSerializer(item.properties), + properties: !item["properties"] + ? item["properties"] + : dataTypeUpdatePropertiesSerializer(item["properties"]), }; } @@ -728,7 +1134,7 @@ export interface DataTypeUpdateProperties { export function dataTypeUpdatePropertiesSerializer( item: DataTypeUpdateProperties, -): Record { +): any { return { state: item["state"], storageOutputRetention: item["storageOutputRetention"], @@ -737,6 +1143,13 @@ export function dataTypeUpdatePropertiesSerializer( }; } +/** model interface _DeleteDataRequest */ +export interface _DeleteDataRequest {} + +export function _deleteDataRequestSerializer(item: _DeleteDataRequest): any { + return item as any; +} + /** The details for container sas creation. */ export interface ContainerSaS { /** Sas token start timestamp. */ @@ -747,9 +1160,7 @@ export interface ContainerSaS { ipAddress: string; } -export function containerSaSSerializer( - item: ContainerSaS, -): Record { +export function containerSaSSerializer(item: ContainerSaS): any { return { startTimeStamp: item["startTimeStamp"].toISOString(), expiryTimeStamp: item["expiryTimeStamp"].toISOString(), @@ -763,6 +1174,12 @@ export interface ContainerSasToken { storageContainerSasToken: string; } +export function containerSasTokenDeserializer(item: any): ContainerSasToken { + return { + storageContainerSasToken: item["storageContainerSasToken"], + }; +} + /** The response of a DataType list operation. */ export interface _DataTypeListResult { /** The DataType items on this page */ @@ -771,12 +1188,49 @@ export interface _DataTypeListResult { nextLink?: string; } +export function _dataTypeListResultDeserializer( + item: any, +): _DataTypeListResult { + return { + value: dataTypeArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function dataTypeArraySerializer(result: Array): any[] { + return result.map((item) => { + return dataTypeSerializer(item); + }); +} + +export function dataTypeArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return dataTypeDeserializer(item); + }); +} + /** The data catalog resource. */ export interface DataProductsCatalog extends ProxyResource { /** The resource-specific properties for this resource. */ properties?: DataProductsCatalogProperties; } +export function dataProductsCatalogDeserializer( + item: any, +): DataProductsCatalog { + return { + id: item["id"], + name: item["name"], + type: item["type"], + systemData: !item["systemData"] + ? item["systemData"] + : systemDataDeserializer(item["systemData"]), + properties: !item["properties"] + ? item["properties"] + : dataProductsCatalogPropertiesDeserializer(item["properties"]), + }; +} + /** Details for data catalog properties. */ export interface DataProductsCatalogProperties { /** The data catalog provisioning state. */ @@ -785,6 +1239,15 @@ export interface DataProductsCatalogProperties { publishers: PublisherInformation[]; } +export function dataProductsCatalogPropertiesDeserializer( + item: any, +): DataProductsCatalogProperties { + return { + provisioningState: item["provisioningState"], + publishers: publisherInformationArrayDeserializer(item["publishers"]), + }; +} + /** Details for Publisher Information. */ export interface PublisherInformation { /** Name of the publisher. */ @@ -793,6 +1256,15 @@ export interface PublisherInformation { dataProducts: DataProductInformation[]; } +export function publisherInformationDeserializer( + item: any, +): PublisherInformation { + return { + publisherName: item["publisherName"], + dataProducts: dataProductInformationArrayDeserializer(item["dataProducts"]), + }; +} + /** Data Product Information */ export interface DataProductInformation { /** Name of data product. */ @@ -803,12 +1275,54 @@ export interface DataProductInformation { dataProductVersions: DataProductVersion[]; } +export function dataProductInformationDeserializer( + item: any, +): DataProductInformation { + return { + dataProductName: item["dataProductName"], + description: item["description"], + dataProductVersions: dataProductVersionArrayDeserializer( + item["dataProductVersions"], + ), + }; +} + /** Data Product Version. */ export interface DataProductVersion { /** Version of data product */ version: string; } +export function dataProductVersionDeserializer(item: any): DataProductVersion { + return { + version: item["version"], + }; +} + +export function dataProductVersionArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return dataProductVersionDeserializer(item); + }); +} + +export function dataProductInformationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return dataProductInformationDeserializer(item); + }); +} + +export function publisherInformationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return publisherInformationDeserializer(item); + }); +} + /** The response of a DataProductsCatalog list operation. */ export interface _DataProductsCatalogListResult { /** The DataProductsCatalog items on this page */ @@ -817,6 +1331,23 @@ export interface _DataProductsCatalogListResult { nextLink?: string; } +export function _dataProductsCatalogListResultDeserializer( + item: any, +): _DataProductsCatalogListResult { + return { + value: dataProductsCatalogArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function dataProductsCatalogArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return dataProductsCatalogDeserializer(item); + }); +} + /** A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. */ export interface _OperationListResult { /** The Operation items on this page */ @@ -825,6 +1356,15 @@ export interface _OperationListResult { nextLink?: string; } +export function _operationListResultDeserializer( + item: any, +): _OperationListResult { + return { + value: operationArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + /** Details of a REST API operation, returned from the Resource Provider Operations API */ export interface Operation { /** The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action" */ @@ -839,6 +1379,18 @@ export interface Operation { actionType?: ActionType; } +export function operationDeserializer(item: any): Operation { + return { + name: item["name"], + isDataAction: item["isDataAction"], + display: !item["display"] + ? item["display"] + : operationDisplayDeserializer(item["display"]), + origin: item["origin"], + actionType: item["actionType"], + }; +} + /** Localized display information for and operation. */ export interface OperationDisplay { /** The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". */ @@ -851,13 +1403,22 @@ export interface OperationDisplay { readonly description?: string; } -/** Known values of {@link Origin} that the service accepts. */ +export function operationDisplayDeserializer(item: any): OperationDisplay { + return { + provider: item["provider"], + resource: item["resource"], + operation: item["operation"], + description: item["description"], + }; +} + +/** The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system" */ export enum KnownOrigin { - /** user */ + /** Indicates the operation is initiated by a user. */ user = "user", - /** system */ + /** Indicates the operation is initiated by a system. */ system = "system", - /** user,system */ + /** Indicates the operation is initiated by a user or system. */ "user,system" = "user,system", } @@ -866,15 +1427,15 @@ export enum KnownOrigin { * {@link KnownOrigin} can be used interchangeably with Origin, * this enum contains the known values that the service supports. * ### Known values supported by the service - * **user** \ - * **system** \ - * **user,system** + * **user**: Indicates the operation is initiated by a user. \ + * **system**: Indicates the operation is initiated by a system. \ + * **user,system**: Indicates the operation is initiated by a user or system. */ export type Origin = string; -/** Known values of {@link ActionType} that the service accepts. */ +/** Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. */ export enum KnownActionType { - /** Internal */ + /** Actions are for internal-only APIs. */ Internal = "Internal", } @@ -883,8 +1444,12 @@ export enum KnownActionType { * {@link KnownActionType} can be used interchangeably with ActionType, * this enum contains the known values that the service supports. * ### Known values supported by the service - * **Internal** + * **Internal**: Actions are for internal-only APIs. */ export type ActionType = string; -/** The available API versions for the Microsoft.NetworkAnalytics RP. */ -export type Versions = "2023-11-15"; + +export function operationArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return operationDeserializer(item); + }); +} diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/networkAnalyticsClient.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/networkAnalyticsClient.ts index 1b188e914f..8baafcecda 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/networkAnalyticsClient.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/networkAnalyticsClient.ts @@ -1,8 +1,6 @@ // 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, @@ -24,6 +22,8 @@ import { NetworkAnalyticsContext, NetworkAnalyticsClientOptionalParams, } from "./api/index.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TokenCredential } from "@azure/core-auth"; export { NetworkAnalyticsClientOptionalParams } from "./api/networkAnalyticsContext.js"; diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/review/ai-anomaly-detector.api.md b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/review/ai-anomaly-detector.api.md index bb11ba69e9..637424c1d1 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/review/ai-anomaly-detector.api.md +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/review/ai-anomaly-detector.api.md @@ -9,9 +9,6 @@ import { KeyCredential } from '@azure/core-auth'; import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; -// @public -export type AlignMode = "Inner" | "Outer"; - // @public (undocumented) export class AnomalyDetectorClient { constructor(endpointParam: string, credential: KeyCredential, options?: AnomalyDetectorClientOptionalParams); @@ -26,7 +23,7 @@ export interface AnomalyDetectorClientOptionalParams extends ClientOptions { } // @public -export type AnomalyDetectorErrorCodes = "InvalidCustomInterval" | "BadArgument" | "InvalidGranularity" | "InvalidPeriod" | "InvalidModelArgument" | "InvalidSeries" | "InvalidJsonFormat" | "RequiredGranularity" | "RequiredSeries" | "InvalidImputeMode" | "InvalidImputeFixedValue"; +export type APIVersion = "v1.1"; // @public export type ContinuablePage = TPage & { @@ -34,21 +31,12 @@ export type ContinuablePage = TPage & { }; // @public -export type DataSchema = "OneTable" | "MultiTable"; - -// @public -export type FillNAMethod = "Previous" | "Subsequent" | "Linear" | "Zero" | "Fixed"; - -// @public -export type ImputeMode = "auto" | "previous" | "linear" | "fixed" | "zero" | "notFill"; - -// @public -export type ModelStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; +export type MultivariateAlignMode = "Inner" | "Outer"; // @public export interface MultivariateAlignPolicy { - alignMode?: AlignMode; - fillNAMethod?: FillNAMethod; + alignMode?: MultivariateAlignMode; + fillNAMethod?: MultivariateFillNAMethod; paddingValue?: number; } @@ -82,14 +70,14 @@ export interface MultivariateAnomalyValue { severity: number; } -// @public -export type MultivariateBatchDetectionStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; - // @public export interface MultivariateCorrelationChanges { changedVariables?: string[]; } +// @public +export type MultivariateDataSchema = "OneTable" | "MultiTable"; + // @public export interface MultivariateDeleteMultivariateModelOptionalParams extends OperationOptions { } @@ -114,6 +102,9 @@ export interface MultivariateErrorResponse { message: string; } +// @public +export type MultivariateFillNAMethod = "Previous" | "Subsequent" | "Linear" | "Zero" | "Fixed"; + // @public export interface MultivariateGetMultivariateBatchDetectionResultOptionalParams extends OperationOptions { } @@ -131,7 +122,7 @@ export interface MultivariateListMultivariateModelsOptionalParams extends Operat // @public export interface MultivariateModelInfo { alignPolicy?: MultivariateAlignPolicy; - dataSchema?: DataSchema; + dataSchema?: MultivariateDataSchema; dataSource: string; diagnosticsInfo?: MultivariateDiagnosticsInfo; displayName?: string; @@ -139,7 +130,7 @@ export interface MultivariateModelInfo { readonly errors?: MultivariateErrorResponse[]; slidingWindow?: number; startTime: Date; - status?: ModelStatus; + status?: MultivariateModelStatus; } // @public @@ -150,6 +141,9 @@ export interface MultivariateModelState { validationLosses?: number[]; } +// @public +export type MultivariateModelStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; + // @public export interface MultivariateMultivariateBatchDetectionOptions { dataSource: string; @@ -162,10 +156,13 @@ export interface MultivariateMultivariateBatchDetectionOptions { export interface MultivariateMultivariateBatchDetectionResultSummary { errors?: MultivariateErrorResponse[]; setupInfo: MultivariateMultivariateBatchDetectionOptions; - status: MultivariateBatchDetectionStatus; + status: MultivariateMultivariateBatchDetectionStatus; variableStates?: MultivariateVariableState[]; } +// @public +export type MultivariateMultivariateBatchDetectionStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; + // @public export interface MultivariateMultivariateDetectionResult { readonly resultId: string; @@ -196,12 +193,6 @@ export interface MultivariateOperations { trainMultivariateModel: (modelInfo: MultivariateModelInfo, options?: MultivariateTrainMultivariateModelOptionalParams) => Promise; } -// @public -export interface MultivariateResponseError { - code: string; - message: string; -} - // @public export interface MultivariateTrainMultivariateModelOptionalParams extends OperationOptions { } @@ -234,15 +225,15 @@ export interface PageSettings { continuationToken?: string; } -// @public -export type TimeGranularity = "yearly" | "monthly" | "weekly" | "daily" | "hourly" | "minutely" | "secondly" | "microsecond" | "none"; - // @public export interface UnivariateAnomalyDetectorError { - code?: AnomalyDetectorErrorCodes; + code?: UnivariateAnomalyDetectorErrorCodes; message?: string; } +// @public +export type UnivariateAnomalyDetectorErrorCodes = "InvalidCustomInterval" | "BadArgument" | "InvalidGranularity" | "InvalidPeriod" | "InvalidModelArgument" | "InvalidSeries" | "InvalidJsonFormat" | "RequiredGranularity" | "RequiredSeries" | "InvalidImputeMode" | "InvalidImputeFixedValue"; + // @public export interface UnivariateDetectUnivariateChangePointOptionalParams extends OperationOptions { } @@ -255,6 +246,9 @@ export interface UnivariateDetectUnivariateEntireSeriesOptionalParams extends Op export interface UnivariateDetectUnivariateLastPointOptionalParams extends OperationOptions { } +// @public +export type UnivariateImputeMode = "auto" | "previous" | "linear" | "fixed" | "zero" | "notFill"; + // @public export interface UnivariateOperations { detectUnivariateChangePoint: (options: UnivariateUnivariateChangePointDetectionOptions, optionalParams?: UnivariateDetectUnivariateChangePointOptionalParams) => Promise; @@ -262,6 +256,9 @@ export interface UnivariateOperations { detectUnivariateLastPoint: (options: UnivariateUnivariateDetectionOptions, optionalParams?: UnivariateDetectUnivariateLastPointOptionalParams) => Promise; } +// @public +export type UnivariateTimeGranularity = "yearly" | "monthly" | "weekly" | "daily" | "hourly" | "minutely" | "secondly" | "microsecond" | "none"; + // @public export interface UnivariateTimeSeriesPoint { timestamp?: Date; @@ -271,7 +268,7 @@ export interface UnivariateTimeSeriesPoint { // @public export interface UnivariateUnivariateChangePointDetectionOptions { customInterval?: number; - granularity: TimeGranularity; + granularity: UnivariateTimeGranularity; period?: number; series: UnivariateTimeSeriesPoint[]; stableTrendWindow?: number; @@ -288,9 +285,9 @@ export interface UnivariateUnivariateChangePointDetectionResult { // @public export interface UnivariateUnivariateDetectionOptions { customInterval?: number; - granularity?: TimeGranularity; + granularity?: UnivariateTimeGranularity; imputeFixedValue?: number; - imputeMode?: ImputeMode; + imputeMode?: UnivariateImputeMode; maxAnomalyRatio?: number; period?: number; sensitivity?: number; @@ -322,9 +319,6 @@ export interface UnivariateUnivariateLastDetectionResult { upperMargin: number; } -// @public -export type Versions = "v1.1"; - // (No @packageDocumentation comment for this package) ``` diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/anomalyDetectorClient.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/anomalyDetectorClient.ts index d28c471858..863b45d313 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/anomalyDetectorClient.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/anomalyDetectorClient.ts @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { KeyCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; import { getUnivariateOperations, UnivariateOperations, @@ -16,6 +14,8 @@ import { AnomalyDetectorContext, AnomalyDetectorClientOptionalParams, } from "./api/index.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { KeyCredential } from "@azure/core-auth"; export { AnomalyDetectorClientOptionalParams } from "./api/anomalyDetectorContext.js"; diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts index c5224dd656..ff15095e55 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts @@ -1,10 +1,28 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { KeyCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { KeyCredential } from "@azure/core-auth"; +/** + * The Anomaly Detector API detects anomalies automatically in time series data. + * It supports two kinds of mode, one is for stateless using, another is for + * stateful using. In stateless mode, there are three functionalities. Entire + * Detect is for detecting the whole series with model trained by the time series, + * Last Detect is detecting last point with model trained by points before. + * ChangePoint Detect is for detecting trend changes in time series. In stateful + * mode, user can store time series, the stored time series will be used for + * detection anomalies. Under this mode, user can still use the above three + * functionalities by only giving a time range without preparing time series in + * client side. Besides the above three functionalities, stateful model also + * provide group based detection and labeling service. By leveraging labeling + * service user can provide labels for each detection result, these labels will be + * used for retuning or regenerating detection models. Inconsistency detection is + * a kind of group based detection, this detection will find inconsistency ones in + * a set of time series. By using anomaly detector service, business customers can + * discover incidents and establish a logic flow for root cause analysis. + */ export interface AnomalyDetectorContext extends Client {} /** Optional parameters for the client. */ diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/index.ts index 8d3268635d..113a94ebf7 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/index.ts @@ -6,3 +6,15 @@ export { AnomalyDetectorContext, AnomalyDetectorClientOptionalParams, } from "./anomalyDetectorContext.js"; +export { + UnivariateDetectUnivariateEntireSeriesOptionalParams, + UnivariateDetectUnivariateLastPointOptionalParams, + UnivariateDetectUnivariateChangePointOptionalParams, + MultivariateGetMultivariateBatchDetectionResultOptionalParams, + MultivariateTrainMultivariateModelOptionalParams, + MultivariateListMultivariateModelsOptionalParams, + MultivariateDeleteMultivariateModelOptionalParams, + MultivariateGetMultivariateModelOptionalParams, + MultivariateDetectMultivariateBatchAnomalyOptionalParams, + MultivariateDetectMultivariateLastAnomalyOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts index 339b2eb62c..8ee761c9ca 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts @@ -2,37 +2,41 @@ // Licensed under the MIT License. import { - multivariateAlignPolicySerializer, - multivariateDiagnosticsInfoSerializer, - multivariateVariableValuesSerializer, + AnomalyDetectorContext as Client, + MultivariateDeleteMultivariateModelOptionalParams, + MultivariateDetectMultivariateBatchAnomalyOptionalParams, + MultivariateDetectMultivariateLastAnomalyOptionalParams, + MultivariateGetMultivariateBatchDetectionResultOptionalParams, + MultivariateGetMultivariateModelOptionalParams, + MultivariateListMultivariateModelsOptionalParams, + MultivariateTrainMultivariateModelOptionalParams, +} from "../index.js"; +import { MultivariateMultivariateDetectionResult, + multivariateMultivariateDetectionResultDeserializer, MultivariateMultivariateBatchDetectionOptions, + multivariateMultivariateBatchDetectionOptionsSerializer, MultivariateModelInfo, + multivariateModelInfoSerializer, MultivariateAnomalyDetectionModel, + multivariateAnomalyDetectionModelDeserializer, + _MultivariateModelList, + _multivariateModelListDeserializer, MultivariateMultivariateLastDetectionOptions, + multivariateMultivariateLastDetectionOptionsSerializer, MultivariateMultivariateLastDetectionResult, - _MultivariateModelList, + multivariateMultivariateLastDetectionResultDeserializer, } from "../../models/models.js"; -import { AnomalyDetectorContext as Client } from "../index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../../static-helpers/pagingHelpers.js"; import { - MultivariateGetMultivariateBatchDetectionResultOptionalParams, - MultivariateTrainMultivariateModelOptionalParams, - MultivariateListMultivariateModelsOptionalParams, - MultivariateDeleteMultivariateModelOptionalParams, - MultivariateGetMultivariateModelOptionalParams, - MultivariateDetectMultivariateBatchAnomalyOptionalParams, - MultivariateDetectMultivariateLastAnomalyOptionalParams, -} from "../../models/options.js"; + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; export function _getMultivariateBatchDetectionResultSend( context: Client, @@ -54,76 +58,7 @@ export async function _getMultivariateBatchDetectionResultDeserialize( throw createRestError(result); } - return { - resultId: result.body["resultId"], - summary: { - status: result.body.summary["status"], - errors: - result.body.summary["errors"] === undefined - ? result.body.summary["errors"] - : result.body.summary["errors"].map((p: any) => { - return { code: p["code"], message: p["message"] }; - }), - variableStates: - result.body.summary["variableStates"] === undefined - ? result.body.summary["variableStates"] - : result.body.summary["variableStates"].map((p: any) => { - return { - variable: p["variable"], - filledNARatio: p["filledNARatio"], - effectiveCount: p["effectiveCount"], - firstTimestamp: - p["firstTimestamp"] !== undefined - ? new Date(p["firstTimestamp"]) - : undefined, - lastTimestamp: - p["lastTimestamp"] !== undefined - ? new Date(p["lastTimestamp"]) - : undefined, - }; - }), - setupInfo: { - dataSource: result.body.summary.setupInfo["dataSource"], - topContributorCount: - result.body.summary.setupInfo["topContributorCount"], - startTime: new Date(result.body.summary.setupInfo["startTime"]), - endTime: new Date(result.body.summary.setupInfo["endTime"]), - }, - }, - results: result.body["results"].map((p: any) => { - return { - timestamp: new Date(p["timestamp"]), - value: !p.value - ? undefined - : { - isAnomaly: p.value?.["isAnomaly"], - severity: p.value?.["severity"], - score: p.value?.["score"], - interpretation: - p.value?.["interpretation"] === undefined - ? p.value?.["interpretation"] - : p.value?.["interpretation"].map((p: any) => { - return { - variable: p["variable"], - contributionScore: p["contributionScore"], - correlationChanges: !p.correlationChanges - ? undefined - : { - changedVariables: - p.correlationChanges?.["changedVariables"], - }, - }; - }), - }, - errors: - p["errors"] === undefined - ? p["errors"] - : p["errors"].map((p: any) => { - return { code: p["code"], message: p["message"] }; - }), - }; - }), - }; + return multivariateMultivariateDetectionResultDeserializer(result.body); } /** @@ -156,21 +91,7 @@ export function _trainMultivariateModelSend( .path("/multivariate/models") .post({ ...operationOptionsToRequestParameters(options), - body: { - dataSource: modelInfo["dataSource"], - dataSchema: modelInfo["dataSchema"], - startTime: modelInfo["startTime"].toISOString(), - endTime: modelInfo["endTime"].toISOString(), - displayName: modelInfo["displayName"], - slidingWindow: modelInfo["slidingWindow"], - alignPolicy: !modelInfo.alignPolicy - ? modelInfo.alignPolicy - : multivariateAlignPolicySerializer(modelInfo.alignPolicy), - status: modelInfo["status"], - diagnosticsInfo: !modelInfo.diagnosticsInfo - ? modelInfo.diagnosticsInfo - : multivariateDiagnosticsInfoSerializer(modelInfo.diagnosticsInfo), - }, + body: multivariateModelInfoSerializer(modelInfo), }); } @@ -182,82 +103,7 @@ export async function _trainMultivariateModelDeserialize( throw createRestError(result); } - return { - modelId: result.body["modelId"], - createdTime: new Date(result.body["createdTime"]), - lastUpdatedTime: new Date(result.body["lastUpdatedTime"]), - modelInfo: !result.body.modelInfo - ? undefined - : { - dataSource: result.body.modelInfo?.["dataSource"], - dataSchema: result.body.modelInfo?.["dataSchema"], - startTime: new Date(result.body.modelInfo?.["startTime"]), - endTime: new Date(result.body.modelInfo?.["endTime"]), - displayName: result.body.modelInfo?.["displayName"], - slidingWindow: result.body.modelInfo?.["slidingWindow"], - alignPolicy: !result.body.modelInfo?.alignPolicy - ? undefined - : { - alignMode: result.body.modelInfo?.alignPolicy?.["alignMode"], - fillNAMethod: - result.body.modelInfo?.alignPolicy?.["fillNAMethod"], - paddingValue: - result.body.modelInfo?.alignPolicy?.["paddingValue"], - }, - status: result.body.modelInfo?.["status"], - errors: - result.body.modelInfo?.["errors"] === undefined - ? result.body.modelInfo?.["errors"] - : result.body.modelInfo?.["errors"].map((p: any) => { - return { code: p["code"], message: p["message"] }; - }), - diagnosticsInfo: !result.body.modelInfo?.diagnosticsInfo - ? undefined - : { - modelState: !result.body.modelInfo?.diagnosticsInfo?.modelState - ? undefined - : { - epochIds: - result.body.modelInfo?.diagnosticsInfo?.modelState?.[ - "epochIds" - ], - trainLosses: - result.body.modelInfo?.diagnosticsInfo?.modelState?.[ - "trainLosses" - ], - validationLosses: - result.body.modelInfo?.diagnosticsInfo?.modelState?.[ - "validationLosses" - ], - latenciesInSeconds: - result.body.modelInfo?.diagnosticsInfo?.modelState?.[ - "latenciesInSeconds" - ], - }, - variableStates: - result.body.modelInfo?.diagnosticsInfo?.["variableStates"] === - undefined - ? result.body.modelInfo?.diagnosticsInfo?.["variableStates"] - : result.body.modelInfo?.diagnosticsInfo?.[ - "variableStates" - ].map((p: any) => { - return { - variable: p["variable"], - filledNARatio: p["filledNARatio"], - effectiveCount: p["effectiveCount"], - firstTimestamp: - p["firstTimestamp"] !== undefined - ? new Date(p["firstTimestamp"]) - : undefined, - lastTimestamp: - p["lastTimestamp"] !== undefined - ? new Date(p["lastTimestamp"]) - : undefined, - }; - }), - }, - }, - }; + return multivariateAnomalyDetectionModelDeserializer(result.body); } /** @@ -302,87 +148,7 @@ export async function _listMultivariateModelsDeserialize( throw createRestError(result); } - return { - models: result.body["models"].map((p: any) => { - return { - modelId: p["modelId"], - createdTime: new Date(p["createdTime"]), - lastUpdatedTime: new Date(p["lastUpdatedTime"]), - modelInfo: !p.modelInfo - ? undefined - : { - dataSource: p.modelInfo?.["dataSource"], - dataSchema: p.modelInfo?.["dataSchema"], - startTime: new Date(p.modelInfo?.["startTime"]), - endTime: new Date(p.modelInfo?.["endTime"]), - displayName: p.modelInfo?.["displayName"], - slidingWindow: p.modelInfo?.["slidingWindow"], - alignPolicy: !p.modelInfo?.alignPolicy - ? undefined - : { - alignMode: p.modelInfo?.alignPolicy?.["alignMode"], - fillNAMethod: p.modelInfo?.alignPolicy?.["fillNAMethod"], - paddingValue: p.modelInfo?.alignPolicy?.["paddingValue"], - }, - status: p.modelInfo?.["status"], - errors: - p.modelInfo?.["errors"] === undefined - ? p.modelInfo?.["errors"] - : p.modelInfo?.["errors"].map((p: any) => { - return { code: p["code"], message: p["message"] }; - }), - diagnosticsInfo: !p.modelInfo?.diagnosticsInfo - ? undefined - : { - modelState: !p.modelInfo?.diagnosticsInfo?.modelState - ? undefined - : { - epochIds: - p.modelInfo?.diagnosticsInfo?.modelState?.[ - "epochIds" - ], - trainLosses: - p.modelInfo?.diagnosticsInfo?.modelState?.[ - "trainLosses" - ], - validationLosses: - p.modelInfo?.diagnosticsInfo?.modelState?.[ - "validationLosses" - ], - latenciesInSeconds: - p.modelInfo?.diagnosticsInfo?.modelState?.[ - "latenciesInSeconds" - ], - }, - variableStates: - p.modelInfo?.diagnosticsInfo?.["variableStates"] === - undefined - ? p.modelInfo?.diagnosticsInfo?.["variableStates"] - : p.modelInfo?.diagnosticsInfo?.["variableStates"].map( - (p: any) => { - return { - variable: p["variable"], - filledNARatio: p["filledNARatio"], - effectiveCount: p["effectiveCount"], - firstTimestamp: - p["firstTimestamp"] !== undefined - ? new Date(p["firstTimestamp"]) - : undefined, - lastTimestamp: - p["lastTimestamp"] !== undefined - ? new Date(p["lastTimestamp"]) - : undefined, - }; - }, - ), - }, - }, - }; - }), - currentCount: result.body["currentCount"], - maxCount: result.body["maxCount"], - nextLink: result.body["nextLink"], - }; + return _multivariateModelListDeserializer(result.body); } /** List models of a resource. */ @@ -456,82 +222,7 @@ export async function _getMultivariateModelDeserialize( throw createRestError(result); } - return { - modelId: result.body["modelId"], - createdTime: new Date(result.body["createdTime"]), - lastUpdatedTime: new Date(result.body["lastUpdatedTime"]), - modelInfo: !result.body.modelInfo - ? undefined - : { - dataSource: result.body.modelInfo?.["dataSource"], - dataSchema: result.body.modelInfo?.["dataSchema"], - startTime: new Date(result.body.modelInfo?.["startTime"]), - endTime: new Date(result.body.modelInfo?.["endTime"]), - displayName: result.body.modelInfo?.["displayName"], - slidingWindow: result.body.modelInfo?.["slidingWindow"], - alignPolicy: !result.body.modelInfo?.alignPolicy - ? undefined - : { - alignMode: result.body.modelInfo?.alignPolicy?.["alignMode"], - fillNAMethod: - result.body.modelInfo?.alignPolicy?.["fillNAMethod"], - paddingValue: - result.body.modelInfo?.alignPolicy?.["paddingValue"], - }, - status: result.body.modelInfo?.["status"], - errors: - result.body.modelInfo?.["errors"] === undefined - ? result.body.modelInfo?.["errors"] - : result.body.modelInfo?.["errors"].map((p: any) => { - return { code: p["code"], message: p["message"] }; - }), - diagnosticsInfo: !result.body.modelInfo?.diagnosticsInfo - ? undefined - : { - modelState: !result.body.modelInfo?.diagnosticsInfo?.modelState - ? undefined - : { - epochIds: - result.body.modelInfo?.diagnosticsInfo?.modelState?.[ - "epochIds" - ], - trainLosses: - result.body.modelInfo?.diagnosticsInfo?.modelState?.[ - "trainLosses" - ], - validationLosses: - result.body.modelInfo?.diagnosticsInfo?.modelState?.[ - "validationLosses" - ], - latenciesInSeconds: - result.body.modelInfo?.diagnosticsInfo?.modelState?.[ - "latenciesInSeconds" - ], - }, - variableStates: - result.body.modelInfo?.diagnosticsInfo?.["variableStates"] === - undefined - ? result.body.modelInfo?.diagnosticsInfo?.["variableStates"] - : result.body.modelInfo?.diagnosticsInfo?.[ - "variableStates" - ].map((p: any) => { - return { - variable: p["variable"], - filledNARatio: p["filledNARatio"], - effectiveCount: p["effectiveCount"], - firstTimestamp: - p["firstTimestamp"] !== undefined - ? new Date(p["firstTimestamp"]) - : undefined, - lastTimestamp: - p["lastTimestamp"] !== undefined - ? new Date(p["lastTimestamp"]) - : undefined, - }; - }), - }, - }, - }; + return multivariateAnomalyDetectionModelDeserializer(result.body); } /** @@ -561,12 +252,7 @@ export function _detectMultivariateBatchAnomalySend( .path("/multivariate/models/{modelId}:detect-batch", modelId) .post({ ...operationOptionsToRequestParameters(optionalParams), - body: { - dataSource: options["dataSource"], - topContributorCount: options["topContributorCount"], - startTime: options["startTime"].toISOString(), - endTime: options["endTime"].toISOString(), - }, + body: multivariateMultivariateBatchDetectionOptionsSerializer(options), }); } @@ -578,76 +264,7 @@ export async function _detectMultivariateBatchAnomalyDeserialize( throw createRestError(result); } - return { - resultId: result.body["resultId"], - summary: { - status: result.body.summary["status"], - errors: - result.body.summary["errors"] === undefined - ? result.body.summary["errors"] - : result.body.summary["errors"].map((p: any) => { - return { code: p["code"], message: p["message"] }; - }), - variableStates: - result.body.summary["variableStates"] === undefined - ? result.body.summary["variableStates"] - : result.body.summary["variableStates"].map((p: any) => { - return { - variable: p["variable"], - filledNARatio: p["filledNARatio"], - effectiveCount: p["effectiveCount"], - firstTimestamp: - p["firstTimestamp"] !== undefined - ? new Date(p["firstTimestamp"]) - : undefined, - lastTimestamp: - p["lastTimestamp"] !== undefined - ? new Date(p["lastTimestamp"]) - : undefined, - }; - }), - setupInfo: { - dataSource: result.body.summary.setupInfo["dataSource"], - topContributorCount: - result.body.summary.setupInfo["topContributorCount"], - startTime: new Date(result.body.summary.setupInfo["startTime"]), - endTime: new Date(result.body.summary.setupInfo["endTime"]), - }, - }, - results: result.body["results"].map((p: any) => { - return { - timestamp: new Date(p["timestamp"]), - value: !p.value - ? undefined - : { - isAnomaly: p.value?.["isAnomaly"], - severity: p.value?.["severity"], - score: p.value?.["score"], - interpretation: - p.value?.["interpretation"] === undefined - ? p.value?.["interpretation"] - : p.value?.["interpretation"].map((p: any) => { - return { - variable: p["variable"], - contributionScore: p["contributionScore"], - correlationChanges: !p.correlationChanges - ? undefined - : { - changedVariables: - p.correlationChanges?.["changedVariables"], - }, - }; - }), - }, - errors: - p["errors"] === undefined - ? p["errors"] - : p["errors"].map((p: any) => { - return { code: p["code"], message: p["message"] }; - }), - }; - }), - }; + return multivariateMultivariateDetectionResultDeserializer(result.body); } /** @@ -687,12 +304,7 @@ export function _detectMultivariateLastAnomalySend( .path("/multivariate/models/{modelId}:detect-last", modelId) .post({ ...operationOptionsToRequestParameters(optionalParams), - body: { - variables: options["variables"].map( - multivariateVariableValuesSerializer, - ), - topContributorCount: options["topContributorCount"], - }, + body: multivariateMultivariateLastDetectionOptionsSerializer(options), }); } @@ -704,64 +316,7 @@ export async function _detectMultivariateLastAnomalyDeserialize( throw createRestError(result); } - return { - variableStates: - result.body["variableStates"] === undefined - ? result.body["variableStates"] - : result.body["variableStates"].map((p: any) => { - return { - variable: p["variable"], - filledNARatio: p["filledNARatio"], - effectiveCount: p["effectiveCount"], - firstTimestamp: - p["firstTimestamp"] !== undefined - ? new Date(p["firstTimestamp"]) - : undefined, - lastTimestamp: - p["lastTimestamp"] !== undefined - ? new Date(p["lastTimestamp"]) - : undefined, - }; - }), - results: - result.body["results"] === undefined - ? result.body["results"] - : result.body["results"].map((p: any) => { - return { - timestamp: new Date(p["timestamp"]), - value: !p.value - ? undefined - : { - isAnomaly: p.value?.["isAnomaly"], - severity: p.value?.["severity"], - score: p.value?.["score"], - interpretation: - p.value?.["interpretation"] === undefined - ? p.value?.["interpretation"] - : p.value?.["interpretation"].map((p: any) => { - return { - variable: p["variable"], - contributionScore: p["contributionScore"], - correlationChanges: !p.correlationChanges - ? undefined - : { - changedVariables: - p.correlationChanges?.[ - "changedVariables" - ], - }, - }; - }), - }, - errors: - p["errors"] === undefined - ? p["errors"] - : p["errors"].map((p: any) => { - return { code: p["code"], message: p["message"] }; - }), - }; - }), - }; + return multivariateMultivariateLastDetectionResultDeserializer(result.body); } /** diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts index 2c7171665a..044e0eee1c 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts @@ -2,25 +2,29 @@ // Licensed under the MIT License. import { - univariateTimeSeriesPointSerializer, + AnomalyDetectorContext as Client, + UnivariateDetectUnivariateChangePointOptionalParams, + UnivariateDetectUnivariateEntireSeriesOptionalParams, + UnivariateDetectUnivariateLastPointOptionalParams, +} from "../index.js"; +import { UnivariateUnivariateDetectionOptions, + univariateUnivariateDetectionOptionsSerializer, UnivariateUnivariateEntireDetectionResult, + univariateUnivariateEntireDetectionResultDeserializer, UnivariateUnivariateLastDetectionResult, + univariateUnivariateLastDetectionResultDeserializer, UnivariateUnivariateChangePointDetectionOptions, + univariateUnivariateChangePointDetectionOptionsSerializer, UnivariateUnivariateChangePointDetectionResult, + univariateUnivariateChangePointDetectionResultDeserializer, } from "../../models/models.js"; -import { AnomalyDetectorContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { - UnivariateDetectUnivariateEntireSeriesOptionalParams, - UnivariateDetectUnivariateLastPointOptionalParams, - UnivariateDetectUnivariateChangePointOptionalParams, -} from "../../models/options.js"; export function _detectUnivariateEntireSeriesSend( context: Client, @@ -33,16 +37,7 @@ export function _detectUnivariateEntireSeriesSend( .path("/timeseries/entire/detect") .post({ ...operationOptionsToRequestParameters(optionalParams), - body: { - series: options["series"].map(univariateTimeSeriesPointSerializer), - granularity: options["granularity"], - customInterval: options["customInterval"], - period: options["period"], - maxAnomalyRatio: options["maxAnomalyRatio"], - sensitivity: options["sensitivity"], - imputeMode: options["imputeMode"], - imputeFixedValue: options["imputeFixedValue"], - }, + body: univariateUnivariateDetectionOptionsSerializer(options), }); } @@ -54,16 +49,7 @@ export async function _detectUnivariateEntireSeriesDeserialize( throw createRestError(result); } - return { - period: result.body["period"], - expectedValues: result.body["expectedValues"], - upperMargins: result.body["upperMargins"], - lowerMargins: result.body["lowerMargins"], - isAnomaly: result.body["isAnomaly"], - isNegativeAnomaly: result.body["isNegativeAnomaly"], - isPositiveAnomaly: result.body["isPositiveAnomaly"], - severity: result.body["severity"], - }; + return univariateUnivariateEntireDetectionResultDeserializer(result.body); } /** @@ -98,16 +84,7 @@ export function _detectUnivariateLastPointSend( .path("/timeseries/last/detect") .post({ ...operationOptionsToRequestParameters(optionalParams), - body: { - series: options["series"].map(univariateTimeSeriesPointSerializer), - granularity: options["granularity"], - customInterval: options["customInterval"], - period: options["period"], - maxAnomalyRatio: options["maxAnomalyRatio"], - sensitivity: options["sensitivity"], - imputeMode: options["imputeMode"], - imputeFixedValue: options["imputeFixedValue"], - }, + body: univariateUnivariateDetectionOptionsSerializer(options), }); } @@ -119,17 +96,7 @@ export async function _detectUnivariateLastPointDeserialize( throw createRestError(result); } - return { - period: result.body["period"], - suggestedWindow: result.body["suggestedWindow"], - expectedValue: result.body["expectedValue"], - upperMargin: result.body["upperMargin"], - lowerMargin: result.body["lowerMargin"], - isAnomaly: result.body["isAnomaly"], - isNegativeAnomaly: result.body["isNegativeAnomaly"], - isPositiveAnomaly: result.body["isPositiveAnomaly"], - severity: result.body["severity"], - }; + return univariateUnivariateLastDetectionResultDeserializer(result.body); } /** @@ -162,14 +129,7 @@ export function _detectUnivariateChangePointSend( .path("/timeseries/changepoint/detect") .post({ ...operationOptionsToRequestParameters(optionalParams), - body: { - series: options["series"].map(univariateTimeSeriesPointSerializer), - granularity: options["granularity"], - customInterval: options["customInterval"], - period: options["period"], - stableTrendWindow: options["stableTrendWindow"], - threshold: options["threshold"], - }, + body: univariateUnivariateChangePointDetectionOptionsSerializer(options), }); } @@ -181,11 +141,9 @@ export async function _detectUnivariateChangePointDeserialize( throw createRestError(result); } - return { - period: result.body["period"], - isChangePoint: result.body["isChangePoint"], - confidenceScores: result.body["confidenceScores"], - }; + return univariateUnivariateChangePointDetectionResultDeserializer( + result.body, + ); } /** Evaluate change point score of every series point */ diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts index 71459cd49f..62047c82d1 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts @@ -2,14 +2,6 @@ // Licensed under the MIT License. import { AnomalyDetectorContext } from "../../api/anomalyDetectorContext.js"; -import { - MultivariateMultivariateDetectionResult, - MultivariateMultivariateBatchDetectionOptions, - MultivariateModelInfo, - MultivariateAnomalyDetectionModel, - MultivariateMultivariateLastDetectionOptions, - MultivariateMultivariateLastDetectionResult, -} from "../../models/models.js"; import { getMultivariateBatchDetectionResult, trainMultivariateModel, @@ -19,7 +11,6 @@ import { detectMultivariateBatchAnomaly, detectMultivariateLastAnomaly, } from "../../api/multivariate/index.js"; -import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; import { MultivariateGetMultivariateBatchDetectionResultOptionalParams, MultivariateTrainMultivariateModelOptionalParams, @@ -28,7 +19,16 @@ import { MultivariateGetMultivariateModelOptionalParams, MultivariateDetectMultivariateBatchAnomalyOptionalParams, MultivariateDetectMultivariateLastAnomalyOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; +import { + MultivariateMultivariateDetectionResult, + MultivariateMultivariateBatchDetectionOptions, + MultivariateModelInfo, + MultivariateAnomalyDetectionModel, + MultivariateMultivariateLastDetectionOptions, + MultivariateMultivariateLastDetectionResult, +} from "../../models/models.js"; +import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; /** Interface representing a Multivariate operations. */ export interface MultivariateOperations { diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts index 6da01e8b45..d8ccd2ab9d 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts @@ -3,22 +3,22 @@ import { AnomalyDetectorContext } from "../../api/anomalyDetectorContext.js"; import { - UnivariateUnivariateDetectionOptions, - UnivariateUnivariateEntireDetectionResult, - UnivariateUnivariateLastDetectionResult, - UnivariateUnivariateChangePointDetectionOptions, - UnivariateUnivariateChangePointDetectionResult, -} from "../../models/models.js"; + UnivariateDetectUnivariateEntireSeriesOptionalParams, + UnivariateDetectUnivariateLastPointOptionalParams, + UnivariateDetectUnivariateChangePointOptionalParams, +} from "../../api/options.js"; import { detectUnivariateEntireSeries, detectUnivariateLastPoint, detectUnivariateChangePoint, } from "../../api/univariate/index.js"; import { - UnivariateDetectUnivariateEntireSeriesOptionalParams, - UnivariateDetectUnivariateLastPointOptionalParams, - UnivariateDetectUnivariateChangePointOptionalParams, -} from "../../models/options.js"; + UnivariateUnivariateDetectionOptions, + UnivariateUnivariateEntireDetectionResult, + UnivariateUnivariateLastDetectionResult, + UnivariateUnivariateChangePointDetectionOptions, + UnivariateUnivariateChangePointDetectionResult, +} from "../../models/models.js"; /** Interface representing a Univariate operations. */ export interface UnivariateOperations { diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts index aaf6de5994..d5a32173b2 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts @@ -7,14 +7,11 @@ import { PagedAsyncIterableIterator, } from "./static-helpers/pagingHelpers.js"; -export { - AnomalyDetectorClient, - AnomalyDetectorClientOptionalParams, -} from "./anomalyDetectorClient.js"; +export { AnomalyDetectorClient } from "./anomalyDetectorClient.js"; export { MultivariateMultivariateDetectionResult, MultivariateMultivariateBatchDetectionResultSummary, - MultivariateBatchDetectionStatus, + MultivariateMultivariateBatchDetectionStatus, MultivariateErrorResponse, MultivariateVariableState, MultivariateMultivariateBatchDetectionOptions, @@ -23,11 +20,11 @@ export { MultivariateAnomalyInterpretation, MultivariateCorrelationChanges, MultivariateModelInfo, - DataSchema, + MultivariateDataSchema, MultivariateAlignPolicy, - AlignMode, - FillNAMethod, - ModelStatus, + MultivariateAlignMode, + MultivariateFillNAMethod, + MultivariateModelStatus, MultivariateDiagnosticsInfo, MultivariateModelState, MultivariateAnomalyDetectionModel, @@ -36,16 +33,18 @@ export { MultivariateMultivariateLastDetectionResult, UnivariateUnivariateDetectionOptions, UnivariateTimeSeriesPoint, - TimeGranularity, - ImputeMode, + UnivariateTimeGranularity, + UnivariateImputeMode, UnivariateUnivariateEntireDetectionResult, UnivariateAnomalyDetectorError, - AnomalyDetectorErrorCodes, + UnivariateAnomalyDetectorErrorCodes, UnivariateUnivariateLastDetectionResult, UnivariateUnivariateChangePointDetectionOptions, UnivariateUnivariateChangePointDetectionResult, - Versions, - MultivariateResponseError, + APIVersion, +} from "./models/index.js"; +export { + AnomalyDetectorClientOptionalParams, UnivariateDetectUnivariateEntireSeriesOptionalParams, UnivariateDetectUnivariateLastPointOptionalParams, UnivariateDetectUnivariateChangePointOptionalParams, @@ -56,7 +55,7 @@ export { MultivariateGetMultivariateModelOptionalParams, MultivariateDetectMultivariateBatchAnomalyOptionalParams, MultivariateDetectMultivariateLastAnomalyOptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; export { MultivariateOperations, UnivariateOperations, diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/index.ts index 341fc92793..c8bde9b187 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/index.ts @@ -4,7 +4,7 @@ export { MultivariateMultivariateDetectionResult, MultivariateMultivariateBatchDetectionResultSummary, - MultivariateBatchDetectionStatus, + MultivariateMultivariateBatchDetectionStatus, MultivariateErrorResponse, MultivariateVariableState, MultivariateMultivariateBatchDetectionOptions, @@ -13,11 +13,11 @@ export { MultivariateAnomalyInterpretation, MultivariateCorrelationChanges, MultivariateModelInfo, - DataSchema, + MultivariateDataSchema, MultivariateAlignPolicy, - AlignMode, - FillNAMethod, - ModelStatus, + MultivariateAlignMode, + MultivariateFillNAMethod, + MultivariateModelStatus, MultivariateDiagnosticsInfo, MultivariateModelState, MultivariateAnomalyDetectionModel, @@ -26,26 +26,13 @@ export { MultivariateMultivariateLastDetectionResult, UnivariateUnivariateDetectionOptions, UnivariateTimeSeriesPoint, - TimeGranularity, - ImputeMode, + UnivariateTimeGranularity, + UnivariateImputeMode, UnivariateUnivariateEntireDetectionResult, UnivariateAnomalyDetectorError, - AnomalyDetectorErrorCodes, + UnivariateAnomalyDetectorErrorCodes, UnivariateUnivariateLastDetectionResult, UnivariateUnivariateChangePointDetectionOptions, UnivariateUnivariateChangePointDetectionResult, - Versions, - MultivariateResponseError, + APIVersion, } from "./models.js"; -export { - UnivariateDetectUnivariateEntireSeriesOptionalParams, - UnivariateDetectUnivariateLastPointOptionalParams, - UnivariateDetectUnivariateChangePointOptionalParams, - MultivariateGetMultivariateBatchDetectionResultOptionalParams, - MultivariateTrainMultivariateModelOptionalParams, - MultivariateListMultivariateModelsOptionalParams, - MultivariateDeleteMultivariateModelOptionalParams, - MultivariateGetMultivariateModelOptionalParams, - MultivariateDetectMultivariateBatchAnomalyOptionalParams, - MultivariateDetectMultivariateLastAnomalyOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts index a885e02e69..999076c97d 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts @@ -11,10 +11,22 @@ export interface MultivariateMultivariateDetectionResult { results: MultivariateAnomalyState[]; } +export function multivariateMultivariateDetectionResultDeserializer( + item: any, +): MultivariateMultivariateDetectionResult { + return { + resultId: item["resultId"], + summary: multivariateMultivariateBatchDetectionResultSummaryDeserializer( + item["summary"], + ), + results: multivariateAnomalyStateArrayDeserializer(item["results"]), + }; +} + /** Multivariate anomaly detection status. */ export interface MultivariateMultivariateBatchDetectionResultSummary { /** Status of detection results. One of CREATED, RUNNING, READY, and FAILED. */ - status: MultivariateBatchDetectionStatus; + status: MultivariateMultivariateBatchDetectionStatus; /** Error message when detection is failed. */ errors?: MultivariateErrorResponse[]; /** Variable Status. */ @@ -26,8 +38,25 @@ export interface MultivariateMultivariateBatchDetectionResultSummary { setupInfo: MultivariateMultivariateBatchDetectionOptions; } -/** Type of MultivariateBatchDetectionStatus */ -export type MultivariateBatchDetectionStatus = +export function multivariateMultivariateBatchDetectionResultSummaryDeserializer( + item: any, +): MultivariateMultivariateBatchDetectionResultSummary { + return { + status: item["status"], + errors: !item["errors"] + ? item["errors"] + : multivariateErrorResponseArrayDeserializer(item["errors"]), + variableStates: !item["variableStates"] + ? item["variableStates"] + : multivariateVariableStateArrayDeserializer(item["variableStates"]), + setupInfo: multivariateMultivariateBatchDetectionOptionsDeserializer( + item["setupInfo"], + ), + }; +} + +/** Type of MultivariateMultivariateBatchDetectionStatus */ +export type MultivariateMultivariateBatchDetectionStatus = | "CREATED" | "RUNNING" | "READY" @@ -41,6 +70,23 @@ export interface MultivariateErrorResponse { message: string; } +export function multivariateErrorResponseDeserializer( + item: any, +): MultivariateErrorResponse { + return { + code: item["code"], + message: item["message"], + }; +} + +export function multivariateErrorResponseArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return multivariateErrorResponseDeserializer(item); + }); +} + /** Variable Status. */ export interface MultivariateVariableState { /** Variable name in variable states. */ @@ -57,7 +103,7 @@ export interface MultivariateVariableState { export function multivariateVariableStateSerializer( item: MultivariateVariableState, -): Record { +): any { return { variable: item["variable"], filledNARatio: item["filledNARatio"], @@ -67,6 +113,38 @@ export function multivariateVariableStateSerializer( }; } +export function multivariateVariableStateDeserializer( + item: any, +): MultivariateVariableState { + return { + variable: item["variable"], + filledNARatio: item["filledNARatio"], + effectiveCount: item["effectiveCount"], + firstTimestamp: !item["firstTimestamp"] + ? item["firstTimestamp"] + : new Date(item["firstTimestamp"]), + lastTimestamp: !item["lastTimestamp"] + ? item["lastTimestamp"] + : new Date(item["lastTimestamp"]), + }; +} + +export function multivariateVariableStateArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return multivariateVariableStateSerializer(item); + }); +} + +export function multivariateVariableStateArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return multivariateVariableStateDeserializer(item); + }); +} + /** * Detection request for batch inference. This is an asynchronous inference which * will need another API to get detection results. @@ -99,7 +177,7 @@ export interface MultivariateMultivariateBatchDetectionOptions { export function multivariateMultivariateBatchDetectionOptionsSerializer( item: MultivariateMultivariateBatchDetectionOptions, -): Record { +): any { return { dataSource: item["dataSource"], topContributorCount: item["topContributorCount"], @@ -108,6 +186,17 @@ export function multivariateMultivariateBatchDetectionOptionsSerializer( }; } +export function multivariateMultivariateBatchDetectionOptionsDeserializer( + item: any, +): MultivariateMultivariateBatchDetectionOptions { + return { + dataSource: item["dataSource"], + topContributorCount: item["topContributorCount"], + startTime: new Date(item["startTime"]), + endTime: new Date(item["endTime"]), + }; +} + /** Anomaly status and information. */ export interface MultivariateAnomalyState { /** The timestamp for this anomaly. */ @@ -118,6 +207,20 @@ export interface MultivariateAnomalyState { errors?: MultivariateErrorResponse[]; } +export function multivariateAnomalyStateDeserializer( + item: any, +): MultivariateAnomalyState { + return { + timestamp: new Date(item["timestamp"]), + value: !item["value"] + ? item["value"] + : multivariateAnomalyValueDeserializer(item["value"]), + errors: !item["errors"] + ? item["errors"] + : multivariateErrorResponseArrayDeserializer(item["errors"]), + }; +} + /** Detailed information of the anomalous timestamp. */ export interface MultivariateAnomalyValue { /** True if an anomaly is detected at the current timestamp. */ @@ -136,6 +239,21 @@ export interface MultivariateAnomalyValue { interpretation?: MultivariateAnomalyInterpretation[]; } +export function multivariateAnomalyValueDeserializer( + item: any, +): MultivariateAnomalyValue { + return { + isAnomaly: item["isAnomaly"], + severity: item["severity"], + score: item["score"], + interpretation: !item["interpretation"] + ? item["interpretation"] + : multivariateAnomalyInterpretationArrayDeserializer( + item["interpretation"], + ), + }; +} + /** Interpretation of the anomalous timestamp. */ export interface MultivariateAnomalyInterpretation { /** Variable. */ @@ -149,12 +267,52 @@ export interface MultivariateAnomalyInterpretation { correlationChanges?: MultivariateCorrelationChanges; } +export function multivariateAnomalyInterpretationDeserializer( + item: any, +): MultivariateAnomalyInterpretation { + return { + variable: item["variable"], + contributionScore: item["contributionScore"], + correlationChanges: !item["correlationChanges"] + ? item["correlationChanges"] + : multivariateCorrelationChangesDeserializer(item["correlationChanges"]), + }; +} + /** Correlation changes among the anomalous variables */ export interface MultivariateCorrelationChanges { /** The correlated variables that have correlation changes under an anomaly. */ changedVariables?: string[]; } +export function multivariateCorrelationChangesDeserializer( + item: any, +): MultivariateCorrelationChanges { + return { + changedVariables: !item["changedVariables"] + ? item["changedVariables"] + : item["changedVariables"].map((p: any) => { + return p; + }), + }; +} + +export function multivariateAnomalyInterpretationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return multivariateAnomalyInterpretationDeserializer(item); + }); +} + +export function multivariateAnomalyStateArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return multivariateAnomalyStateDeserializer(item); + }); +} + /** * Training result of a model including its status, errors and diagnostics * information. @@ -170,7 +328,7 @@ export interface MultivariateModelInfo { * Data schema of input data source: OneTable or MultiTable. The default * DataSchema is OneTable. */ - dataSchema?: DataSchema; + dataSchema?: MultivariateDataSchema; /** * A required field, indicating the start time of training data, which should be * date-time of ISO 8601 format. @@ -194,7 +352,7 @@ export interface MultivariateModelInfo { /** An optional field, indicating the manner to align multiple variables. */ alignPolicy?: MultivariateAlignPolicy; /** Model status. One of CREATED, RUNNING, READY, and FAILED. */ - status?: ModelStatus; + status?: MultivariateModelStatus; /** Error messages when failed to create a model. */ readonly errors?: MultivariateErrorResponse[]; /** Diagnostics information to help inspect the states of model or variable. */ @@ -203,7 +361,7 @@ export interface MultivariateModelInfo { export function multivariateModelInfoSerializer( item: MultivariateModelInfo, -): Record { +): any { return { dataSource: item["dataSource"], dataSchema: item["dataSchema"], @@ -211,18 +369,41 @@ export function multivariateModelInfoSerializer( endTime: item["endTime"].toISOString(), displayName: item["displayName"], slidingWindow: item["slidingWindow"], - alignPolicy: !item.alignPolicy - ? item.alignPolicy - : multivariateAlignPolicySerializer(item.alignPolicy), + alignPolicy: !item["alignPolicy"] + ? item["alignPolicy"] + : multivariateAlignPolicySerializer(item["alignPolicy"]), + status: item["status"], + diagnosticsInfo: !item["diagnosticsInfo"] + ? item["diagnosticsInfo"] + : multivariateDiagnosticsInfoSerializer(item["diagnosticsInfo"]), + }; +} + +export function multivariateModelInfoDeserializer( + item: any, +): MultivariateModelInfo { + return { + dataSource: item["dataSource"], + dataSchema: item["dataSchema"], + startTime: new Date(item["startTime"]), + endTime: new Date(item["endTime"]), + displayName: item["displayName"], + slidingWindow: item["slidingWindow"], + alignPolicy: !item["alignPolicy"] + ? item["alignPolicy"] + : multivariateAlignPolicyDeserializer(item["alignPolicy"]), status: item["status"], - diagnosticsInfo: !item.diagnosticsInfo - ? item.diagnosticsInfo - : multivariateDiagnosticsInfoSerializer(item.diagnosticsInfo), + errors: !item["errors"] + ? item["errors"] + : multivariateErrorResponseArrayDeserializer(item["errors"]), + diagnosticsInfo: !item["diagnosticsInfo"] + ? item["diagnosticsInfo"] + : multivariateDiagnosticsInfoDeserializer(item["diagnosticsInfo"]), }; } /** Data schema of input data source: OneTable or MultiTable. The default DataSchema is OneTable. */ -export type DataSchema = "OneTable" | "MultiTable"; +export type MultivariateDataSchema = "OneTable" | "MultiTable"; /** An optional field, indicating the manner to align multiple variables. */ export interface MultivariateAlignPolicy { @@ -230,19 +411,19 @@ export interface MultivariateAlignPolicy { * An optional field, indicating how to align different variables to the same * time-range. Either Inner or Outer. */ - alignMode?: AlignMode; + alignMode?: MultivariateAlignMode; /** * An optional field, indicating how missing values will be filled. One of * Previous, Subsequent, Linear, Zero, Fixed. */ - fillNAMethod?: FillNAMethod; + fillNAMethod?: MultivariateFillNAMethod; /** An optional field. Required when fillNAMethod is Fixed. */ paddingValue?: number; } export function multivariateAlignPolicySerializer( item: MultivariateAlignPolicy, -): Record { +): any { return { alignMode: item["alignMode"], fillNAMethod: item["fillNAMethod"], @@ -250,17 +431,31 @@ export function multivariateAlignPolicySerializer( }; } -/** Type of AlignMode */ -export type AlignMode = "Inner" | "Outer"; +export function multivariateAlignPolicyDeserializer( + item: any, +): MultivariateAlignPolicy { + return { + alignMode: item["alignMode"], + fillNAMethod: item["fillNAMethod"], + paddingValue: item["paddingValue"], + }; +} + +/** Type of MultivariateAlignMode */ +export type MultivariateAlignMode = "Inner" | "Outer"; /** An optional field, indicating how missing values will be filled. One of Previous, Subsequent, Linear, Zero, Fixed. */ -export type FillNAMethod = +export type MultivariateFillNAMethod = | "Previous" | "Subsequent" | "Linear" | "Zero" | "Fixed"; -/** Type of ModelStatus */ -export type ModelStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; +/** Type of MultivariateModelStatus */ +export type MultivariateModelStatus = + | "CREATED" + | "RUNNING" + | "READY" + | "FAILED"; /** Diagnostics information to help inspect the states of model or variable. */ export interface MultivariateDiagnosticsInfo { @@ -272,15 +467,27 @@ export interface MultivariateDiagnosticsInfo { export function multivariateDiagnosticsInfoSerializer( item: MultivariateDiagnosticsInfo, -): Record { +): any { + return { + modelState: !item["modelState"] + ? item["modelState"] + : multivariateModelStateSerializer(item["modelState"]), + variableStates: !item["variableStates"] + ? item["variableStates"] + : multivariateVariableStateArraySerializer(item["variableStates"]), + }; +} + +export function multivariateDiagnosticsInfoDeserializer( + item: any, +): MultivariateDiagnosticsInfo { return { - modelState: !item.modelState - ? item.modelState - : multivariateModelStateSerializer(item.modelState), - variableStates: - item["variableStates"] === undefined - ? item["variableStates"] - : item["variableStates"].map(multivariateVariableStateSerializer), + modelState: !item["modelState"] + ? item["modelState"] + : multivariateModelStateDeserializer(item["modelState"]), + variableStates: !item["variableStates"] + ? item["variableStates"] + : multivariateVariableStateArrayDeserializer(item["variableStates"]), }; } @@ -307,12 +514,55 @@ export interface MultivariateModelState { export function multivariateModelStateSerializer( item: MultivariateModelState, -): Record { +): any { return { - epochIds: item["epochIds"], - trainLosses: item["trainLosses"], - validationLosses: item["validationLosses"], - latenciesInSeconds: item["latenciesInSeconds"], + epochIds: !item["epochIds"] + ? item["epochIds"] + : item["epochIds"].map((p: any) => { + return p; + }), + trainLosses: !item["trainLosses"] + ? item["trainLosses"] + : item["trainLosses"].map((p: any) => { + return p; + }), + validationLosses: !item["validationLosses"] + ? item["validationLosses"] + : item["validationLosses"].map((p: any) => { + return p; + }), + latenciesInSeconds: !item["latenciesInSeconds"] + ? item["latenciesInSeconds"] + : item["latenciesInSeconds"].map((p: any) => { + return p; + }), + }; +} + +export function multivariateModelStateDeserializer( + item: any, +): MultivariateModelState { + return { + epochIds: !item["epochIds"] + ? item["epochIds"] + : item["epochIds"].map((p: any) => { + return p; + }), + trainLosses: !item["trainLosses"] + ? item["trainLosses"] + : item["trainLosses"].map((p: any) => { + return p; + }), + validationLosses: !item["validationLosses"] + ? item["validationLosses"] + : item["validationLosses"].map((p: any) => { + return p; + }), + latenciesInSeconds: !item["latenciesInSeconds"] + ? item["latenciesInSeconds"] + : item["latenciesInSeconds"].map((p: any) => { + return p; + }), }; } @@ -331,6 +581,19 @@ export interface MultivariateAnomalyDetectionModel { modelInfo?: MultivariateModelInfo; } +export function multivariateAnomalyDetectionModelDeserializer( + item: any, +): MultivariateAnomalyDetectionModel { + return { + modelId: item["modelId"], + createdTime: new Date(item["createdTime"]), + lastUpdatedTime: new Date(item["lastUpdatedTime"]), + modelInfo: !item["modelInfo"] + ? item["modelInfo"] + : multivariateModelInfoDeserializer(item["modelInfo"]), + }; +} + /** Response of listing models. */ export interface _MultivariateModelList { /** List of models. */ @@ -343,6 +606,25 @@ export interface _MultivariateModelList { nextLink?: string; } +export function _multivariateModelListDeserializer( + item: any, +): _MultivariateModelList { + return { + models: multivariateAnomalyDetectionModelArrayDeserializer(item["models"]), + currentCount: item["currentCount"], + maxCount: item["maxCount"], + nextLink: item["nextLink"], + }; +} + +export function multivariateAnomalyDetectionModelArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return multivariateAnomalyDetectionModelDeserializer(item); + }); +} + /** Request of last detection. */ export interface MultivariateMultivariateLastDetectionOptions { /** @@ -360,9 +642,9 @@ export interface MultivariateMultivariateLastDetectionOptions { export function multivariateMultivariateLastDetectionOptionsSerializer( item: MultivariateMultivariateLastDetectionOptions, -): Record { +): any { return { - variables: item["variables"].map(multivariateVariableValuesSerializer), + variables: multivariateVariableValuesArraySerializer(item["variables"]), topContributorCount: item["topContributorCount"], }; } @@ -379,14 +661,26 @@ export interface MultivariateVariableValues { export function multivariateVariableValuesSerializer( item: MultivariateVariableValues, -): Record { +): any { return { variable: item["variable"], - timestamps: item["timestamps"], - values: item["values"], + timestamps: item["timestamps"].map((p: any) => { + return p; + }), + values: item["values"].map((p: any) => { + return p; + }), }; } +export function multivariateVariableValuesArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return multivariateVariableValuesSerializer(item); + }); +} + /** Results of last detection. */ export interface MultivariateMultivariateLastDetectionResult { /** Variable Status. */ @@ -395,6 +689,19 @@ export interface MultivariateMultivariateLastDetectionResult { results?: MultivariateAnomalyState[]; } +export function multivariateMultivariateLastDetectionResultDeserializer( + item: any, +): MultivariateMultivariateLastDetectionResult { + return { + variableStates: !item["variableStates"] + ? item["variableStates"] + : multivariateVariableStateArrayDeserializer(item["variableStates"]), + results: !item["results"] + ? item["results"] + : multivariateAnomalyStateArrayDeserializer(item["results"]), + }; +} + /** The request of entire or last anomaly detection. */ export interface UnivariateUnivariateDetectionOptions { /** @@ -410,7 +717,7 @@ export interface UnivariateUnivariateDetectionOptions { * be none by default. If granularity is none, the timestamp property in time * series point can be absent. */ - granularity?: TimeGranularity; + granularity?: UnivariateTimeGranularity; /** * Custom Interval is used to set non-standard time interval, for example, if the * series is 5 minutes, request can be set as {"granularity":"minutely", @@ -434,7 +741,7 @@ export interface UnivariateUnivariateDetectionOptions { * Used to specify how to deal with missing values in the input series, it's used * when granularity is not "none". */ - imputeMode?: ImputeMode; + imputeMode?: UnivariateImputeMode; /** * Used to specify the value to fill, it's used when granularity is not "none" * and imputeMode is "fixed". @@ -444,9 +751,9 @@ export interface UnivariateUnivariateDetectionOptions { export function univariateUnivariateDetectionOptionsSerializer( item: UnivariateUnivariateDetectionOptions, -): Record { +): any { return { - series: item["series"].map(univariateTimeSeriesPointSerializer), + series: univariateTimeSeriesPointArraySerializer(item["series"]), granularity: item["granularity"], customInterval: item["customInterval"], period: item["period"], @@ -467,15 +774,20 @@ export interface UnivariateTimeSeriesPoint { export function univariateTimeSeriesPointSerializer( item: UnivariateTimeSeriesPoint, -): Record { - return { - timestamp: item["timestamp"]?.toISOString(), - value: item["value"], - }; +): any { + return { timestamp: item["timestamp"]?.toISOString(), value: item["value"] }; +} + +export function univariateTimeSeriesPointArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return univariateTimeSeriesPointSerializer(item); + }); } -/** Type of TimeGranularity */ -export type TimeGranularity = +/** Type of UnivariateTimeGranularity */ +export type UnivariateTimeGranularity = | "yearly" | "monthly" | "weekly" @@ -485,8 +797,8 @@ export type TimeGranularity = | "secondly" | "microsecond" | "none"; -/** Type of ImputeMode */ -export type ImputeMode = +/** Type of UnivariateImputeMode */ +export type UnivariateImputeMode = | "auto" | "previous" | "linear" @@ -550,16 +862,56 @@ export interface UnivariateUnivariateEntireDetectionResult { severity?: number[]; } +export function univariateUnivariateEntireDetectionResultDeserializer( + item: any, +): UnivariateUnivariateEntireDetectionResult { + return { + period: item["period"], + expectedValues: item["expectedValues"].map((p: any) => { + return p; + }), + upperMargins: item["upperMargins"].map((p: any) => { + return p; + }), + lowerMargins: item["lowerMargins"].map((p: any) => { + return p; + }), + isAnomaly: item["isAnomaly"].map((p: any) => { + return p; + }), + isNegativeAnomaly: item["isNegativeAnomaly"].map((p: any) => { + return p; + }), + isPositiveAnomaly: item["isPositiveAnomaly"].map((p: any) => { + return p; + }), + severity: !item["severity"] + ? item["severity"] + : item["severity"].map((p: any) => { + return p; + }), + }; +} + /** Error information returned by the API. */ export interface UnivariateAnomalyDetectorError { /** The error code. */ - code?: AnomalyDetectorErrorCodes; + code?: UnivariateAnomalyDetectorErrorCodes; /** A message explaining the error reported by the service. */ message?: string; } -/** Type of AnomalyDetectorErrorCodes */ -export type AnomalyDetectorErrorCodes = +export function univariateAnomalyDetectorErrorDeserializer( + item: any, +): UnivariateAnomalyDetectorError { + return { + code: item["code"], + message: item["message"], + }; +} + +/** Type of UnivariateAnomalyDetectorErrorCodes */ +export type UnivariateAnomalyDetectorErrorCodes = | "InvalidCustomInterval" | "BadArgument" | "InvalidGranularity" @@ -619,6 +971,22 @@ export interface UnivariateUnivariateLastDetectionResult { severity?: number; } +export function univariateUnivariateLastDetectionResultDeserializer( + item: any, +): UnivariateUnivariateLastDetectionResult { + return { + period: item["period"], + suggestedWindow: item["suggestedWindow"], + expectedValue: item["expectedValue"], + upperMargin: item["upperMargin"], + lowerMargin: item["lowerMargin"], + isAnomaly: item["isAnomaly"], + isNegativeAnomaly: item["isNegativeAnomaly"], + isPositiveAnomaly: item["isPositiveAnomaly"], + severity: item["severity"], + }; +} + /** The request of change point detection. */ export interface UnivariateUnivariateChangePointDetectionOptions { /** @@ -630,7 +998,7 @@ export interface UnivariateUnivariateChangePointDetectionOptions { * Can only be one of yearly, monthly, weekly, daily, hourly, minutely or * secondly. Granularity is used for verify whether input series is valid. */ - granularity: TimeGranularity; + granularity: UnivariateTimeGranularity; /** * Custom Interval is used to set non-standard time interval, for example, if the * series is 5 minutes, request can be set as {"granularity":"minutely", @@ -657,9 +1025,9 @@ export interface UnivariateUnivariateChangePointDetectionOptions { export function univariateUnivariateChangePointDetectionOptionsSerializer( item: UnivariateUnivariateChangePointDetectionOptions, -): Record { +): any { return { - series: item["series"].map(univariateTimeSeriesPointSerializer), + series: univariateTimeSeriesPointArraySerializer(item["series"]), granularity: item["granularity"], customInterval: item["customInterval"], period: item["period"], @@ -685,13 +1053,23 @@ export interface UnivariateUnivariateChangePointDetectionResult { confidenceScores?: number[]; } -/** Type of Versions */ -export type Versions = "v1.1"; - -/** Error response */ -export interface MultivariateResponseError { - /** The error code. */ - code: string; - /** The message explaining the error reported by the service. */ - message: string; +export function univariateUnivariateChangePointDetectionResultDeserializer( + item: any, +): UnivariateUnivariateChangePointDetectionResult { + return { + period: item["period"], + isChangePoint: !item["isChangePoint"] + ? item["isChangePoint"] + : item["isChangePoint"].map((p: any) => { + return p; + }), + confidenceScores: !item["confidenceScores"] + ? item["confidenceScores"] + : item["confidenceScores"].map((p: any) => { + return p; + }), + }; } + +/** Type of APIVersion */ +export type APIVersion = "v1.1"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md b/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md index dbc6909f4c..bb8efe8f7f 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md @@ -189,6 +189,7 @@ export class BatchClient { // @public export interface BatchClientOptionalParams extends ClientOptions { + apiVersion?: string; } // @public @@ -1734,7 +1735,7 @@ export interface PoolUsageMetrics { // @public export interface PublicIpAddressConfiguration { ipAddressIds?: string[]; - ipAddressProvisioningType?: IpAddressProvisioningType; + IpAddressProvisioningType?: IpAddressProvisioningType; } // @public @@ -2195,9 +2196,6 @@ export interface UserIdentity { // @public export type VerificationType = "verified" | "unverified"; -// @public -export type Versions = "2023-05-01.17.0"; - // @public export interface VirtualMachineConfiguration { containerConfiguration?: ContainerConfiguration; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts index 0b9bead362..96210e417a 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts @@ -1,14 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { TokenCredential } from "@azure/core-auth"; +/** Azure Batch provides Cloud-scale job scheduling and compute management. */ export interface BatchContext extends Client {} /** Optional parameters for the client. */ -export interface BatchClientOptionalParams extends ClientOptions {} +export interface BatchClientOptionalParams extends ClientOptions { + /** The API version to use for this operation. */ + apiVersion?: string; +} /** Azure Batch provides Cloud-scale job scheduling and compute management. */ export function createBatch( diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/index.ts index 50f42778ed..6ae19d1894 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/index.ts @@ -84,3 +84,81 @@ export { getNodeFileProperties, listNodeFiles, } from "./operations.js"; +export { + ListApplicationsOptionalParams, + GetApplicationOptionalParams, + ListPoolUsageMetricsOptionalParams, + CreatePoolOptionalParams, + ListPoolsOptionalParams, + DeletePoolOptionalParams, + PoolExistsOptionalParams, + GetPoolOptionalParams, + UpdatePoolOptionalParams, + DisablePoolAutoScaleOptionalParams, + EnablePoolAutoScaleOptionalParams, + EvaluatePoolAutoScaleOptionalParams, + ResizePoolOptionalParams, + StopPoolResizeOptionalParams, + ReplacePoolPropertiesOptionalParams, + RemoveNodesOptionalParams, + ListSupportedImagesOptionalParams, + ListPoolNodeCountsOptionalParams, + DeleteJobOptionalParams, + GetJobOptionalParams, + UpdateJobOptionalParams, + ReplaceJobOptionalParams, + DisableJobOptionalParams, + EnableJobOptionalParams, + TerminateJobOptionalParams, + CreateJobOptionalParams, + ListJobsOptionalParams, + ListJobsFromScheduleOptionalParams, + ListJobPreparationAndReleaseTaskStatusOptionalParams, + GetJobTaskCountsOptionalParams, + CreateCertificateOptionalParams, + ListCertificatesOptionalParams, + CancelCertificateDeletionOptionalParams, + DeleteCertificateOptionalParams, + GetCertificateOptionalParams, + JobScheduleExistsOptionalParams, + DeleteJobScheduleOptionalParams, + GetJobScheduleOptionalParams, + UpdateJobScheduleOptionalParams, + ReplaceJobScheduleOptionalParams, + DisableJobScheduleOptionalParams, + EnableJobScheduleOptionalParams, + TerminateJobScheduleOptionalParams, + CreateJobScheduleOptionalParams, + ListJobSchedulesOptionalParams, + CreateTaskOptionalParams, + ListTasksOptionalParams, + CreateTaskCollectionOptionalParams, + DeleteTaskOptionalParams, + GetTaskOptionalParams, + ReplaceTaskOptionalParams, + ListSubTasksOptionalParams, + TerminateTaskOptionalParams, + ReactivateTaskOptionalParams, + DeleteTaskFileOptionalParams, + GetTaskFileOptionalParams, + GetTaskFilePropertiesOptionalParams, + ListTaskFilesOptionalParams, + CreateNodeUserOptionalParams, + DeleteNodeUserOptionalParams, + ReplaceNodeUserOptionalParams, + GetNodeOptionalParams, + RebootNodeOptionalParams, + ReimageNodeOptionalParams, + DisableNodeSchedulingOptionalParams, + EnableNodeSchedulingOptionalParams, + GetNodeRemoteLoginSettingsOptionalParams, + GetNodeRemoteDesktopFileOptionalParams, + UploadNodeLogsOptionalParams, + ListNodesOptionalParams, + GetNodeExtensionOptionalParams, + ListNodeExtensionsOptionalParams, + DeleteNodeFileOptionalParams, + GetNodeFileOptionalParams, + GetNodeFilePropertiesOptionalParams, + ListNodeFilesOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts index a60479554f..4ed8d6d9aa 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts @@ -2,181 +2,202 @@ // Licensed under the MIT License. import { - startTaskSerializer, - taskContainerSettingsSerializer, - batchNodeIdentityReferenceSerializer, - resourceFileSerializer, - environmentSettingSerializer, - userIdentitySerializer, - certificateReferenceSerializer, - batchTaskCreateOptionsSerializer, - exitConditionsSerializer, - outputFileSerializer, - affinityInformationSerializer, - taskConstraintsSerializer, - multiInstanceSettingsSerializer, - taskDependenciesSerializer, - applicationPackageReferenceSerializer, - authenticationTokenSettingsSerializer, - scheduleSerializer, - jobSpecificationSerializer, - jobNetworkConfigurationSerializer, - jobConstraintsSerializer, - jobManagerTaskSerializer, - jobPreparationTaskSerializer, - jobReleaseTaskSerializer, - poolInformationSerializer, - cloudServiceConfigurationSerializer, - virtualMachineConfigurationSerializer, - taskSchedulingPolicySerializer, - networkConfigurationSerializer, - userAccountSerializer, - metadataItemSerializer, - mountConfigurationSerializer, + CancelCertificateDeletionOptionalParams, + BatchContext as Client, + CreateCertificateOptionalParams, + CreateJobOptionalParams, + CreateJobScheduleOptionalParams, + CreateNodeUserOptionalParams, + CreatePoolOptionalParams, + CreateTaskCollectionOptionalParams, + CreateTaskOptionalParams, + DeleteCertificateOptionalParams, + DeleteJobOptionalParams, + DeleteJobScheduleOptionalParams, + DeleteNodeFileOptionalParams, + DeleteNodeUserOptionalParams, + DeletePoolOptionalParams, + DeleteTaskFileOptionalParams, + DeleteTaskOptionalParams, + DisableJobOptionalParams, + DisableJobScheduleOptionalParams, + DisableNodeSchedulingOptionalParams, + DisablePoolAutoScaleOptionalParams, + EnableJobOptionalParams, + EnableJobScheduleOptionalParams, + EnableNodeSchedulingOptionalParams, + EnablePoolAutoScaleOptionalParams, + EvaluatePoolAutoScaleOptionalParams, + GetApplicationOptionalParams, + GetCertificateOptionalParams, + GetJobOptionalParams, + GetJobScheduleOptionalParams, + GetJobTaskCountsOptionalParams, + GetNodeExtensionOptionalParams, + GetNodeFileOptionalParams, + GetNodeFilePropertiesOptionalParams, + GetNodeOptionalParams, + GetNodeRemoteDesktopFileOptionalParams, + GetNodeRemoteLoginSettingsOptionalParams, + GetPoolOptionalParams, + GetTaskFileOptionalParams, + GetTaskFilePropertiesOptionalParams, + GetTaskOptionalParams, + JobScheduleExistsOptionalParams, + ListApplicationsOptionalParams, + ListCertificatesOptionalParams, + ListJobPreparationAndReleaseTaskStatusOptionalParams, + ListJobSchedulesOptionalParams, + ListJobsFromScheduleOptionalParams, + ListJobsOptionalParams, + ListNodeExtensionsOptionalParams, + ListNodeFilesOptionalParams, + ListNodesOptionalParams, + ListPoolNodeCountsOptionalParams, + ListPoolsOptionalParams, + ListPoolUsageMetricsOptionalParams, + ListSubTasksOptionalParams, + ListSupportedImagesOptionalParams, + ListTaskFilesOptionalParams, + ListTasksOptionalParams, + PoolExistsOptionalParams, + ReactivateTaskOptionalParams, + RebootNodeOptionalParams, + ReimageNodeOptionalParams, + RemoveNodesOptionalParams, + ReplaceJobOptionalParams, + ReplaceJobScheduleOptionalParams, + ReplaceNodeUserOptionalParams, + ReplacePoolPropertiesOptionalParams, + ReplaceTaskOptionalParams, + ResizePoolOptionalParams, + StopPoolResizeOptionalParams, + TerminateJobOptionalParams, + TerminateJobScheduleOptionalParams, + TerminateTaskOptionalParams, + UpdateJobOptionalParams, + UpdateJobScheduleOptionalParams, + UpdatePoolOptionalParams, + UploadNodeLogsOptionalParams, +} from "./index.js"; +import { BatchNodeUserCreateOptions, + batchNodeUserCreateOptionsSerializer, BatchNodeUserUpdateOptions, + batchNodeUserUpdateOptionsSerializer, BatchNode, + batchNodeDeserializer, NodeRebootOptions, + nodeRebootOptionsSerializer, NodeReimageOptions, + nodeReimageOptionsSerializer, NodeDisableSchedulingOptions, + nodeDisableSchedulingOptionsSerializer, BatchNodeRemoteLoginSettingsResult, + batchNodeRemoteLoginSettingsResultDeserializer, UploadBatchServiceLogsOptions, + uploadBatchServiceLogsOptionsSerializer, UploadBatchServiceLogsResult, + uploadBatchServiceLogsResultDeserializer, + _BatchNodeListResult, + _batchNodeListResultDeserializer, NodeVMExtension, + nodeVMExtensionDeserializer, + _NodeVMExtensionList, + _nodeVMExtensionListDeserializer, + _NodeFileListResult, + _nodeFileListResultDeserializer, NodeFile, BatchTaskCreateOptions, + batchTaskCreateOptionsSerializer, + _BatchTaskListResult, + _batchTaskListResultDeserializer, BatchTask, + batchTaskSerializer, + batchTaskDeserializer, BatchTaskCollection, + batchTaskCollectionSerializer, TaskAddCollectionResult, + taskAddCollectionResultDeserializer, BatchTaskListSubtasksResult, + batchTaskListSubtasksResultDeserializer, BatchJobSchedule, + batchJobScheduleSerializer, + batchJobScheduleDeserializer, BatchJobScheduleUpdateOptions, + batchJobScheduleUpdateOptionsSerializer, BatchJobScheduleCreateOptions, + batchJobScheduleCreateOptionsSerializer, + _BatchJobScheduleListResult, + _batchJobScheduleListResultDeserializer, BatchCertificate, + batchCertificateSerializer, + batchCertificateDeserializer, + _CertificateListResult, + _certificateListResultDeserializer, BatchJob, + batchJobSerializer, + batchJobDeserializer, BatchJobUpdateOptions, + batchJobUpdateOptionsSerializer, BatchJobDisableOptions, + batchJobDisableOptionsSerializer, BatchJobTerminateOptions, + batchJobTerminateOptionsSerializer, BatchJobCreateOptions, + batchJobCreateOptionsSerializer, + _BatchJobListResult, + _batchJobListResultDeserializer, + _BatchJobListPreparationAndReleaseTaskStatusResult, + _batchJobListPreparationAndReleaseTaskStatusResultDeserializer, JobPreparationAndReleaseTaskExecutionInformation, TaskCountsResult, + taskCountsResultDeserializer, + _AccountListSupportedImagesResult, + _accountListSupportedImagesResultDeserializer, ImageInformation, + _PoolNodeCountsListResult, + _poolNodeCountsListResultDeserializer, PoolNodeCounts, + _PoolListUsageMetricsResult, + _poolListUsageMetricsResultDeserializer, PoolUsageMetrics, BatchPoolCreateOptions, + batchPoolCreateOptionsSerializer, + _BatchPoolListResult, + _batchPoolListResultDeserializer, BatchPool, + batchPoolDeserializer, AutoScaleRun, + autoScaleRunDeserializer, BatchPoolUpdateOptions, + batchPoolUpdateOptionsSerializer, BatchPoolEnableAutoScaleOptions, + batchPoolEnableAutoScaleOptionsSerializer, BatchPoolEvaluateAutoScaleOptions, + batchPoolEvaluateAutoScaleOptionsSerializer, BatchPoolResizeOptions, + batchPoolResizeOptionsSerializer, BatchPoolReplaceOptions, + batchPoolReplaceOptionsSerializer, NodeRemoveOptions, - BatchApplication, - _AccountListSupportedImagesResult, + nodeRemoveOptionsSerializer, _ApplicationListResult, - _BatchJobListPreparationAndReleaseTaskStatusResult, - _BatchJobListResult, - _BatchJobScheduleListResult, - _BatchNodeListResult, - _BatchPoolListResult, - _BatchTaskListResult, - _CertificateListResult, - _NodeFileListResult, - _NodeVMExtensionList, - _PoolListUsageMetricsResult, - _PoolNodeCountsListResult, + _applicationListResultDeserializer, + BatchApplication, + batchApplicationDeserializer, } from "../models/models.js"; -import { BatchContext as Client } from "./index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../static-helpers/pagingHelpers.js"; -import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; import { - ListApplicationsOptionalParams, - GetApplicationOptionalParams, - ListPoolUsageMetricsOptionalParams, - CreatePoolOptionalParams, - ListPoolsOptionalParams, - DeletePoolOptionalParams, - PoolExistsOptionalParams, - GetPoolOptionalParams, - UpdatePoolOptionalParams, - DisablePoolAutoScaleOptionalParams, - EnablePoolAutoScaleOptionalParams, - EvaluatePoolAutoScaleOptionalParams, - ResizePoolOptionalParams, - StopPoolResizeOptionalParams, - ReplacePoolPropertiesOptionalParams, - RemoveNodesOptionalParams, - ListSupportedImagesOptionalParams, - ListPoolNodeCountsOptionalParams, - DeleteJobOptionalParams, - GetJobOptionalParams, - UpdateJobOptionalParams, - ReplaceJobOptionalParams, - DisableJobOptionalParams, - EnableJobOptionalParams, - TerminateJobOptionalParams, - CreateJobOptionalParams, - ListJobsOptionalParams, - ListJobsFromScheduleOptionalParams, - ListJobPreparationAndReleaseTaskStatusOptionalParams, - GetJobTaskCountsOptionalParams, - CreateCertificateOptionalParams, - ListCertificatesOptionalParams, - CancelCertificateDeletionOptionalParams, - DeleteCertificateOptionalParams, - GetCertificateOptionalParams, - JobScheduleExistsOptionalParams, - DeleteJobScheduleOptionalParams, - GetJobScheduleOptionalParams, - UpdateJobScheduleOptionalParams, - ReplaceJobScheduleOptionalParams, - DisableJobScheduleOptionalParams, - EnableJobScheduleOptionalParams, - TerminateJobScheduleOptionalParams, - CreateJobScheduleOptionalParams, - ListJobSchedulesOptionalParams, - CreateTaskOptionalParams, - ListTasksOptionalParams, - CreateTaskCollectionOptionalParams, - DeleteTaskOptionalParams, - GetTaskOptionalParams, - ReplaceTaskOptionalParams, - ListSubTasksOptionalParams, - TerminateTaskOptionalParams, - ReactivateTaskOptionalParams, - DeleteTaskFileOptionalParams, - GetTaskFileOptionalParams, - GetTaskFilePropertiesOptionalParams, - ListTaskFilesOptionalParams, - CreateNodeUserOptionalParams, - DeleteNodeUserOptionalParams, - ReplaceNodeUserOptionalParams, - GetNodeOptionalParams, - RebootNodeOptionalParams, - ReimageNodeOptionalParams, - DisableNodeSchedulingOptionalParams, - EnableNodeSchedulingOptionalParams, - GetNodeRemoteLoginSettingsOptionalParams, - GetNodeRemoteDesktopFileOptionalParams, - UploadNodeLogsOptionalParams, - ListNodesOptionalParams, - GetNodeExtensionOptionalParams, - ListNodeExtensionsOptionalParams, - DeleteNodeFileOptionalParams, - GetNodeFileOptionalParams, - GetNodeFilePropertiesOptionalParams, - ListNodeFilesOptionalParams, -} from "../models/options.js"; + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { stringToUint8Array } from "@azure/core-util"; export function _listApplicationsSend( context: Client, @@ -202,19 +223,7 @@ export async function _listApplicationsDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - id: p["id"], - displayName: p["displayName"], - versions: p["versions"], - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _applicationListResultDeserializer(result.body); } /** @@ -261,11 +270,7 @@ export async function _getApplicationDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - displayName: result.body["displayName"], - versions: result.body["versions"], - }; + return batchApplicationDeserializer(result.body); } /** @@ -311,21 +316,7 @@ export async function _listPoolUsageMetricsDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - poolId: p["poolId"], - startTime: new Date(p["startTime"]), - endTime: new Date(p["endTime"]), - vmSize: p["vmSize"], - totalCoreHours: p["totalCoreHours"], - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _poolListUsageMetricsResultDeserializer(result.body); } /** @@ -365,60 +356,7 @@ export function _createPoolSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - id: body["id"], - displayName: body["displayName"], - vmSize: body["vmSize"], - cloudServiceConfiguration: !body.cloudServiceConfiguration - ? body.cloudServiceConfiguration - : cloudServiceConfigurationSerializer(body.cloudServiceConfiguration), - virtualMachineConfiguration: !body.virtualMachineConfiguration - ? body.virtualMachineConfiguration - : virtualMachineConfigurationSerializer( - body.virtualMachineConfiguration, - ), - resizeTimeout: body["resizeTimeout"], - targetDedicatedNodes: body["targetDedicatedNodes"], - targetLowPriorityNodes: body["targetLowPriorityNodes"], - enableAutoScale: body["enableAutoScale"], - autoScaleFormula: body["autoScaleFormula"], - autoScaleEvaluationInterval: body["autoScaleEvaluationInterval"], - enableInterNodeCommunication: body["enableInterNodeCommunication"], - networkConfiguration: !body.networkConfiguration - ? body.networkConfiguration - : networkConfigurationSerializer(body.networkConfiguration), - startTask: !body.startTask - ? body.startTask - : startTaskSerializer(body.startTask), - certificateReferences: - body["certificateReferences"] === undefined - ? body["certificateReferences"] - : body["certificateReferences"].map(certificateReferenceSerializer), - applicationPackageReferences: - body["applicationPackageReferences"] === undefined - ? body["applicationPackageReferences"] - : body["applicationPackageReferences"].map( - applicationPackageReferenceSerializer, - ), - applicationLicenses: body["applicationLicenses"], - taskSlotsPerNode: body["taskSlotsPerNode"], - taskSchedulingPolicy: !body.taskSchedulingPolicy - ? body.taskSchedulingPolicy - : taskSchedulingPolicySerializer(body.taskSchedulingPolicy), - userAccounts: - body["userAccounts"] === undefined - ? body["userAccounts"] - : body["userAccounts"].map(userAccountSerializer), - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map(metadataItemSerializer), - mountConfiguration: - body["mountConfiguration"] === undefined - ? body["mountConfiguration"] - : body["mountConfiguration"].map(mountConfigurationSerializer), - targetNodeCommunicationMode: body["targetNodeCommunicationMode"], - }, + body: batchPoolCreateOptionsSerializer(body), }); } @@ -451,19 +389,25 @@ export function _listPoolsSend( context: Client, options: ListPoolsOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/pools") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/pools").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); } export async function _listPoolsDeserialize( @@ -474,581 +418,7 @@ export async function _listPoolsDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - id: p["id"], - displayName: p["displayName"], - url: p["url"], - eTag: p["eTag"], - lastModified: - p["lastModified"] !== undefined - ? new Date(p["lastModified"]) - : undefined, - creationTime: - p["creationTime"] !== undefined - ? new Date(p["creationTime"]) - : undefined, - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - allocationState: p["allocationState"], - allocationStateTransitionTime: - p["allocationStateTransitionTime"] !== undefined - ? new Date(p["allocationStateTransitionTime"]) - : undefined, - vmSize: p["vmSize"], - cloudServiceConfiguration: !p.cloudServiceConfiguration - ? undefined - : { - osFamily: p.cloudServiceConfiguration?.["osFamily"], - osVersion: p.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !p.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - p.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - p.virtualMachineConfiguration?.imageReference["offer"], - sku: p.virtualMachineConfiguration?.imageReference["sku"], - version: - p.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - p.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - p.virtualMachineConfiguration?.imageReference[ - "exactVersion" - ], - }, - nodeAgentSkuId: - p.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !p.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - p.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - p.virtualMachineConfiguration?.["dataDisks"] === undefined - ? p.virtualMachineConfiguration?.["dataDisks"] - : p.virtualMachineConfiguration?.["dataDisks"].map( - (p: any) => { - return { - lun: p["lun"], - caching: p["caching"], - diskSizeGb: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - }; - }, - ), - licenseType: p.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !p.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: p.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - p.virtualMachineConfiguration - ?.containerConfiguration?.["containerImageNames"], - containerRegistries: - p.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? p.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : p.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p: any) => { - return { - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - }, - diskEncryptionConfiguration: !p.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - p.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !p.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - p.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: - p.virtualMachineConfiguration?.["extensions"] === - undefined - ? p.virtualMachineConfiguration?.["extensions"] - : p.virtualMachineConfiguration?.["extensions"].map( - (p: any) => { - return { - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - }; - }, - ), - osDisk: !p.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !p - .virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - p.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings?.["placement"], - }, - }, - }, - resizeTimeout: p["resizeTimeout"], - resizeErrors: - p["resizeErrors"] === undefined - ? p["resizeErrors"] - : p["resizeErrors"].map((p: any) => { - return { - code: p["code"], - message: p["message"], - values: - p["values"] === undefined - ? p["values"] - : p["values"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }; - }), - currentDedicatedNodes: p["currentDedicatedNodes"], - currentLowPriorityNodes: p["currentLowPriorityNodes"], - targetDedicatedNodes: p["targetDedicatedNodes"], - targetLowPriorityNodes: p["targetLowPriorityNodes"], - enableAutoScale: p["enableAutoScale"], - autoScaleFormula: p["autoScaleFormula"], - autoScaleEvaluationInterval: p["autoScaleEvaluationInterval"], - autoScaleRun: !p.autoScaleRun - ? undefined - : { - timestamp: new Date(p.autoScaleRun?.["timestamp"]), - results: p.autoScaleRun?.["results"], - error: !p.autoScaleRun?.error - ? undefined - : { - code: p.autoScaleRun?.error?.["code"], - message: p.autoScaleRun?.error?.["message"], - values: - p.autoScaleRun?.error?.["values"] === undefined - ? p.autoScaleRun?.error?.["values"] - : p.autoScaleRun?.error?.["values"].map( - (p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }, - ), - }, - }, - enableInterNodeCommunication: p["enableInterNodeCommunication"], - networkConfiguration: !p.networkConfiguration - ? undefined - : { - subnetId: p.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - p.networkConfiguration?.["dynamicVNetAssignmentScope"], - endpointConfiguration: !p.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNatPools: - p.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ].map((p: any) => { - return { - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === undefined - ? p["networkSecurityGroupRules"] - : p["networkSecurityGroupRules"].map( - (p: any) => { - return { - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - }; - }, - ), - }; - }), - }, - publicIpAddressConfiguration: !p.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - ipAddressProvisioningType: - p.networkConfiguration - ?.publicIPAddressConfiguration?.["provision"], - ipAddressIds: - p.networkConfiguration - ?.publicIPAddressConfiguration?.["ipAddressIds"], - }, - enableAcceleratedNetworking: - p.networkConfiguration?.["enableAcceleratedNetworking"], - }, - startTask: !p.startTask - ? undefined - : { - commandLine: p.startTask?.["commandLine"], - containerSettings: !p.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.startTask?.containerSettings?.["imageName"], - registry: !p.startTask?.containerSettings?.registry - ? undefined - : { - username: - p.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - p.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.startTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - p.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.startTask?.["resourceFiles"] === undefined - ? p.startTask?.["resourceFiles"] - : p.startTask?.["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - environmentSettings: - p.startTask?.["environmentSettings"] === undefined - ? p.startTask?.["environmentSettings"] - : p.startTask?.["environmentSettings"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - userIdentity: !p.startTask?.userIdentity - ? undefined - : { - username: p.startTask?.userIdentity?.["username"], - autoUser: !p.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.startTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: p.startTask?.["maxTaskRetryCount"], - waitForSuccess: p.startTask?.["waitForSuccess"], - }, - certificateReferences: - p["certificateReferences"] === undefined - ? p["certificateReferences"] - : p["certificateReferences"].map((p: any) => { - return { - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }; - }), - applicationPackageReferences: - p["applicationPackageReferences"] === undefined - ? p["applicationPackageReferences"] - : p["applicationPackageReferences"].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - applicationLicenses: p["applicationLicenses"], - taskSlotsPerNode: p["taskSlotsPerNode"], - taskSchedulingPolicy: !p.taskSchedulingPolicy - ? undefined - : { nodeFillType: p.taskSchedulingPolicy?.["nodeFillType"] }, - userAccounts: - p["userAccounts"] === undefined - ? p["userAccounts"] - : p["userAccounts"].map((p: any) => { - return { - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - }; - }), - metadata: - p["metadata"] === undefined - ? p["metadata"] - : p["metadata"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - stats: !p.stats - ? undefined - : { - url: p.stats?.["url"], - startTime: new Date(p.stats?.["startTime"]), - lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), - usageStats: !p.stats?.usageStats - ? undefined - : { - startTime: new Date( - p.stats?.usageStats?.["startTime"], - ), - lastUpdateTime: new Date( - p.stats?.usageStats?.["lastUpdateTime"], - ), - dedicatedCoreTime: - p.stats?.usageStats?.["dedicatedCoreTime"], - }, - resourceStats: !p.stats?.resourceStats - ? undefined - : { - startTime: new Date( - p.stats?.resourceStats?.["startTime"], - ), - lastUpdateTime: new Date( - p.stats?.resourceStats?.["lastUpdateTime"], - ), - avgCpuPercentage: - p.stats?.resourceStats?.["avgCPUPercentage"], - avgMemoryGiB: - p.stats?.resourceStats?.["avgMemoryGiB"], - peakMemoryGiB: - p.stats?.resourceStats?.["peakMemoryGiB"], - avgDiskGiB: p.stats?.resourceStats?.["avgDiskGiB"], - peakDiskGiB: p.stats?.resourceStats?.["peakDiskGiB"], - diskReadIOps: - p.stats?.resourceStats?.["diskReadIOps"], - diskWriteIOps: - p.stats?.resourceStats?.["diskWriteIOps"], - diskReadGiB: p.stats?.resourceStats?.["diskReadGiB"], - diskWriteGiB: - p.stats?.resourceStats?.["diskWriteGiB"], - networkReadGiB: - p.stats?.resourceStats?.["networkReadGiB"], - networkWriteGiB: - p.stats?.resourceStats?.["networkWriteGiB"], - }, - }, - mountConfiguration: - p["mountConfiguration"] === undefined - ? p["mountConfiguration"] - : p["mountConfiguration"].map((p: any) => { - return { - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.["accountKey"], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - }; - }), - identity: !p.identity - ? undefined - : { - type: p.identity?.["type"], - userAssignedIdentities: - p.identity?.["userAssignedIdentities"] === undefined - ? p.identity?.["userAssignedIdentities"] - : p.identity?.["userAssignedIdentities"].map( - (p: any) => { - return { - resourceId: p["resourceId"], - clientId: p["clientId"], - principalId: p["principalId"], - }; - }, - ), - }, - targetNodeCommunicationMode: p["targetNodeCommunicationMode"], - currentNodeCommunicationMode: p["currentNodeCommunicationMode"], - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _batchPoolListResultDeserializer(result.body); } /** Lists all of the Pools in the specified Account. */ @@ -1082,10 +452,18 @@ export function _deletePoolSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -1146,10 +524,18 @@ export function _poolExistsSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -1185,31 +571,45 @@ export function _getPoolSend( poolId: string, options: GetPoolOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/pools/{poolId}", poolId) - .get({ - ...operationOptionsToRequestParameters(options), - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/pools/{poolId}", poolId).get({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); } export async function _getPoolDeserialize( @@ -1220,518 +620,7 @@ export async function _getPoolDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - displayName: result.body["displayName"], - url: result.body["url"], - eTag: result.body["eTag"], - lastModified: - result.body["lastModified"] !== undefined - ? new Date(result.body["lastModified"]) - : undefined, - creationTime: - result.body["creationTime"] !== undefined - ? new Date(result.body["creationTime"]) - : undefined, - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - allocationState: result.body["allocationState"], - allocationStateTransitionTime: - result.body["allocationStateTransitionTime"] !== undefined - ? new Date(result.body["allocationStateTransitionTime"]) - : undefined, - vmSize: result.body["vmSize"], - cloudServiceConfiguration: !result.body.cloudServiceConfiguration - ? undefined - : { - osFamily: result.body.cloudServiceConfiguration?.["osFamily"], - osVersion: result.body.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !result.body.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - result.body.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - result.body.virtualMachineConfiguration?.imageReference["offer"], - sku: result.body.virtualMachineConfiguration?.imageReference["sku"], - version: - result.body.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - result.body.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - result.body.virtualMachineConfiguration?.imageReference[ - "exactVersion" - ], - }, - nodeAgentSkuId: - result.body.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !result.body.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - result.body.virtualMachineConfiguration - ?.windowsConfiguration?.["enableAutomaticUpdates"], - }, - dataDisks: - result.body.virtualMachineConfiguration?.["dataDisks"] === undefined - ? result.body.virtualMachineConfiguration?.["dataDisks"] - : result.body.virtualMachineConfiguration?.["dataDisks"].map( - (p: any) => { - return { - lun: p["lun"], - caching: p["caching"], - diskSizeGb: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - }; - }, - ), - licenseType: result.body.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !result.body.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: result.body.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - result.body.virtualMachineConfiguration - ?.containerConfiguration?.["containerImageNames"], - containerRegistries: - result.body.virtualMachineConfiguration - ?.containerConfiguration?.["containerRegistries"] === - undefined - ? result.body.virtualMachineConfiguration - ?.containerConfiguration?.["containerRegistries"] - : result.body.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p: any) => { - return { - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: p.identityReference?.["resourceId"], - }, - }; - }), - }, - diskEncryptionConfiguration: !result.body.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - result.body.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !result.body.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - result.body.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: - result.body.virtualMachineConfiguration?.["extensions"] === - undefined - ? result.body.virtualMachineConfiguration?.["extensions"] - : result.body.virtualMachineConfiguration?.["extensions"].map( - (p: any) => { - return { - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: p["provisionAfterExtensions"], - }; - }, - ), - osDisk: !result.body.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !result.body - .virtualMachineConfiguration?.osDisk?.ephemeralOSDiskSettings - ? undefined - : { - placement: - result.body.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings?.["placement"], - }, - }, - }, - resizeTimeout: result.body["resizeTimeout"], - resizeErrors: - result.body["resizeErrors"] === undefined - ? result.body["resizeErrors"] - : result.body["resizeErrors"].map((p: any) => { - return { - code: p["code"], - message: p["message"], - values: - p["values"] === undefined - ? p["values"] - : p["values"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }; - }), - currentDedicatedNodes: result.body["currentDedicatedNodes"], - currentLowPriorityNodes: result.body["currentLowPriorityNodes"], - targetDedicatedNodes: result.body["targetDedicatedNodes"], - targetLowPriorityNodes: result.body["targetLowPriorityNodes"], - enableAutoScale: result.body["enableAutoScale"], - autoScaleFormula: result.body["autoScaleFormula"], - autoScaleEvaluationInterval: result.body["autoScaleEvaluationInterval"], - autoScaleRun: !result.body.autoScaleRun - ? undefined - : { - timestamp: new Date(result.body.autoScaleRun?.["timestamp"]), - results: result.body.autoScaleRun?.["results"], - error: !result.body.autoScaleRun?.error - ? undefined - : { - code: result.body.autoScaleRun?.error?.["code"], - message: result.body.autoScaleRun?.error?.["message"], - values: - result.body.autoScaleRun?.error?.["values"] === undefined - ? result.body.autoScaleRun?.error?.["values"] - : result.body.autoScaleRun?.error?.["values"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - }, - }, - enableInterNodeCommunication: result.body["enableInterNodeCommunication"], - networkConfiguration: !result.body.networkConfiguration - ? undefined - : { - subnetId: result.body.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - result.body.networkConfiguration?.["dynamicVNetAssignmentScope"], - endpointConfiguration: !result.body.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNatPools: - result.body.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ].map((p: any) => { - return { - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: p["frontendPortRangeStart"], - frontendPortRangeEnd: p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === undefined - ? p["networkSecurityGroupRules"] - : p["networkSecurityGroupRules"].map((p: any) => { - return { - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - }; - }), - }; - }), - }, - publicIpAddressConfiguration: !result.body.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - ipAddressProvisioningType: - result.body.networkConfiguration - ?.publicIPAddressConfiguration?.["provision"], - ipAddressIds: - result.body.networkConfiguration - ?.publicIPAddressConfiguration?.["ipAddressIds"], - }, - enableAcceleratedNetworking: - result.body.networkConfiguration?.["enableAcceleratedNetworking"], - }, - startTask: !result.body.startTask - ? undefined - : { - commandLine: result.body.startTask?.["commandLine"], - containerSettings: !result.body.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.startTask?.containerSettings?.["imageName"], - registry: !result.body.startTask?.containerSettings?.registry - ? undefined - : { - username: - result.body.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - result.body.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - result.body.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !result.body.startTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - result.body.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - result.body.startTask?.["resourceFiles"] === undefined - ? result.body.startTask?.["resourceFiles"] - : result.body.startTask?.["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }; - }), - environmentSettings: - result.body.startTask?.["environmentSettings"] === undefined - ? result.body.startTask?.["environmentSettings"] - : result.body.startTask?.["environmentSettings"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - userIdentity: !result.body.startTask?.userIdentity - ? undefined - : { - username: result.body.startTask?.userIdentity?.["username"], - autoUser: !result.body.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.startTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - result.body.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: result.body.startTask?.["maxTaskRetryCount"], - waitForSuccess: result.body.startTask?.["waitForSuccess"], - }, - certificateReferences: - result.body["certificateReferences"] === undefined - ? result.body["certificateReferences"] - : result.body["certificateReferences"].map((p: any) => { - return { - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }; - }), - applicationPackageReferences: - result.body["applicationPackageReferences"] === undefined - ? result.body["applicationPackageReferences"] - : result.body["applicationPackageReferences"].map((p: any) => { - return { applicationId: p["applicationId"], version: p["version"] }; - }), - applicationLicenses: result.body["applicationLicenses"], - taskSlotsPerNode: result.body["taskSlotsPerNode"], - taskSchedulingPolicy: !result.body.taskSchedulingPolicy - ? undefined - : { nodeFillType: result.body.taskSchedulingPolicy?.["nodeFillType"] }, - userAccounts: - result.body["userAccounts"] === undefined - ? result.body["userAccounts"] - : result.body["userAccounts"].map((p: any) => { - return { - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { loginMode: p.windowsUserConfiguration?.["loginMode"] }, - }; - }), - metadata: - result.body["metadata"] === undefined - ? result.body["metadata"] - : result.body["metadata"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - stats: !result.body.stats - ? undefined - : { - url: result.body.stats?.["url"], - startTime: new Date(result.body.stats?.["startTime"]), - lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), - usageStats: !result.body.stats?.usageStats - ? undefined - : { - startTime: new Date( - result.body.stats?.usageStats?.["startTime"], - ), - lastUpdateTime: new Date( - result.body.stats?.usageStats?.["lastUpdateTime"], - ), - dedicatedCoreTime: - result.body.stats?.usageStats?.["dedicatedCoreTime"], - }, - resourceStats: !result.body.stats?.resourceStats - ? undefined - : { - startTime: new Date( - result.body.stats?.resourceStats?.["startTime"], - ), - lastUpdateTime: new Date( - result.body.stats?.resourceStats?.["lastUpdateTime"], - ), - avgCpuPercentage: - result.body.stats?.resourceStats?.["avgCPUPercentage"], - avgMemoryGiB: - result.body.stats?.resourceStats?.["avgMemoryGiB"], - peakMemoryGiB: - result.body.stats?.resourceStats?.["peakMemoryGiB"], - avgDiskGiB: result.body.stats?.resourceStats?.["avgDiskGiB"], - peakDiskGiB: result.body.stats?.resourceStats?.["peakDiskGiB"], - diskReadIOps: - result.body.stats?.resourceStats?.["diskReadIOps"], - diskWriteIOps: - result.body.stats?.resourceStats?.["diskWriteIOps"], - diskReadGiB: result.body.stats?.resourceStats?.["diskReadGiB"], - diskWriteGiB: - result.body.stats?.resourceStats?.["diskWriteGiB"], - networkReadGiB: - result.body.stats?.resourceStats?.["networkReadGiB"], - networkWriteGiB: - result.body.stats?.resourceStats?.["networkWriteGiB"], - }, - }, - mountConfiguration: - result.body["mountConfiguration"] === undefined - ? result.body["mountConfiguration"] - : result.body["mountConfiguration"].map((p: any) => { - return { - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.["accountName"], - containerName: - p.azureBlobFileSystemConfiguration?.["containerName"], - accountKey: - p.azureBlobFileSystemConfiguration?.["accountKey"], - sasKey: p.azureBlobFileSystemConfiguration?.["sasKey"], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.["blobfuseOptions"], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p.azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: !p.azureFileShareConfiguration - ? undefined - : { - accountName: p.azureFileShareConfiguration?.["accountName"], - azureFileUrl: - p.azureFileShareConfiguration?.["azureFileUrl"], - accountKey: p.azureFileShareConfiguration?.["accountKey"], - relativeMountPath: - p.azureFileShareConfiguration?.["relativeMountPath"], - mountOptions: - p.azureFileShareConfiguration?.["mountOptions"], - }, - }; - }), - identity: !result.body.identity - ? undefined - : { - type: result.body.identity?.["type"], - userAssignedIdentities: - result.body.identity?.["userAssignedIdentities"] === undefined - ? result.body.identity?.["userAssignedIdentities"] - : result.body.identity?.["userAssignedIdentities"].map( - (p: any) => { - return { - resourceId: p["resourceId"], - clientId: p["clientId"], - principalId: p["principalId"], - }; - }, - ), - }, - targetNodeCommunicationMode: result.body["targetNodeCommunicationMode"], - currentNodeCommunicationMode: result.body["currentNodeCommunicationMode"], - }; + return batchPoolDeserializer(result.body); } /** Gets information about the specified Pool. */ @@ -1765,36 +654,25 @@ export function _updatePoolSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - startTask: !body.startTask - ? body.startTask - : startTaskSerializer(body.startTask), - certificateReferences: - body["certificateReferences"] === undefined - ? body["certificateReferences"] - : body["certificateReferences"].map(certificateReferenceSerializer), - applicationPackageReferences: - body["applicationPackageReferences"] === undefined - ? body["applicationPackageReferences"] - : body["applicationPackageReferences"].map( - applicationPackageReferenceSerializer, - ), - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map(metadataItemSerializer), - targetNodeCommunicationMode: body["targetNodeCommunicationMode"], - }, + body: batchPoolUpdateOptionsSerializer(body), }); } @@ -1882,20 +760,25 @@ export function _enablePoolAutoScaleSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - autoScaleFormula: body["autoScaleFormula"], - autoScaleEvaluationInterval: body["autoScaleEvaluationInterval"], - }, + body: batchPoolEnableAutoScaleOptionsSerializer(body), }); } @@ -1945,7 +828,7 @@ export function _evaluatePoolAutoScaleSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { autoScaleFormula: body["autoScaleFormula"] }, + body: batchPoolEvaluateAutoScaleOptionsSerializer(body), }); } @@ -1957,22 +840,7 @@ export async function _evaluatePoolAutoScaleDeserialize( throw createRestError(result); } - return { - timestamp: new Date(result.body["timestamp"]), - results: result.body["results"], - error: !result.body.error - ? undefined - : { - code: result.body.error?.["code"], - message: result.body.error?.["message"], - values: - result.body.error?.["values"] === undefined - ? result.body.error?.["values"] - : result.body.error?.["values"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }, - }; + return autoScaleRunDeserializer(result.body); } /** @@ -2016,22 +884,25 @@ export function _resizePoolSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - targetDedicatedNodes: body["targetDedicatedNodes"], - targetLowPriorityNodes: body["targetLowPriorityNodes"], - resizeTimeout: body["resizeTimeout"], - nodeDeallocationOption: body["nodeDeallocationOption"], - }, + body: batchPoolResizeOptionsSerializer(body), }); } @@ -2082,10 +953,18 @@ export function _stopPoolResizeSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -2141,19 +1020,7 @@ export function _replacePoolPropertiesSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - startTask: !body.startTask - ? body.startTask - : startTaskSerializer(body.startTask), - certificateReferences: body["certificateReferences"].map( - certificateReferenceSerializer, - ), - applicationPackageReferences: body["applicationPackageReferences"].map( - applicationPackageReferenceSerializer, - ), - metadata: body["metadata"].map(metadataItemSerializer), - targetNodeCommunicationMode: body["targetNodeCommunicationMode"], - }, + body: batchPoolReplaceOptionsSerializer(body), }); } @@ -2209,21 +1076,25 @@ export function _removeNodesSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - nodeList: body["nodeList"], - resizeTimeout: body["resizeTimeout"], - nodeDeallocationOption: body["nodeDeallocationOption"], - }, + body: nodeRemoveOptionsSerializer(body), }); } @@ -2277,33 +1148,7 @@ export async function _listSupportedImagesDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - nodeAgentSkuId: p["nodeAgentSKUId"], - imageReference: { - publisher: p.imageReference["publisher"], - offer: p.imageReference["offer"], - sku: p.imageReference["sku"], - version: p.imageReference["version"], - virtualMachineImageId: - p.imageReference["virtualMachineImageId"], - exactVersion: p.imageReference["exactVersion"], - }, - osType: p["osType"], - capabilities: p["capabilities"], - batchSupportEndOfLife: - p["batchSupportEndOfLife"] !== undefined - ? new Date(p["batchSupportEndOfLife"]) - : undefined, - verificationType: p["verificationType"], - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _accountListSupportedImagesResultDeserializer(result.body); } /** Lists all Virtual Machine Images supported by the Azure Batch service. */ @@ -2345,53 +1190,7 @@ export async function _listPoolNodeCountsDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - poolId: p["poolId"], - dedicated: !p.dedicated - ? undefined - : { - creating: p.dedicated?.["creating"], - idle: p.dedicated?.["idle"], - offline: p.dedicated?.["offline"], - preempted: p.dedicated?.["preempted"], - rebooting: p.dedicated?.["rebooting"], - reimaging: p.dedicated?.["reimaging"], - running: p.dedicated?.["running"], - starting: p.dedicated?.["starting"], - startTaskFailed: p.dedicated?.["startTaskFailed"], - leavingPool: p.dedicated?.["leavingPool"], - unknown: p.dedicated?.["unknown"], - unusable: p.dedicated?.["unusable"], - waitingForStartTask: p.dedicated?.["waitingForStartTask"], - total: p.dedicated?.["total"], - }, - lowPriority: !p.lowPriority - ? undefined - : { - creating: p.lowPriority?.["creating"], - idle: p.lowPriority?.["idle"], - offline: p.lowPriority?.["offline"], - preempted: p.lowPriority?.["preempted"], - rebooting: p.lowPriority?.["rebooting"], - reimaging: p.lowPriority?.["reimaging"], - running: p.lowPriority?.["running"], - starting: p.lowPriority?.["starting"], - startTaskFailed: p.lowPriority?.["startTaskFailed"], - leavingPool: p.lowPriority?.["leavingPool"], - unknown: p.lowPriority?.["unknown"], - unusable: p.lowPriority?.["unusable"], - waitingForStartTask: p.lowPriority?.["waitingForStartTask"], - total: p.lowPriority?.["total"], - }, - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _poolNodeCountsListResultDeserializer(result.body); } /** @@ -2429,10 +1228,18 @@ export function _deleteJobSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -2477,31 +1284,45 @@ export function _getJobSend( jobId: string, options: GetJobOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/jobs/{jobId}", jobId) - .get({ - ...operationOptionsToRequestParameters(options), - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/jobs/{jobId}", jobId).get({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); } export async function _getJobDeserialize( @@ -2512,1095 +1333,7 @@ export async function _getJobDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - displayName: result.body["displayName"], - usesTaskDependencies: result.body["usesTaskDependencies"], - url: result.body["url"], - eTag: result.body["eTag"], - lastModified: - result.body["lastModified"] !== undefined - ? new Date(result.body["lastModified"]) - : undefined, - creationTime: - result.body["creationTime"] !== undefined - ? new Date(result.body["creationTime"]) - : undefined, - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - previousState: result.body["previousState"], - previousStateTransitionTime: - result.body["previousStateTransitionTime"] !== undefined - ? new Date(result.body["previousStateTransitionTime"]) - : undefined, - priority: result.body["priority"], - allowTaskPreemption: result.body["allowTaskPreemption"], - maxParallelTasks: result.body["maxParallelTasks"], - constraints: !result.body.constraints - ? undefined - : { - maxWallClockTime: result.body.constraints?.["maxWallClockTime"], - maxTaskRetryCount: result.body.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !result.body.jobManagerTask - ? undefined - : { - id: result.body.jobManagerTask?.["id"], - displayName: result.body.jobManagerTask?.["displayName"], - commandLine: result.body.jobManagerTask?.["commandLine"], - containerSettings: !result.body.jobManagerTask?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobManagerTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.jobManagerTask?.containerSettings?.["imageName"], - registry: !result.body.jobManagerTask?.containerSettings - ?.registry - ? undefined - : { - username: - result.body.jobManagerTask?.containerSettings - ?.registry?.["username"], - password: - result.body.jobManagerTask?.containerSettings - ?.registry?.["password"], - registryServer: - result.body.jobManagerTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !result.body.jobManagerTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - result.body.jobManagerTask?.containerSettings - ?.registry?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobManagerTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - result.body.jobManagerTask?.["resourceFiles"] === undefined - ? result.body.jobManagerTask?.["resourceFiles"] - : result.body.jobManagerTask?.["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }; - }), - outputFiles: - result.body.jobManagerTask?.["outputFiles"] === undefined - ? result.body.jobManagerTask?.["outputFiles"] - : result.body.jobManagerTask?.["outputFiles"].map((p: any) => { - return { - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.["resourceId"], - }, - uploadHeaders: - p.destination.container?.["uploadHeaders"] === - undefined - ? p.destination.container?.["uploadHeaders"] - : p.destination.container?.[ - "uploadHeaders" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - }; - }), - environmentSettings: - result.body.jobManagerTask?.["environmentSettings"] === undefined - ? result.body.jobManagerTask?.["environmentSettings"] - : result.body.jobManagerTask?.["environmentSettings"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - constraints: !result.body.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobManagerTask?.constraints?.["maxWallClockTime"], - retentionTime: - result.body.jobManagerTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - result.body.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: result.body.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - result.body.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !result.body.jobManagerTask?.userIdentity - ? undefined - : { - username: - result.body.jobManagerTask?.userIdentity?.["username"], - autoUser: !result.body.jobManagerTask?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobManagerTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - result.body.jobManagerTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - runExclusive: result.body.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - result.body.jobManagerTask?.["applicationPackageReferences"] === - undefined - ? result.body.jobManagerTask?.["applicationPackageReferences"] - : result.body.jobManagerTask?.[ - "applicationPackageReferences" - ].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - authenticationTokenSettings: !result.body.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - result.body.jobManagerTask?.authenticationTokenSettings?.[ - "access" - ], - }, - allowLowPriorityNode: - result.body.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !result.body.jobPreparationTask - ? undefined - : { - id: result.body.jobPreparationTask?.["id"], - commandLine: result.body.jobPreparationTask?.["commandLine"], - containerSettings: !result.body.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobPreparationTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.jobPreparationTask?.containerSettings?.[ - "imageName" - ], - registry: !result.body.jobPreparationTask?.containerSettings - ?.registry - ? undefined - : { - username: - result.body.jobPreparationTask?.containerSettings - ?.registry?.["username"], - password: - result.body.jobPreparationTask?.containerSettings - ?.registry?.["password"], - registryServer: - result.body.jobPreparationTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !result.body.jobPreparationTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - result.body.jobPreparationTask?.containerSettings - ?.registry?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobPreparationTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - result.body.jobPreparationTask?.["resourceFiles"] === undefined - ? result.body.jobPreparationTask?.["resourceFiles"] - : result.body.jobPreparationTask?.["resourceFiles"].map( - (p: any) => { - return { - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }; - }, - ), - environmentSettings: - result.body.jobPreparationTask?.["environmentSettings"] === - undefined - ? result.body.jobPreparationTask?.["environmentSettings"] - : result.body.jobPreparationTask?.["environmentSettings"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - constraints: !result.body.jobPreparationTask?.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - result.body.jobPreparationTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - result.body.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: result.body.jobPreparationTask?.["waitForSuccess"], - userIdentity: !result.body.jobPreparationTask?.userIdentity - ? undefined - : { - username: - result.body.jobPreparationTask?.userIdentity?.["username"], - autoUser: !result.body.jobPreparationTask?.userIdentity - ?.autoUser - ? undefined - : { - scope: - result.body.jobPreparationTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - result.body.jobPreparationTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - rerunOnNodeRebootAfterSuccess: - result.body.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], - }, - jobReleaseTask: !result.body.jobReleaseTask - ? undefined - : { - id: result.body.jobReleaseTask?.["id"], - commandLine: result.body.jobReleaseTask?.["commandLine"], - containerSettings: !result.body.jobReleaseTask?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.jobReleaseTask?.containerSettings?.["imageName"], - registry: !result.body.jobReleaseTask?.containerSettings - ?.registry - ? undefined - : { - username: - result.body.jobReleaseTask?.containerSettings - ?.registry?.["username"], - password: - result.body.jobReleaseTask?.containerSettings - ?.registry?.["password"], - registryServer: - result.body.jobReleaseTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !result.body.jobReleaseTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - result.body.jobReleaseTask?.containerSettings - ?.registry?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobReleaseTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - result.body.jobReleaseTask?.["resourceFiles"] === undefined - ? result.body.jobReleaseTask?.["resourceFiles"] - : result.body.jobReleaseTask?.["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }; - }), - environmentSettings: - result.body.jobReleaseTask?.["environmentSettings"] === undefined - ? result.body.jobReleaseTask?.["environmentSettings"] - : result.body.jobReleaseTask?.["environmentSettings"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - maxWallClockTime: result.body.jobReleaseTask?.["maxWallClockTime"], - retentionTime: result.body.jobReleaseTask?.["retentionTime"], - userIdentity: !result.body.jobReleaseTask?.userIdentity - ? undefined - : { - username: - result.body.jobReleaseTask?.userIdentity?.["username"], - autoUser: !result.body.jobReleaseTask?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobReleaseTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - result.body.jobReleaseTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - }, - commonEnvironmentSettings: - result.body["commonEnvironmentSettings"] === undefined - ? result.body["commonEnvironmentSettings"] - : result.body["commonEnvironmentSettings"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - poolInfo: { - poolId: result.body.poolInfo["poolId"], - autoPoolSpecification: !result.body.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - result.body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - result.body.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - result.body.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !result.body.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "vmSize" - ], - cloudServiceConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool?.cloudServiceConfiguration - ? undefined - : { - osFamily: - result.body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - result.body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" - ], - sku: result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "exactVersion" - ], - }, - nodeAgentSkuId: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] === - undefined - ? result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] - : result.body.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p: any) => { - return { - lun: p["lun"], - caching: p["caching"], - diskSizeGb: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - }; - }), - licenseType: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.containerConfiguration - ? undefined - : { - type: result.body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? result.body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : result.body.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p: any) => { - return { - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - }; - }), - }, - diskEncryptionConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] === - undefined - ? result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] - : result.body.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p: any) => { - return { - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - }; - }), - osDisk: !result.body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !result.body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - result.body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !result.body.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - result.body.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - result.body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - result.body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNatPools: - result.body.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ].map((p: any) => { - return { - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === - undefined - ? p["networkSecurityGroupRules"] - : p["networkSecurityGroupRules"].map( - (p: any) => { - return { - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - }; - }, - ), - }; - }), - }, - publicIpAddressConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - ipAddressProvisioningType: - result.body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.["provision"], - ipAddressIds: - result.body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - result.body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !result.body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.["imageName"], - registry: !result.body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - result.body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["username"], - password: - result.body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - result.body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !result.body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] === undefined - ? result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] - : result.body.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - environmentSettings: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] === undefined - ? result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] - : result.body.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - userIdentity: !result.body.poolInfo - .autoPoolSpecification?.pool?.startTask?.userIdentity - ? undefined - : { - username: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.["username"], - autoUser: !result.body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - result.body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? result.body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : result.body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p: any) => { - return { - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }; - }), - applicationPackageReferences: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? result.body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : result.body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - applicationLicenses: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] === undefined - ? result.body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] - : result.body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p: any) => { - return { - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - }; - }), - metadata: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] === undefined - ? result.body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] - : result.body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - mountConfiguration: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] === undefined - ? result.body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] - : result.body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p: any) => { - return { - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: - p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - }; - }), - targetNodeCommunicationMode: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: result.body["onAllTasksComplete"], - onTaskFailure: result.body["onTaskFailure"], - networkConfiguration: !result.body.networkConfiguration - ? undefined - : { subnetId: result.body.networkConfiguration?.["subnetId"] }, - metadata: - result.body["metadata"] === undefined - ? result.body["metadata"] - : result.body["metadata"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - executionInfo: !result.body.executionInfo - ? undefined - : { - startTime: new Date(result.body.executionInfo?.["startTime"]), - endTime: - result.body.executionInfo?.["endTime"] !== undefined - ? new Date(result.body.executionInfo?.["endTime"]) - : undefined, - poolId: result.body.executionInfo?.["poolId"], - schedulingError: !result.body.executionInfo?.schedulingError - ? undefined - : { - category: - result.body.executionInfo?.schedulingError?.["category"], - code: result.body.executionInfo?.schedulingError?.["code"], - message: - result.body.executionInfo?.schedulingError?.["message"], - details: - result.body.executionInfo?.schedulingError?.["details"] === - undefined - ? result.body.executionInfo?.schedulingError?.["details"] - : result.body.executionInfo?.schedulingError?.[ - "details" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }, - terminateReason: result.body.executionInfo?.["terminateReason"], - }, - stats: !result.body.stats - ? undefined - : { - url: result.body.stats?.["url"], - startTime: new Date(result.body.stats?.["startTime"]), - lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), - userCPUTime: result.body.stats?.["userCPUTime"], - kernelCPUTime: result.body.stats?.["kernelCPUTime"], - wallClockTime: result.body.stats?.["wallClockTime"], - readIOps: result.body.stats?.["readIOps"], - writeIOps: result.body.stats?.["writeIOps"], - readIOGiB: result.body.stats?.["readIOGiB"], - writeIOGiB: result.body.stats?.["writeIOGiB"], - numSucceededTasks: result.body.stats?.["numSucceededTasks"], - numFailedTasks: result.body.stats?.["numFailedTasks"], - numTaskRetries: result.body.stats?.["numTaskRetries"], - waitTime: result.body.stats?.["waitTime"], - }, - }; + return batchJobDeserializer(result.body); } /** Gets information about the specified Job. */ @@ -3634,32 +1367,25 @@ export function _updateJobSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - priority: body["priority"], - allowTaskPreemption: body["allowTaskPreemption"], - maxParallelTasks: body["maxParallelTasks"], - constraints: !body.constraints - ? body.constraints - : jobConstraintsSerializer(body.constraints), - poolInfo: !body.poolInfo - ? body.poolInfo - : poolInformationSerializer(body.poolInfo), - onAllTasksComplete: body["onAllTasksComplete"], - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map(metadataItemSerializer), - }, + body: batchJobUpdateOptionsSerializer(body), }); } @@ -3710,30 +1436,25 @@ export function _replaceJobSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - priority: body["priority"], - allowTaskPreemption: body["allowTaskPreemption"], - maxParallelTasks: body["maxParallelTasks"], - constraints: !body.constraints - ? body.constraints - : jobConstraintsSerializer(body.constraints), - poolInfo: poolInformationSerializer(body.poolInfo), - onAllTasksComplete: body["onAllTasksComplete"], - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map(metadataItemSerializer), - }, + body: batchJobSerializer(body), }); } @@ -3784,17 +1505,25 @@ export function _disableJobSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { disableTasks: body["disableTasks"] }, + body: batchJobDisableOptionsSerializer(body), }); } @@ -3846,10 +1575,18 @@ export function _enableJobSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -3908,20 +1645,25 @@ export function _terminateJobSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: - body === undefined - ? body - : { terminateReason: body["terminateReason"] }, + body: !body ? body : batchJobTerminateOptionsSerializer(body), }); } @@ -3970,42 +1712,7 @@ export function _createJobSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - id: body["id"], - displayName: body["displayName"], - usesTaskDependencies: body["usesTaskDependencies"], - priority: body["priority"], - allowTaskPreemption: body["allowTaskPreemption"], - maxParallelTasks: body["maxParallelTasks"], - constraints: !body.constraints - ? body.constraints - : jobConstraintsSerializer(body.constraints), - jobManagerTask: !body.jobManagerTask - ? body.jobManagerTask - : jobManagerTaskSerializer(body.jobManagerTask), - jobPreparationTask: !body.jobPreparationTask - ? body.jobPreparationTask - : jobPreparationTaskSerializer(body.jobPreparationTask), - jobReleaseTask: !body.jobReleaseTask - ? body.jobReleaseTask - : jobReleaseTaskSerializer(body.jobReleaseTask), - commonEnvironmentSettings: - body["commonEnvironmentSettings"] === undefined - ? body["commonEnvironmentSettings"] - : body["commonEnvironmentSettings"].map( - environmentSettingSerializer, - ), - poolInfo: poolInformationSerializer(body.poolInfo), - onAllTasksComplete: body["onAllTasksComplete"], - onTaskFailure: body["onTaskFailure"], - networkConfiguration: !body.networkConfiguration - ? body.networkConfiguration - : jobNetworkConfigurationSerializer(body.networkConfiguration), - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map(metadataItemSerializer), - }, + body: batchJobCreateOptionsSerializer(body), }); } @@ -4044,19 +1751,25 @@ export function _listJobsSend( context: Client, options: ListJobsOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/jobs") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/jobs").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); } export async function _listJobsDeserialize( @@ -4067,1228 +1780,7 @@ export async function _listJobsDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - id: p["id"], - displayName: p["displayName"], - usesTaskDependencies: p["usesTaskDependencies"], - url: p["url"], - eTag: p["eTag"], - lastModified: - p["lastModified"] !== undefined - ? new Date(p["lastModified"]) - : undefined, - creationTime: - p["creationTime"] !== undefined - ? new Date(p["creationTime"]) - : undefined, - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - priority: p["priority"], - allowTaskPreemption: p["allowTaskPreemption"], - maxParallelTasks: p["maxParallelTasks"], - constraints: !p.constraints - ? undefined - : { - maxWallClockTime: p.constraints?.["maxWallClockTime"], - maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !p.jobManagerTask - ? undefined - : { - id: p.jobManagerTask?.["id"], - displayName: p.jobManagerTask?.["displayName"], - commandLine: p.jobManagerTask?.["commandLine"], - containerSettings: !p.jobManagerTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobManagerTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobManagerTask?.containerSettings?.["imageName"], - registry: !p.jobManagerTask?.containerSettings - ?.registry - ? undefined - : { - username: - p.jobManagerTask?.containerSettings - ?.registry?.["username"], - password: - p.jobManagerTask?.containerSettings - ?.registry?.["password"], - registryServer: - p.jobManagerTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !p.jobManagerTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.jobManagerTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobManagerTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobManagerTask?.["resourceFiles"] === undefined - ? p.jobManagerTask?.["resourceFiles"] - : p.jobManagerTask?.["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - outputFiles: - p.jobManagerTask?.["outputFiles"] === undefined - ? p.jobManagerTask?.["outputFiles"] - : p.jobManagerTask?.["outputFiles"].map((p: any) => { - return { - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.[ - "containerUrl" - ], - identityReference: !p.destination - .container?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: - p.destination.container?.[ - "uploadHeaders" - ] === undefined - ? p.destination.container?.[ - "uploadHeaders" - ] - : p.destination.container?.[ - "uploadHeaders" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - }, - }, - uploadOptions: { - uploadCondition: - p.uploadOptions["uploadCondition"], - }, - }; - }), - environmentSettings: - p.jobManagerTask?.["environmentSettings"] === undefined - ? p.jobManagerTask?.["environmentSettings"] - : p.jobManagerTask?.["environmentSettings"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - constraints: !p.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - p.jobManagerTask?.constraints?.["maxWallClockTime"], - retentionTime: - p.jobManagerTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - p.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: p.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - p.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !p.jobManagerTask?.userIdentity - ? undefined - : { - username: - p.jobManagerTask?.userIdentity?.["username"], - autoUser: !p.jobManagerTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobManagerTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.jobManagerTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - runExclusive: p.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - p.jobManagerTask?.["applicationPackageReferences"] === - undefined - ? p.jobManagerTask?.["applicationPackageReferences"] - : p.jobManagerTask?.[ - "applicationPackageReferences" - ].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - authenticationTokenSettings: !p.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - p.jobManagerTask?.authenticationTokenSettings?.[ - "access" - ], - }, - allowLowPriorityNode: - p.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !p.jobPreparationTask - ? undefined - : { - id: p.jobPreparationTask?.["id"], - commandLine: p.jobPreparationTask?.["commandLine"], - containerSettings: !p.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobPreparationTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobPreparationTask?.containerSettings?.[ - "imageName" - ], - registry: !p.jobPreparationTask?.containerSettings - ?.registry - ? undefined - : { - username: - p.jobPreparationTask?.containerSettings - ?.registry?.["username"], - password: - p.jobPreparationTask?.containerSettings - ?.registry?.["password"], - registryServer: - p.jobPreparationTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !p.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.jobPreparationTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobPreparationTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobPreparationTask?.["resourceFiles"] === undefined - ? p.jobPreparationTask?.["resourceFiles"] - : p.jobPreparationTask?.["resourceFiles"].map( - (p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }, - ), - environmentSettings: - p.jobPreparationTask?.["environmentSettings"] === - undefined - ? p.jobPreparationTask?.["environmentSettings"] - : p.jobPreparationTask?.["environmentSettings"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - constraints: !p.jobPreparationTask?.constraints - ? undefined - : { - maxWallClockTime: - p.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - p.jobPreparationTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - p.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: p.jobPreparationTask?.["waitForSuccess"], - userIdentity: !p.jobPreparationTask?.userIdentity - ? undefined - : { - username: - p.jobPreparationTask?.userIdentity?.["username"], - autoUser: !p.jobPreparationTask?.userIdentity - ?.autoUser - ? undefined - : { - scope: - p.jobPreparationTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - p.jobPreparationTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - rerunOnNodeRebootAfterSuccess: - p.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], - }, - jobReleaseTask: !p.jobReleaseTask - ? undefined - : { - id: p.jobReleaseTask?.["id"], - commandLine: p.jobReleaseTask?.["commandLine"], - containerSettings: !p.jobReleaseTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobReleaseTask?.containerSettings?.["imageName"], - registry: !p.jobReleaseTask?.containerSettings - ?.registry - ? undefined - : { - username: - p.jobReleaseTask?.containerSettings - ?.registry?.["username"], - password: - p.jobReleaseTask?.containerSettings - ?.registry?.["password"], - registryServer: - p.jobReleaseTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !p.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.jobReleaseTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobReleaseTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobReleaseTask?.["resourceFiles"] === undefined - ? p.jobReleaseTask?.["resourceFiles"] - : p.jobReleaseTask?.["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - environmentSettings: - p.jobReleaseTask?.["environmentSettings"] === undefined - ? p.jobReleaseTask?.["environmentSettings"] - : p.jobReleaseTask?.["environmentSettings"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - maxWallClockTime: p.jobReleaseTask?.["maxWallClockTime"], - retentionTime: p.jobReleaseTask?.["retentionTime"], - userIdentity: !p.jobReleaseTask?.userIdentity - ? undefined - : { - username: - p.jobReleaseTask?.userIdentity?.["username"], - autoUser: !p.jobReleaseTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobReleaseTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.jobReleaseTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - }, - commonEnvironmentSettings: - p["commonEnvironmentSettings"] === undefined - ? p["commonEnvironmentSettings"] - : p["commonEnvironmentSettings"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - poolInfo: { - poolId: p.poolInfo["poolId"], - autoPoolSpecification: !p.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - p.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - p.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - p.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !p.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - p.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - p.poolInfo.autoPoolSpecification?.pool?.[ - "vmSize" - ], - cloudServiceConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - p.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - p.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.[ - "osVersion" - ], - }, - virtualMachineConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["sku"], - version: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["exactVersion"], - }, - nodeAgentSkuId: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p: any) => { - return { - lun: p["lun"], - caching: p["caching"], - diskSizeGb: p["diskSizeGB"], - storageAccountType: - p["storageAccountType"], - }; - }), - licenseType: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: p.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? p.poolInfo.autoPoolSpecification - ?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p: any) => { - return { - username: p["username"], - password: p["password"], - registryServer: - p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p - .identityReference?.[ - "resourceId" - ], - }, - }; - }), - }, - diskEncryptionConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p: any) => { - return { - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: - p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: - p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - }; - }), - osDisk: !p.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - p.poolInfo.autoPoolSpecification - ?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - p.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !p.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - p.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - p.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - p.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - p.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - p.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - p.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !p.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNatPools: - p.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ].map((p: any) => { - return { - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p[ - "networkSecurityGroupRules" - ] === undefined - ? p[ - "networkSecurityGroupRules" - ] - : p[ - "networkSecurityGroupRules" - ].map((p: any) => { - return { - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p[ - "sourceAddressPrefix" - ], - sourcePortRanges: - p["sourcePortRanges"], - }; - }), - }; - }), - }, - publicIpAddressConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - ipAddressProvisioningType: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !p.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !p.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !p.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry - ? undefined - : { - username: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry?.["username"], - password: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry?.["password"], - registryServer: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry?.[ - "registryServer" - ], - identityReference: !p.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - p.poolInfo - .autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] === - undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] - : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - }; - }), - environmentSettings: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] === - undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] - : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - userIdentity: !p.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.[ - "username" - ], - autoUser: !p.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: - p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p: any) => { - return { - thumbprint: p["thumbprint"], - thumbprintAlgorithm: - p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }; - }), - applicationPackageReferences: - p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - applicationLicenses: - p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: - p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p: any) => { - return { - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: - !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.[ - "uid" - ], - gid: p.linuxUserConfiguration?.[ - "gid" - ], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" - ], - }, - }; - }), - metadata: - p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - mountConfiguration: - p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p: any) => { - return { - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p - .azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p - .azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p - .azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p - .azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p - .azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p - .azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p - .azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: - !p.nfsMountConfiguration - ? undefined - : { - source: - p.nfsMountConfiguration?.[ - "source" - ], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.[ - "mountOptions" - ], - }, - cifsMountConfiguration: - !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.[ - "username" - ], - source: - p.cifsMountConfiguration?.[ - "source" - ], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.[ - "password" - ], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - }; - }), - targetNodeCommunicationMode: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: p["onAllTasksComplete"], - onTaskFailure: p["onTaskFailure"], - networkConfiguration: !p.networkConfiguration - ? undefined - : { subnetId: p.networkConfiguration?.["subnetId"] }, - metadata: - p["metadata"] === undefined - ? p["metadata"] - : p["metadata"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - executionInfo: !p.executionInfo - ? undefined - : { - startTime: new Date(p.executionInfo?.["startTime"]), - endTime: - p.executionInfo?.["endTime"] !== undefined - ? new Date(p.executionInfo?.["endTime"]) - : undefined, - poolId: p.executionInfo?.["poolId"], - schedulingError: !p.executionInfo?.schedulingError - ? undefined - : { - category: - p.executionInfo?.schedulingError?.["category"], - code: p.executionInfo?.schedulingError?.["code"], - message: - p.executionInfo?.schedulingError?.["message"], - details: - p.executionInfo?.schedulingError?.["details"] === - undefined - ? p.executionInfo?.schedulingError?.["details"] - : p.executionInfo?.schedulingError?.[ - "details" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }, - terminateReason: p.executionInfo?.["terminateReason"], - }, - stats: !p.stats - ? undefined - : { - url: p.stats?.["url"], - startTime: new Date(p.stats?.["startTime"]), - lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), - userCPUTime: p.stats?.["userCPUTime"], - kernelCPUTime: p.stats?.["kernelCPUTime"], - wallClockTime: p.stats?.["wallClockTime"], - readIOps: p.stats?.["readIOps"], - writeIOps: p.stats?.["writeIOps"], - readIOGiB: p.stats?.["readIOGiB"], - writeIOGiB: p.stats?.["writeIOGiB"], - numSucceededTasks: p.stats?.["numSucceededTasks"], - numFailedTasks: p.stats?.["numFailedTasks"], - numTaskRetries: p.stats?.["numTaskRetries"], - waitTime: p.stats?.["waitTime"], - }, - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _batchJobListResultDeserializer(result.body); } /** Lists all of the Jobs in the specified Account. */ @@ -5310,19 +1802,25 @@ export function _listJobsFromScheduleSend( jobScheduleId: string, options: ListJobsFromScheduleOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/jobschedules/{jobScheduleId}/jobs", jobScheduleId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/jobschedules/{jobScheduleId}/jobs", jobScheduleId).get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); } export async function _listJobsFromScheduleDeserialize( @@ -5333,1228 +1831,7 @@ export async function _listJobsFromScheduleDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - id: p["id"], - displayName: p["displayName"], - usesTaskDependencies: p["usesTaskDependencies"], - url: p["url"], - eTag: p["eTag"], - lastModified: - p["lastModified"] !== undefined - ? new Date(p["lastModified"]) - : undefined, - creationTime: - p["creationTime"] !== undefined - ? new Date(p["creationTime"]) - : undefined, - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - priority: p["priority"], - allowTaskPreemption: p["allowTaskPreemption"], - maxParallelTasks: p["maxParallelTasks"], - constraints: !p.constraints - ? undefined - : { - maxWallClockTime: p.constraints?.["maxWallClockTime"], - maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !p.jobManagerTask - ? undefined - : { - id: p.jobManagerTask?.["id"], - displayName: p.jobManagerTask?.["displayName"], - commandLine: p.jobManagerTask?.["commandLine"], - containerSettings: !p.jobManagerTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobManagerTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobManagerTask?.containerSettings?.["imageName"], - registry: !p.jobManagerTask?.containerSettings - ?.registry - ? undefined - : { - username: - p.jobManagerTask?.containerSettings - ?.registry?.["username"], - password: - p.jobManagerTask?.containerSettings - ?.registry?.["password"], - registryServer: - p.jobManagerTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !p.jobManagerTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.jobManagerTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobManagerTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobManagerTask?.["resourceFiles"] === undefined - ? p.jobManagerTask?.["resourceFiles"] - : p.jobManagerTask?.["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - outputFiles: - p.jobManagerTask?.["outputFiles"] === undefined - ? p.jobManagerTask?.["outputFiles"] - : p.jobManagerTask?.["outputFiles"].map((p: any) => { - return { - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.[ - "containerUrl" - ], - identityReference: !p.destination - .container?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: - p.destination.container?.[ - "uploadHeaders" - ] === undefined - ? p.destination.container?.[ - "uploadHeaders" - ] - : p.destination.container?.[ - "uploadHeaders" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - }, - }, - uploadOptions: { - uploadCondition: - p.uploadOptions["uploadCondition"], - }, - }; - }), - environmentSettings: - p.jobManagerTask?.["environmentSettings"] === undefined - ? p.jobManagerTask?.["environmentSettings"] - : p.jobManagerTask?.["environmentSettings"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - constraints: !p.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - p.jobManagerTask?.constraints?.["maxWallClockTime"], - retentionTime: - p.jobManagerTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - p.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: p.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - p.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !p.jobManagerTask?.userIdentity - ? undefined - : { - username: - p.jobManagerTask?.userIdentity?.["username"], - autoUser: !p.jobManagerTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobManagerTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.jobManagerTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - runExclusive: p.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - p.jobManagerTask?.["applicationPackageReferences"] === - undefined - ? p.jobManagerTask?.["applicationPackageReferences"] - : p.jobManagerTask?.[ - "applicationPackageReferences" - ].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - authenticationTokenSettings: !p.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - p.jobManagerTask?.authenticationTokenSettings?.[ - "access" - ], - }, - allowLowPriorityNode: - p.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !p.jobPreparationTask - ? undefined - : { - id: p.jobPreparationTask?.["id"], - commandLine: p.jobPreparationTask?.["commandLine"], - containerSettings: !p.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobPreparationTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobPreparationTask?.containerSettings?.[ - "imageName" - ], - registry: !p.jobPreparationTask?.containerSettings - ?.registry - ? undefined - : { - username: - p.jobPreparationTask?.containerSettings - ?.registry?.["username"], - password: - p.jobPreparationTask?.containerSettings - ?.registry?.["password"], - registryServer: - p.jobPreparationTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !p.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.jobPreparationTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobPreparationTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobPreparationTask?.["resourceFiles"] === undefined - ? p.jobPreparationTask?.["resourceFiles"] - : p.jobPreparationTask?.["resourceFiles"].map( - (p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }, - ), - environmentSettings: - p.jobPreparationTask?.["environmentSettings"] === - undefined - ? p.jobPreparationTask?.["environmentSettings"] - : p.jobPreparationTask?.["environmentSettings"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - constraints: !p.jobPreparationTask?.constraints - ? undefined - : { - maxWallClockTime: - p.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - p.jobPreparationTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - p.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: p.jobPreparationTask?.["waitForSuccess"], - userIdentity: !p.jobPreparationTask?.userIdentity - ? undefined - : { - username: - p.jobPreparationTask?.userIdentity?.["username"], - autoUser: !p.jobPreparationTask?.userIdentity - ?.autoUser - ? undefined - : { - scope: - p.jobPreparationTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - p.jobPreparationTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - rerunOnNodeRebootAfterSuccess: - p.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], - }, - jobReleaseTask: !p.jobReleaseTask - ? undefined - : { - id: p.jobReleaseTask?.["id"], - commandLine: p.jobReleaseTask?.["commandLine"], - containerSettings: !p.jobReleaseTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobReleaseTask?.containerSettings?.["imageName"], - registry: !p.jobReleaseTask?.containerSettings - ?.registry - ? undefined - : { - username: - p.jobReleaseTask?.containerSettings - ?.registry?.["username"], - password: - p.jobReleaseTask?.containerSettings - ?.registry?.["password"], - registryServer: - p.jobReleaseTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !p.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.jobReleaseTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobReleaseTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobReleaseTask?.["resourceFiles"] === undefined - ? p.jobReleaseTask?.["resourceFiles"] - : p.jobReleaseTask?.["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - environmentSettings: - p.jobReleaseTask?.["environmentSettings"] === undefined - ? p.jobReleaseTask?.["environmentSettings"] - : p.jobReleaseTask?.["environmentSettings"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - maxWallClockTime: p.jobReleaseTask?.["maxWallClockTime"], - retentionTime: p.jobReleaseTask?.["retentionTime"], - userIdentity: !p.jobReleaseTask?.userIdentity - ? undefined - : { - username: - p.jobReleaseTask?.userIdentity?.["username"], - autoUser: !p.jobReleaseTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobReleaseTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.jobReleaseTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - }, - commonEnvironmentSettings: - p["commonEnvironmentSettings"] === undefined - ? p["commonEnvironmentSettings"] - : p["commonEnvironmentSettings"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - poolInfo: { - poolId: p.poolInfo["poolId"], - autoPoolSpecification: !p.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - p.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - p.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - p.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !p.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - p.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - p.poolInfo.autoPoolSpecification?.pool?.[ - "vmSize" - ], - cloudServiceConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - p.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - p.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.[ - "osVersion" - ], - }, - virtualMachineConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["sku"], - version: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["exactVersion"], - }, - nodeAgentSkuId: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p: any) => { - return { - lun: p["lun"], - caching: p["caching"], - diskSizeGb: p["diskSizeGB"], - storageAccountType: - p["storageAccountType"], - }; - }), - licenseType: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: p.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? p.poolInfo.autoPoolSpecification - ?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p: any) => { - return { - username: p["username"], - password: p["password"], - registryServer: - p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p - .identityReference?.[ - "resourceId" - ], - }, - }; - }), - }, - diskEncryptionConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p: any) => { - return { - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: - p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: - p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - }; - }), - osDisk: !p.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - p.poolInfo.autoPoolSpecification - ?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - p.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !p.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - p.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - p.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - p.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - p.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - p.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - p.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !p.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNatPools: - p.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ].map((p: any) => { - return { - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p[ - "networkSecurityGroupRules" - ] === undefined - ? p[ - "networkSecurityGroupRules" - ] - : p[ - "networkSecurityGroupRules" - ].map((p: any) => { - return { - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p[ - "sourceAddressPrefix" - ], - sourcePortRanges: - p["sourcePortRanges"], - }; - }), - }; - }), - }, - publicIpAddressConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - ipAddressProvisioningType: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !p.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !p.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !p.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry - ? undefined - : { - username: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry?.["username"], - password: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry?.["password"], - registryServer: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry?.[ - "registryServer" - ], - identityReference: !p.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - p.poolInfo - .autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] === - undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] - : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - }; - }), - environmentSettings: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] === - undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] - : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - userIdentity: !p.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.[ - "username" - ], - autoUser: !p.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: - p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p: any) => { - return { - thumbprint: p["thumbprint"], - thumbprintAlgorithm: - p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }; - }), - applicationPackageReferences: - p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - applicationLicenses: - p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: - p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p: any) => { - return { - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: - !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.[ - "uid" - ], - gid: p.linuxUserConfiguration?.[ - "gid" - ], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" - ], - }, - }; - }), - metadata: - p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - mountConfiguration: - p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p: any) => { - return { - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p - .azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p - .azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p - .azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p - .azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p - .azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p - .azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p - .azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: - !p.nfsMountConfiguration - ? undefined - : { - source: - p.nfsMountConfiguration?.[ - "source" - ], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.[ - "mountOptions" - ], - }, - cifsMountConfiguration: - !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.[ - "username" - ], - source: - p.cifsMountConfiguration?.[ - "source" - ], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.[ - "password" - ], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - }; - }), - targetNodeCommunicationMode: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: p["onAllTasksComplete"], - onTaskFailure: p["onTaskFailure"], - networkConfiguration: !p.networkConfiguration - ? undefined - : { subnetId: p.networkConfiguration?.["subnetId"] }, - metadata: - p["metadata"] === undefined - ? p["metadata"] - : p["metadata"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - executionInfo: !p.executionInfo - ? undefined - : { - startTime: new Date(p.executionInfo?.["startTime"]), - endTime: - p.executionInfo?.["endTime"] !== undefined - ? new Date(p.executionInfo?.["endTime"]) - : undefined, - poolId: p.executionInfo?.["poolId"], - schedulingError: !p.executionInfo?.schedulingError - ? undefined - : { - category: - p.executionInfo?.schedulingError?.["category"], - code: p.executionInfo?.schedulingError?.["code"], - message: - p.executionInfo?.schedulingError?.["message"], - details: - p.executionInfo?.schedulingError?.["details"] === - undefined - ? p.executionInfo?.schedulingError?.["details"] - : p.executionInfo?.schedulingError?.[ - "details" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }, - terminateReason: p.executionInfo?.["terminateReason"], - }, - stats: !p.stats - ? undefined - : { - url: p.stats?.["url"], - startTime: new Date(p.stats?.["startTime"]), - lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), - userCPUTime: p.stats?.["userCPUTime"], - kernelCPUTime: p.stats?.["kernelCPUTime"], - wallClockTime: p.stats?.["wallClockTime"], - readIOps: p.stats?.["readIOps"], - writeIOps: p.stats?.["writeIOps"], - readIOGiB: p.stats?.["readIOGiB"], - writeIOGiB: p.stats?.["writeIOGiB"], - numSucceededTasks: p.stats?.["numSucceededTasks"], - numFailedTasks: p.stats?.["numFailedTasks"], - numTaskRetries: p.stats?.["numTaskRetries"], - waitTime: p.stats?.["waitTime"], - }, - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _batchJobListResultDeserializer(result.body); } /** Lists the Jobs that have been created under the specified Job Schedule. */ @@ -6587,7 +1864,11 @@ export function _listJobPreparationAndReleaseTaskStatusSend( maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, $filter: options?.$filter, - $select: options?.$select, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), }, }); } @@ -6600,160 +1881,9 @@ export async function _listJobPreparationAndReleaseTaskStatusDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - poolId: p["poolId"], - nodeId: p["nodeId"], - nodeUrl: p["nodeUrl"], - jobPreparationTaskExecutionInfo: - !p.jobPreparationTaskExecutionInfo - ? undefined - : { - startTime: new Date( - p.jobPreparationTaskExecutionInfo?.["startTime"], - ), - endTime: - p.jobPreparationTaskExecutionInfo?.["endTime"] !== - undefined - ? new Date( - p.jobPreparationTaskExecutionInfo?.["endTime"], - ) - : undefined, - state: p.jobPreparationTaskExecutionInfo?.["state"], - taskRootDirectory: - p.jobPreparationTaskExecutionInfo?.[ - "taskRootDirectory" - ], - taskRootDirectoryUrl: - p.jobPreparationTaskExecutionInfo?.[ - "taskRootDirectoryUrl" - ], - exitCode: p.jobPreparationTaskExecutionInfo?.["exitCode"], - containerInfo: !p.jobPreparationTaskExecutionInfo - ?.containerInfo - ? undefined - : { - containerId: - p.jobPreparationTaskExecutionInfo - ?.containerInfo?.["containerId"], - state: - p.jobPreparationTaskExecutionInfo - ?.containerInfo?.["state"], - error: - p.jobPreparationTaskExecutionInfo - ?.containerInfo?.["error"], - }, - failureInfo: !p.jobPreparationTaskExecutionInfo - ?.failureInfo - ? undefined - : { - category: - p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "category" - ], - code: p.jobPreparationTaskExecutionInfo - ?.failureInfo?.["code"], - message: - p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "message" - ], - details: - p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "details" - ] === undefined - ? p.jobPreparationTaskExecutionInfo - ?.failureInfo?.["details"] - : p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "details" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - }, - retryCount: - p.jobPreparationTaskExecutionInfo?.["retryCount"], - lastRetryTime: - p.jobPreparationTaskExecutionInfo?.["lastRetryTime"] !== - undefined - ? new Date( - p.jobPreparationTaskExecutionInfo?.[ - "lastRetryTime" - ], - ) - : undefined, - result: p.jobPreparationTaskExecutionInfo?.["result"], - }, - jobReleaseTaskExecutionInfo: !p.jobReleaseTaskExecutionInfo - ? undefined - : { - startTime: new Date( - p.jobReleaseTaskExecutionInfo?.["startTime"], - ), - endTime: - p.jobReleaseTaskExecutionInfo?.["endTime"] !== undefined - ? new Date(p.jobReleaseTaskExecutionInfo?.["endTime"]) - : undefined, - state: p.jobReleaseTaskExecutionInfo?.["state"], - taskRootDirectory: - p.jobReleaseTaskExecutionInfo?.["taskRootDirectory"], - taskRootDirectoryUrl: - p.jobReleaseTaskExecutionInfo?.["taskRootDirectoryUrl"], - exitCode: p.jobReleaseTaskExecutionInfo?.["exitCode"], - containerInfo: !p.jobReleaseTaskExecutionInfo?.containerInfo - ? undefined - : { - containerId: - p.jobReleaseTaskExecutionInfo?.containerInfo?.[ - "containerId" - ], - state: - p.jobReleaseTaskExecutionInfo?.containerInfo?.[ - "state" - ], - error: - p.jobReleaseTaskExecutionInfo?.containerInfo?.[ - "error" - ], - }, - failureInfo: !p.jobReleaseTaskExecutionInfo?.failureInfo - ? undefined - : { - category: - p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "category" - ], - code: p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "code" - ], - message: - p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "message" - ], - details: - p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "details" - ] === undefined - ? p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "details" - ] - : p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "details" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }, - result: p.jobReleaseTaskExecutionInfo?.["result"], - }, - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _batchJobListPreparationAndReleaseTaskStatusResultDeserializer( + result.body, + ); } /** @@ -6804,22 +1934,7 @@ export async function _getJobTaskCountsDeserialize( throw createRestError(result); } - return { - taskCounts: { - active: result.body.taskCounts["active"], - running: result.body.taskCounts["running"], - completed: result.body.taskCounts["completed"], - succeeded: result.body.taskCounts["succeeded"], - failed: result.body.taskCounts["failed"], - }, - taskSlotCounts: { - active: result.body.taskSlotCounts["active"], - running: result.body.taskSlotCounts["running"], - completed: result.body.taskSlotCounts["completed"], - succeeded: result.body.taskSlotCounts["succeeded"], - failed: result.body.taskSlotCounts["failed"], - }, - }; + return taskCountsResultDeserializer(result.body); } /** @@ -6853,13 +1968,7 @@ export function _createCertificateSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - thumbprint: body["thumbprint"], - thumbprintAlgorithm: body["thumbprintAlgorithm"], - data: uint8ArrayToString(body["data"], "base64"), - certificateFormat: body["certificateFormat"], - password: body["password"], - }, + body: batchCertificateSerializer(body), }); } @@ -6888,18 +1997,20 @@ export function _listCertificatesSend( context: Client, options: ListCertificatesOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/certificates") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: options?.$select, - }, - }); + return context.path("/certificates").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + }, + }); } export async function _listCertificatesDeserialize( @@ -6910,51 +2021,7 @@ export async function _listCertificatesDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - url: p["url"], - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - publicData: - typeof p["publicData"] === "string" - ? stringToUint8Array(p["publicData"], "base64") - : p["publicData"], - deleteCertificateError: !p.deleteCertificateError - ? undefined - : { - code: p.deleteCertificateError?.["code"], - message: p.deleteCertificateError?.["message"], - values: - p.deleteCertificateError?.["values"] === undefined - ? p.deleteCertificateError?.["values"] - : p.deleteCertificateError?.["values"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }, - data: - typeof p["data"] === "string" - ? stringToUint8Array(p["data"], "base64") - : p["data"], - certificateFormat: p["certificateFormat"], - password: p["password"], - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _certificateListResultDeserializer(result.body); } /** Lists all of the Certificates that have been added to the specified Account. */ @@ -7102,7 +2169,11 @@ export function _getCertificateSend( queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, - $select: options?.$select, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), }, }); } @@ -7115,43 +2186,7 @@ export async function _getCertificateDeserialize( throw createRestError(result); } - return { - thumbprint: result.body["thumbprint"], - thumbprintAlgorithm: result.body["thumbprintAlgorithm"], - url: result.body["url"], - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - previousState: result.body["previousState"], - previousStateTransitionTime: - result.body["previousStateTransitionTime"] !== undefined - ? new Date(result.body["previousStateTransitionTime"]) - : undefined, - publicData: - typeof result.body["publicData"] === "string" - ? stringToUint8Array(result.body["publicData"], "base64") - : result.body["publicData"], - deleteCertificateError: !result.body.deleteCertificateError - ? undefined - : { - code: result.body.deleteCertificateError?.["code"], - message: result.body.deleteCertificateError?.["message"], - values: - result.body.deleteCertificateError?.["values"] === undefined - ? result.body.deleteCertificateError?.["values"] - : result.body.deleteCertificateError?.["values"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }, - data: - typeof result.body["data"] === "string" - ? stringToUint8Array(result.body["data"], "base64") - : result.body["data"], - certificateFormat: result.body["certificateFormat"], - password: result.body["password"], - }; + return batchCertificateDeserializer(result.body); } /** Gets information about the specified Certificate. */ @@ -7187,10 +2222,18 @@ export function _jobScheduleExistsSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -7238,10 +2281,18 @@ export function _deleteJobScheduleSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -7283,31 +2334,45 @@ export function _getJobScheduleSend( jobScheduleId: string, options: GetJobScheduleOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .get({ - ...operationOptionsToRequestParameters(options), - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/jobschedules/{jobScheduleId}", jobScheduleId).get({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); } export async function _getJobScheduleDeserialize( @@ -7318,1242 +2383,7 @@ export async function _getJobScheduleDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - displayName: result.body["displayName"], - url: result.body["url"], - eTag: result.body["eTag"], - lastModified: - result.body["lastModified"] !== undefined - ? new Date(result.body["lastModified"]) - : undefined, - creationTime: - result.body["creationTime"] !== undefined - ? new Date(result.body["creationTime"]) - : undefined, - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - previousState: result.body["previousState"], - previousStateTransitionTime: - result.body["previousStateTransitionTime"] !== undefined - ? new Date(result.body["previousStateTransitionTime"]) - : undefined, - schedule: { - doNotRunUntil: - result.body.schedule["doNotRunUntil"] !== undefined - ? new Date(result.body.schedule["doNotRunUntil"]) - : undefined, - doNotRunAfter: - result.body.schedule["doNotRunAfter"] !== undefined - ? new Date(result.body.schedule["doNotRunAfter"]) - : undefined, - startWindow: result.body.schedule["startWindow"], - recurrenceInterval: result.body.schedule["recurrenceInterval"], - }, - jobSpecification: { - priority: result.body.jobSpecification["priority"], - allowTaskPreemption: result.body.jobSpecification["allowTaskPreemption"], - maxParallelTasks: result.body.jobSpecification["maxParallelTasks"], - displayName: result.body.jobSpecification["displayName"], - usesTaskDependencies: - result.body.jobSpecification["usesTaskDependencies"], - onAllTasksComplete: result.body.jobSpecification["onAllTasksComplete"], - onTaskFailure: result.body.jobSpecification["onTaskFailure"], - networkConfiguration: !result.body.jobSpecification.networkConfiguration - ? undefined - : { - subnetId: - result.body.jobSpecification.networkConfiguration?.["subnetId"], - }, - constraints: !result.body.jobSpecification.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobSpecification.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - result.body.jobSpecification.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !result.body.jobSpecification.jobManagerTask - ? undefined - : { - id: result.body.jobSpecification.jobManagerTask?.["id"], - displayName: - result.body.jobSpecification.jobManagerTask?.["displayName"], - commandLine: - result.body.jobSpecification.jobManagerTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobManagerTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ? undefined - : { - username: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - result.body.jobSpecification.jobManagerTask?.["resourceFiles"] === - undefined - ? result.body.jobSpecification.jobManagerTask?.["resourceFiles"] - : result.body.jobSpecification.jobManagerTask?.[ - "resourceFiles" - ].map((p: any) => { - return { - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }; - }), - outputFiles: - result.body.jobSpecification.jobManagerTask?.["outputFiles"] === - undefined - ? result.body.jobSpecification.jobManagerTask?.["outputFiles"] - : result.body.jobSpecification.jobManagerTask?.[ - "outputFiles" - ].map((p: any) => { - return { - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.["resourceId"], - }, - uploadHeaders: - p.destination.container?.["uploadHeaders"] === - undefined - ? p.destination.container?.["uploadHeaders"] - : p.destination.container?.[ - "uploadHeaders" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - }; - }), - environmentSettings: - result.body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] === undefined - ? result.body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] - : result.body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - constraints: !result.body.jobSpecification.jobManagerTask - ?.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: - result.body.jobSpecification.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - result.body.jobSpecification.jobManagerTask?.[ - "killJobOnCompletion" - ], - userIdentity: !result.body.jobSpecification.jobManagerTask - ?.userIdentity - ? undefined - : { - username: - result.body.jobSpecification.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - runExclusive: - result.body.jobSpecification.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - result.body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] === undefined - ? result.body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] - : result.body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - authenticationTokenSettings: !result.body.jobSpecification - .jobManagerTask?.authenticationTokenSettings - ? undefined - : { - access: - result.body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: - result.body.jobSpecification.jobManagerTask?.[ - "allowLowPriorityNode" - ], - }, - jobPreparationTask: !result.body.jobSpecification.jobPreparationTask - ? undefined - : { - id: result.body.jobSpecification.jobPreparationTask?.["id"], - commandLine: - result.body.jobSpecification.jobPreparationTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobPreparationTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ? undefined - : { - username: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["username"], - password: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["password"], - registryServer: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobPreparationTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - result.body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] === undefined - ? result.body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] - : result.body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ].map((p: any) => { - return { - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }; - }), - environmentSettings: - result.body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] === undefined - ? result.body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] - : result.body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - constraints: !result.body.jobSpecification.jobPreparationTask - ?.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["maxWallClockTime"], - retentionTime: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["retentionTime"], - maxTaskRetryCount: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["maxTaskRetryCount"], - }, - waitForSuccess: - result.body.jobSpecification.jobPreparationTask?.[ - "waitForSuccess" - ], - userIdentity: !result.body.jobSpecification.jobPreparationTask - ?.userIdentity - ? undefined - : { - username: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - rerunOnNodeRebootAfterSuccess: - result.body.jobSpecification.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], - }, - jobReleaseTask: !result.body.jobSpecification.jobReleaseTask - ? undefined - : { - id: result.body.jobSpecification.jobReleaseTask?.["id"], - commandLine: - result.body.jobSpecification.jobReleaseTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobReleaseTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ? undefined - : { - username: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["username"], - password: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["password"], - registryServer: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobReleaseTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - result.body.jobSpecification.jobReleaseTask?.["resourceFiles"] === - undefined - ? result.body.jobSpecification.jobReleaseTask?.["resourceFiles"] - : result.body.jobSpecification.jobReleaseTask?.[ - "resourceFiles" - ].map((p: any) => { - return { - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }; - }), - environmentSettings: - result.body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] === undefined - ? result.body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] - : result.body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - maxWallClockTime: - result.body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - result.body.jobSpecification.jobReleaseTask?.["retentionTime"], - userIdentity: !result.body.jobSpecification.jobReleaseTask - ?.userIdentity - ? undefined - : { - username: - result.body.jobSpecification.jobReleaseTask?.userIdentity?.[ - "username" - ], - autoUser: !result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - }, - commonEnvironmentSettings: - result.body.jobSpecification["commonEnvironmentSettings"] === undefined - ? result.body.jobSpecification["commonEnvironmentSettings"] - : result.body.jobSpecification["commonEnvironmentSettings"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - poolInfo: { - poolId: result.body.jobSpecification.poolInfo["poolId"], - autoPoolSpecification: !result.body.jobSpecification.poolInfo - .autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !result.body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool - ? undefined - : { - displayName: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["displayName"], - vmSize: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" - ], - sku: result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "exactVersion" - ], - }, - nodeAgentSkuId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] === - undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p: any) => { - return { - lun: p["lun"], - caching: p["caching"], - diskSizeGb: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - }; - }), - licenseType: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p: any) => { - return { - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - }; - }), - }, - diskEncryptionConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] === - undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p: any) => { - return { - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - }; - }), - osDisk: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !result.body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["taskSlotsPerNode"], - taskSchedulingPolicy: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["resizeTimeout"], - targetDedicatedNodes: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["targetDedicatedNodes"], - targetLowPriorityNodes: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["enableAutoScale"], - autoScaleFormula: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["autoScaleFormula"], - autoScaleEvaluationInterval: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNatPools: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ].map((p: any) => { - return { - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === - undefined - ? p["networkSecurityGroupRules"] - : p["networkSecurityGroupRules"].map( - (p: any) => { - return { - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - }; - }, - ), - }; - }), - }, - publicIpAddressConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - ipAddressProvisioningType: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ? undefined - : { - commandLine: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "commandLine" - ], - containerSettings: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !result.body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.jobSpecification - .poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - environmentSettings: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - userIdentity: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.["username"], - autoUser: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], - waitForSuccess: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], - }, - certificateReferences: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p: any) => { - return { - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }; - }), - applicationPackageReferences: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - applicationLicenses: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["applicationLicenses"], - userAccounts: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["userAccounts"] === - undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["userAccounts"] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p: any) => { - return { - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" - ], - }, - }; - }), - metadata: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["metadata"] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["metadata"] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - mountConfiguration: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["mountConfiguration"] === - undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["mountConfiguration"] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p: any) => { - return { - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.["username"], - source: - p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - }; - }), - targetNodeCommunicationMode: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - metadata: - result.body.jobSpecification["metadata"] === undefined - ? result.body.jobSpecification["metadata"] - : result.body.jobSpecification["metadata"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }, - executionInfo: !result.body.executionInfo - ? undefined - : { - nextRunTime: - result.body.executionInfo?.["nextRunTime"] !== undefined - ? new Date(result.body.executionInfo?.["nextRunTime"]) - : undefined, - recentJob: !result.body.executionInfo?.recentJob - ? undefined - : { - id: result.body.executionInfo?.recentJob?.["id"], - url: result.body.executionInfo?.recentJob?.["url"], - }, - endTime: - result.body.executionInfo?.["endTime"] !== undefined - ? new Date(result.body.executionInfo?.["endTime"]) - : undefined, - }, - metadata: - result.body["metadata"] === undefined - ? result.body["metadata"] - : result.body["metadata"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - stats: !result.body.stats - ? undefined - : { - url: result.body.stats?.["url"], - startTime: new Date(result.body.stats?.["startTime"]), - lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), - userCPUTime: result.body.stats?.["userCPUTime"], - kernelCPUTime: result.body.stats?.["kernelCPUTime"], - wallClockTime: result.body.stats?.["wallClockTime"], - readIOps: result.body.stats?.["readIOps"], - writeIOps: result.body.stats?.["writeIOps"], - readIOGiB: result.body.stats?.["readIOGiB"], - writeIOGiB: result.body.stats?.["writeIOGiB"], - numSucceededTasks: result.body.stats?.["numSucceededTasks"], - numFailedTasks: result.body.stats?.["numFailedTasks"], - numTaskRetries: result.body.stats?.["numTaskRetries"], - waitTime: result.body.stats?.["waitTime"], - }, - }; + return batchJobScheduleDeserializer(result.body); } /** Gets information about the specified Job Schedule. */ @@ -8587,28 +2417,25 @@ export function _updateJobScheduleSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - schedule: !body.schedule - ? body.schedule - : scheduleSerializer(body.schedule), - jobSpecification: !body.jobSpecification - ? body.jobSpecification - : jobSpecificationSerializer(body.jobSpecification), - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map(metadataItemSerializer), - }, + body: batchJobScheduleUpdateOptionsSerializer(body), }); } @@ -8666,24 +2493,25 @@ export function _replaceJobScheduleSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - schedule: scheduleSerializer(body.schedule), - jobSpecification: jobSpecificationSerializer(body.jobSpecification), - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map(metadataItemSerializer), - }, + body: batchJobScheduleSerializer(body), }); } @@ -8737,10 +2565,18 @@ export function _disableJobScheduleSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -8788,10 +2624,18 @@ export function _enableJobScheduleSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -8839,10 +2683,18 @@ export function _terminateJobScheduleSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -8893,16 +2745,7 @@ export function _createJobScheduleSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - id: body["id"], - displayName: body["displayName"], - schedule: scheduleSerializer(body.schedule), - jobSpecification: jobSpecificationSerializer(body.jobSpecification), - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map(metadataItemSerializer), - }, + body: batchJobScheduleCreateOptionsSerializer(body), }); } @@ -8931,19 +2774,25 @@ export function _listJobSchedulesSend( context: Client, options: ListJobSchedulesOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/jobschedules") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/jobschedules").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); } export async function _listJobSchedulesDeserialize( @@ -8954,1399 +2803,7 @@ export async function _listJobSchedulesDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - id: p["id"], - displayName: p["displayName"], - url: p["url"], - eTag: p["eTag"], - lastModified: - p["lastModified"] !== undefined - ? new Date(p["lastModified"]) - : undefined, - creationTime: - p["creationTime"] !== undefined - ? new Date(p["creationTime"]) - : undefined, - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - schedule: { - doNotRunUntil: - p.schedule["doNotRunUntil"] !== undefined - ? new Date(p.schedule["doNotRunUntil"]) - : undefined, - doNotRunAfter: - p.schedule["doNotRunAfter"] !== undefined - ? new Date(p.schedule["doNotRunAfter"]) - : undefined, - startWindow: p.schedule["startWindow"], - recurrenceInterval: p.schedule["recurrenceInterval"], - }, - jobSpecification: { - priority: p.jobSpecification["priority"], - allowTaskPreemption: p.jobSpecification["allowTaskPreemption"], - maxParallelTasks: p.jobSpecification["maxParallelTasks"], - displayName: p.jobSpecification["displayName"], - usesTaskDependencies: - p.jobSpecification["usesTaskDependencies"], - onAllTasksComplete: p.jobSpecification["onAllTasksComplete"], - onTaskFailure: p.jobSpecification["onTaskFailure"], - networkConfiguration: !p.jobSpecification.networkConfiguration - ? undefined - : { - subnetId: - p.jobSpecification.networkConfiguration?.["subnetId"], - }, - constraints: !p.jobSpecification.constraints - ? undefined - : { - maxWallClockTime: - p.jobSpecification.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - p.jobSpecification.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !p.jobSpecification.jobManagerTask - ? undefined - : { - id: p.jobSpecification.jobManagerTask?.["id"], - displayName: - p.jobSpecification.jobManagerTask?.["displayName"], - commandLine: - p.jobSpecification.jobManagerTask?.["commandLine"], - containerSettings: !p.jobSpecification.jobManagerTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobSpecification.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - p.jobSpecification.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !p.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ? undefined - : { - username: - p.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.[ - "username" - ], - password: - p.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.jobSpecification - .jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - p.jobSpecification.jobManagerTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - p.jobSpecification.jobManagerTask?.["resourceFiles"] === - undefined - ? p.jobSpecification.jobManagerTask?.["resourceFiles"] - : p.jobSpecification.jobManagerTask?.[ - "resourceFiles" - ].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - outputFiles: - p.jobSpecification.jobManagerTask?.["outputFiles"] === - undefined - ? p.jobSpecification.jobManagerTask?.["outputFiles"] - : p.jobSpecification.jobManagerTask?.[ - "outputFiles" - ].map((p: any) => { - return { - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.[ - "containerUrl" - ], - identityReference: !p.destination - .container?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: - p.destination.container?.[ - "uploadHeaders" - ] === undefined - ? p.destination.container?.[ - "uploadHeaders" - ] - : p.destination.container?.[ - "uploadHeaders" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - }, - }, - uploadOptions: { - uploadCondition: - p.uploadOptions["uploadCondition"], - }, - }; - }), - environmentSettings: - p.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] === undefined - ? p.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] - : p.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - constraints: !p.jobSpecification.jobManagerTask - ?.constraints - ? undefined - : { - maxWallClockTime: - p.jobSpecification.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - p.jobSpecification.jobManagerTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - p.jobSpecification.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: - p.jobSpecification.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - p.jobSpecification.jobManagerTask?.[ - "killJobOnCompletion" - ], - userIdentity: !p.jobSpecification.jobManagerTask - ?.userIdentity - ? undefined - : { - username: - p.jobSpecification.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !p.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - p.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - runExclusive: - p.jobSpecification.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - p.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] === undefined - ? p.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] - : p.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - authenticationTokenSettings: !p.jobSpecification - .jobManagerTask?.authenticationTokenSettings - ? undefined - : { - access: - p.jobSpecification.jobManagerTask - ?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: - p.jobSpecification.jobManagerTask?.[ - "allowLowPriorityNode" - ], - }, - jobPreparationTask: !p.jobSpecification.jobPreparationTask - ? undefined - : { - id: p.jobSpecification.jobPreparationTask?.["id"], - commandLine: - p.jobSpecification.jobPreparationTask?.["commandLine"], - containerSettings: !p.jobSpecification.jobPreparationTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobSpecification.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - p.jobSpecification.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !p.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ? undefined - : { - username: - p.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.[ - "username" - ], - password: - p.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.jobSpecification - .jobPreparationTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - p.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - p.jobSpecification.jobPreparationTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - p.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] === undefined - ? p.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] - : p.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - environmentSettings: - p.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] === undefined - ? p.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] - : p.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - constraints: !p.jobSpecification.jobPreparationTask - ?.constraints - ? undefined - : { - maxWallClockTime: - p.jobSpecification.jobPreparationTask - ?.constraints?.["maxWallClockTime"], - retentionTime: - p.jobSpecification.jobPreparationTask - ?.constraints?.["retentionTime"], - maxTaskRetryCount: - p.jobSpecification.jobPreparationTask - ?.constraints?.["maxTaskRetryCount"], - }, - waitForSuccess: - p.jobSpecification.jobPreparationTask?.[ - "waitForSuccess" - ], - userIdentity: !p.jobSpecification.jobPreparationTask - ?.userIdentity - ? undefined - : { - username: - p.jobSpecification.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !p.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - p.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - rerunOnNodeRebootAfterSuccess: - p.jobSpecification.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], - }, - jobReleaseTask: !p.jobSpecification.jobReleaseTask - ? undefined - : { - id: p.jobSpecification.jobReleaseTask?.["id"], - commandLine: - p.jobSpecification.jobReleaseTask?.["commandLine"], - containerSettings: !p.jobSpecification.jobReleaseTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobSpecification.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - p.jobSpecification.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !p.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ? undefined - : { - username: - p.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.[ - "username" - ], - password: - p.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.jobSpecification - .jobReleaseTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - p.jobSpecification.jobReleaseTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - p.jobSpecification.jobReleaseTask?.["resourceFiles"] === - undefined - ? p.jobSpecification.jobReleaseTask?.["resourceFiles"] - : p.jobSpecification.jobReleaseTask?.[ - "resourceFiles" - ].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - environmentSettings: - p.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] === undefined - ? p.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] - : p.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - maxWallClockTime: - p.jobSpecification.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - p.jobSpecification.jobReleaseTask?.["retentionTime"], - userIdentity: !p.jobSpecification.jobReleaseTask - ?.userIdentity - ? undefined - : { - username: - p.jobSpecification.jobReleaseTask?.userIdentity?.[ - "username" - ], - autoUser: !p.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - p.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - }, - commonEnvironmentSettings: - p.jobSpecification["commonEnvironmentSettings"] === undefined - ? p.jobSpecification["commonEnvironmentSettings"] - : p.jobSpecification["commonEnvironmentSettings"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - poolInfo: { - poolId: p.jobSpecification.poolInfo["poolId"], - autoPoolSpecification: !p.jobSpecification.poolInfo - .autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - p.jobSpecification.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - p.jobSpecification.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - p.jobSpecification.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !p.jobSpecification.poolInfo.autoPoolSpecification - ?.pool - ? undefined - : { - displayName: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["displayName"], - vmSize: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !p.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.[ - "osFamily" - ], - osVersion: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.[ - "osVersion" - ], - }, - virtualMachineConfiguration: !p.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["sku"], - version: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["exactVersion"], - }, - nodeAgentSkuId: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !p.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] === undefined - ? p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] - : p.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p: any) => { - return { - lun: p["lun"], - caching: p["caching"], - diskSizeGb: p["diskSizeGB"], - storageAccountType: - p["storageAccountType"], - }; - }), - licenseType: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !p.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : p.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p: any) => { - return { - username: p["username"], - password: p["password"], - registryServer: - p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p - .identityReference?.[ - "resourceId" - ], - }, - }; - }), - }, - diskEncryptionConfiguration: !p - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !p - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] === undefined - ? p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] - : p.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p: any) => { - return { - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: - p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: - p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - }; - }), - osDisk: !p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !p - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings - ? undefined - : { - placement: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.[ - "nodeFillType" - ], - }, - resizeTimeout: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ? undefined - : { - subnetId: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !p.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNatPools: - p.jobSpecification.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ].map((p: any) => { - return { - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p[ - "networkSecurityGroupRules" - ] === undefined - ? p[ - "networkSecurityGroupRules" - ] - : p[ - "networkSecurityGroupRules" - ].map((p: any) => { - return { - priority: - p["priority"], - access: p["access"], - sourceAddressPrefix: - p[ - "sourceAddressPrefix" - ], - sourcePortRanges: - p[ - "sourcePortRanges" - ], - }; - }), - }; - }), - }, - publicIpAddressConfiguration: !p - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - ipAddressProvisioningType: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ? undefined - : { - commandLine: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !p.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry - ? undefined - : { - username: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask - ?.containerSettings - ?.registry?.["username"], - password: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask - ?.containerSettings - ?.registry?.["password"], - registryServer: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask - ?.containerSettings - ?.registry?.[ - "registryServer" - ], - identityReference: !p - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - p.jobSpecification - .poolInfo - .autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] === - undefined - ? p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] - : p.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - }; - }), - environmentSettings: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] === - undefined - ? p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] - : p.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - userIdentity: !p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity?.[ - "username" - ], - autoUser: !p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : p.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p: any) => { - return { - thumbprint: p["thumbprint"], - thumbprintAlgorithm: - p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }; - }), - applicationPackageReferences: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : p.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - applicationLicenses: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "userAccounts" - ] === undefined - ? p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "userAccounts" - ] - : p.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p: any) => { - return { - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: - !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.[ - "uid" - ], - gid: p.linuxUserConfiguration?.[ - "gid" - ], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" - ], - }, - }; - }), - metadata: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["metadata"] === - undefined - ? p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["metadata"] - : p.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - mountConfiguration: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] === undefined - ? p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] - : p.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p: any) => { - return { - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p - .azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p - .azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p - .azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p - .azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p - .azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p - .azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p - .azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: - !p.nfsMountConfiguration - ? undefined - : { - source: - p.nfsMountConfiguration?.[ - "source" - ], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.[ - "mountOptions" - ], - }, - cifsMountConfiguration: - !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.[ - "username" - ], - source: - p.cifsMountConfiguration?.[ - "source" - ], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.[ - "password" - ], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p - .azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p - .azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p - .azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p - .azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p - .azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - }; - }), - targetNodeCommunicationMode: - p.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - metadata: - p.jobSpecification["metadata"] === undefined - ? p.jobSpecification["metadata"] - : p.jobSpecification["metadata"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }, - executionInfo: !p.executionInfo - ? undefined - : { - nextRunTime: - p.executionInfo?.["nextRunTime"] !== undefined - ? new Date(p.executionInfo?.["nextRunTime"]) - : undefined, - recentJob: !p.executionInfo?.recentJob - ? undefined - : { - id: p.executionInfo?.recentJob?.["id"], - url: p.executionInfo?.recentJob?.["url"], - }, - endTime: - p.executionInfo?.["endTime"] !== undefined - ? new Date(p.executionInfo?.["endTime"]) - : undefined, - }, - metadata: - p["metadata"] === undefined - ? p["metadata"] - : p["metadata"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - stats: !p.stats - ? undefined - : { - url: p.stats?.["url"], - startTime: new Date(p.stats?.["startTime"]), - lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), - userCPUTime: p.stats?.["userCPUTime"], - kernelCPUTime: p.stats?.["kernelCPUTime"], - wallClockTime: p.stats?.["wallClockTime"], - readIOps: p.stats?.["readIOps"], - writeIOps: p.stats?.["writeIOps"], - readIOGiB: p.stats?.["readIOGiB"], - writeIOGiB: p.stats?.["writeIOGiB"], - numSucceededTasks: p.stats?.["numSucceededTasks"], - numFailedTasks: p.stats?.["numFailedTasks"], - numTaskRetries: p.stats?.["numTaskRetries"], - waitTime: p.stats?.["waitTime"], - }, - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _batchJobScheduleListResultDeserializer(result.body); } /** Lists all of the Job Schedules in the specified Account. */ @@ -10380,56 +2837,7 @@ export function _createTaskSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - id: body["id"], - displayName: body["displayName"], - exitConditions: !body.exitConditions - ? body.exitConditions - : exitConditionsSerializer(body.exitConditions), - commandLine: body["commandLine"], - containerSettings: !body.containerSettings - ? body.containerSettings - : taskContainerSettingsSerializer(body.containerSettings), - resourceFiles: - body["resourceFiles"] === undefined - ? body["resourceFiles"] - : body["resourceFiles"].map(resourceFileSerializer), - outputFiles: - body["outputFiles"] === undefined - ? body["outputFiles"] - : body["outputFiles"].map(outputFileSerializer), - environmentSettings: - body["environmentSettings"] === undefined - ? body["environmentSettings"] - : body["environmentSettings"].map(environmentSettingSerializer), - affinityInfo: !body.affinityInfo - ? body.affinityInfo - : affinityInformationSerializer(body.affinityInfo), - constraints: !body.constraints - ? body.constraints - : taskConstraintsSerializer(body.constraints), - requiredSlots: body["requiredSlots"], - userIdentity: !body.userIdentity - ? body.userIdentity - : userIdentitySerializer(body.userIdentity), - multiInstanceSettings: !body.multiInstanceSettings - ? body.multiInstanceSettings - : multiInstanceSettingsSerializer(body.multiInstanceSettings), - dependsOn: !body.dependsOn - ? body.dependsOn - : taskDependenciesSerializer(body.dependsOn), - applicationPackageReferences: - body["applicationPackageReferences"] === undefined - ? body["applicationPackageReferences"] - : body["applicationPackageReferences"].map( - applicationPackageReferenceSerializer, - ), - authenticationTokenSettings: !body.authenticationTokenSettings - ? body.authenticationTokenSettings - : authenticationTokenSettingsSerializer( - body.authenticationTokenSettings, - ), - }, + body: batchTaskCreateOptionsSerializer(body), }); } @@ -10464,19 +2872,25 @@ export function _listTasksSend( jobId: string, options: ListTasksOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/jobs/{jobId}/tasks", jobId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/jobs/{jobId}/tasks", jobId).get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); } export async function _listTasksDeserialize( @@ -10487,336 +2901,7 @@ export async function _listTasksDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - id: p["id"], - displayName: p["displayName"], - url: p["url"], - eTag: p["eTag"], - lastModified: - p["lastModified"] !== undefined - ? new Date(p["lastModified"]) - : undefined, - creationTime: - p["creationTime"] !== undefined - ? new Date(p["creationTime"]) - : undefined, - exitConditions: !p.exitConditions - ? undefined - : { - exitCodes: - p.exitConditions?.["exitCodes"] === undefined - ? p.exitConditions?.["exitCodes"] - : p.exitConditions?.["exitCodes"].map((p: any) => { - return { - code: p["code"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: - p.exitOptions["dependencyAction"], - }, - }; - }), - exitCodeRanges: - p.exitConditions?.["exitCodeRanges"] === undefined - ? p.exitConditions?.["exitCodeRanges"] - : p.exitConditions?.["exitCodeRanges"].map((p: any) => { - return { - start: p["start"], - end: p["end"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: - p.exitOptions["dependencyAction"], - }, - }; - }), - preProcessingError: !p.exitConditions?.preProcessingError - ? undefined - : { - jobAction: - p.exitConditions?.preProcessingError?.["jobAction"], - dependencyAction: - p.exitConditions?.preProcessingError?.[ - "dependencyAction" - ], - }, - fileUploadError: !p.exitConditions?.fileUploadError - ? undefined - : { - jobAction: - p.exitConditions?.fileUploadError?.["jobAction"], - dependencyAction: - p.exitConditions?.fileUploadError?.[ - "dependencyAction" - ], - }, - default: !p.exitConditions?.default - ? undefined - : { - jobAction: p.exitConditions?.default?.["jobAction"], - dependencyAction: - p.exitConditions?.default?.["dependencyAction"], - }, - }, - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - commandLine: p["commandLine"], - containerSettings: !p.containerSettings - ? undefined - : { - containerRunOptions: - p.containerSettings?.["containerRunOptions"], - imageName: p.containerSettings?.["imageName"], - registry: !p.containerSettings?.registry - ? undefined - : { - username: p.containerSettings?.registry?.["username"], - password: p.containerSettings?.registry?.["password"], - registryServer: - p.containerSettings?.registry?.["registryServer"], - identityReference: !p.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: p.containerSettings?.["workingDirectory"], - }, - resourceFiles: - p["resourceFiles"] === undefined - ? p["resourceFiles"] - : p["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }; - }), - outputFiles: - p["outputFiles"] === undefined - ? p["outputFiles"] - : p["outputFiles"].map((p: any) => { - return { - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.["resourceId"], - }, - uploadHeaders: - p.destination.container?.["uploadHeaders"] === - undefined - ? p.destination.container?.["uploadHeaders"] - : p.destination.container?.[ - "uploadHeaders" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - }; - }), - environmentSettings: - p["environmentSettings"] === undefined - ? p["environmentSettings"] - : p["environmentSettings"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - affinityInfo: !p.affinityInfo - ? undefined - : { affinityId: p.affinityInfo?.["affinityId"] }, - constraints: !p.constraints - ? undefined - : { - maxWallClockTime: p.constraints?.["maxWallClockTime"], - retentionTime: p.constraints?.["retentionTime"], - maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: p["requiredSlots"], - userIdentity: !p.userIdentity - ? undefined - : { - username: p.userIdentity?.["username"], - autoUser: !p.userIdentity?.autoUser - ? undefined - : { - scope: p.userIdentity?.autoUser?.["scope"], - elevationLevel: - p.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - executionInfo: !p.executionInfo - ? undefined - : { - startTime: - p.executionInfo?.["startTime"] !== undefined - ? new Date(p.executionInfo?.["startTime"]) - : undefined, - endTime: - p.executionInfo?.["endTime"] !== undefined - ? new Date(p.executionInfo?.["endTime"]) - : undefined, - exitCode: p.executionInfo?.["exitCode"], - containerInfo: !p.executionInfo?.containerInfo - ? undefined - : { - containerId: - p.executionInfo?.containerInfo?.["containerId"], - state: p.executionInfo?.containerInfo?.["state"], - error: p.executionInfo?.containerInfo?.["error"], - }, - failureInfo: !p.executionInfo?.failureInfo - ? undefined - : { - category: p.executionInfo?.failureInfo?.["category"], - code: p.executionInfo?.failureInfo?.["code"], - message: p.executionInfo?.failureInfo?.["message"], - details: - p.executionInfo?.failureInfo?.["details"] === - undefined - ? p.executionInfo?.failureInfo?.["details"] - : p.executionInfo?.failureInfo?.["details"].map( - (p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }, - ), - }, - retryCount: p.executionInfo?.["retryCount"], - lastRetryTime: - p.executionInfo?.["lastRetryTime"] !== undefined - ? new Date(p.executionInfo?.["lastRetryTime"]) - : undefined, - requeueCount: p.executionInfo?.["requeueCount"], - lastRequeueTime: - p.executionInfo?.["lastRequeueTime"] !== undefined - ? new Date(p.executionInfo?.["lastRequeueTime"]) - : undefined, - result: p.executionInfo?.["result"], - }, - nodeInfo: !p.nodeInfo - ? undefined - : { - affinityId: p.nodeInfo?.["affinityId"], - nodeUrl: p.nodeInfo?.["nodeUrl"], - poolId: p.nodeInfo?.["poolId"], - nodeId: p.nodeInfo?.["nodeId"], - taskRootDirectory: p.nodeInfo?.["taskRootDirectory"], - taskRootDirectoryUrl: p.nodeInfo?.["taskRootDirectoryUrl"], - }, - multiInstanceSettings: !p.multiInstanceSettings - ? undefined - : { - numberOfInstances: - p.multiInstanceSettings?.["numberOfInstances"], - coordinationCommandLine: - p.multiInstanceSettings?.["coordinationCommandLine"], - commonResourceFiles: - p.multiInstanceSettings?.["commonResourceFiles"] === - undefined - ? p.multiInstanceSettings?.["commonResourceFiles"] - : p.multiInstanceSettings?.["commonResourceFiles"].map( - (p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }, - ), - }, - stats: !p.stats - ? undefined - : { - url: p.stats?.["url"], - startTime: new Date(p.stats?.["startTime"]), - lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), - userCPUTime: p.stats?.["userCPUTime"], - kernelCPUTime: p.stats?.["kernelCPUTime"], - wallClockTime: p.stats?.["wallClockTime"], - readIOps: p.stats?.["readIOps"], - writeIOps: p.stats?.["writeIOps"], - readIOGiB: p.stats?.["readIOGiB"], - writeIOGiB: p.stats?.["writeIOGiB"], - waitTime: p.stats?.["waitTime"], - }, - dependsOn: !p.dependsOn - ? undefined - : { - taskIds: p.dependsOn?.["taskIds"], - taskIdRanges: - p.dependsOn?.["taskIdRanges"] === undefined - ? p.dependsOn?.["taskIdRanges"] - : p.dependsOn?.["taskIdRanges"].map((p: any) => { - return { start: p["start"], end: p["end"] }; - }), - }, - applicationPackageReferences: - p["applicationPackageReferences"] === undefined - ? p["applicationPackageReferences"] - : p["applicationPackageReferences"].map((p: any) => { - return { - applicationId: p["applicationId"], - version: p["version"], - }; - }), - authenticationTokenSettings: !p.authenticationTokenSettings - ? undefined - : { access: p.authenticationTokenSettings?.["access"] }, - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _batchTaskListResultDeserializer(result.body); } /** @@ -10855,9 +2940,7 @@ export function _createTaskCollectionSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - value: collection["value"].map(batchTaskCreateOptionsSerializer), - }, + body: batchTaskCollectionSerializer(collection), }); } @@ -10869,40 +2952,7 @@ export async function _createTaskCollectionDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - status: p["status"], - taskId: p["taskId"], - eTag: p["eTag"], - lastModified: - p["lastModified"] !== undefined - ? new Date(p["lastModified"]) - : undefined, - location: p["location"], - error: !p.error - ? undefined - : { - code: p.error?.["code"], - message: !p.error?.message - ? undefined - : { - lang: p.error?.message?.["lang"], - value: p.error?.message?.["value"], - }, - values: - p.error?.["values"] === undefined - ? p.error?.["values"] - : p.error?.["values"].map((p: any) => { - return { key: p["key"], value: p["value"] }; - }), - }, - }; - }), - }; + return taskAddCollectionResultDeserializer(result.body); } /** @@ -10954,10 +3004,18 @@ export function _deleteTaskSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -11001,31 +3059,45 @@ export function _getTaskSend( taskId: string, options: GetTaskOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId) - .get({ - ...operationOptionsToRequestParameters(options), - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId).get({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); } export async function _getTaskDeserialize( @@ -11036,312 +3108,7 @@ export async function _getTaskDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - displayName: result.body["displayName"], - url: result.body["url"], - eTag: result.body["eTag"], - lastModified: - result.body["lastModified"] !== undefined - ? new Date(result.body["lastModified"]) - : undefined, - creationTime: - result.body["creationTime"] !== undefined - ? new Date(result.body["creationTime"]) - : undefined, - exitConditions: !result.body.exitConditions - ? undefined - : { - exitCodes: - result.body.exitConditions?.["exitCodes"] === undefined - ? result.body.exitConditions?.["exitCodes"] - : result.body.exitConditions?.["exitCodes"].map((p: any) => { - return { - code: p["code"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: p.exitOptions["dependencyAction"], - }, - }; - }), - exitCodeRanges: - result.body.exitConditions?.["exitCodeRanges"] === undefined - ? result.body.exitConditions?.["exitCodeRanges"] - : result.body.exitConditions?.["exitCodeRanges"].map((p: any) => { - return { - start: p["start"], - end: p["end"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: p.exitOptions["dependencyAction"], - }, - }; - }), - preProcessingError: !result.body.exitConditions?.preProcessingError - ? undefined - : { - jobAction: - result.body.exitConditions?.preProcessingError?.["jobAction"], - dependencyAction: - result.body.exitConditions?.preProcessingError?.[ - "dependencyAction" - ], - }, - fileUploadError: !result.body.exitConditions?.fileUploadError - ? undefined - : { - jobAction: - result.body.exitConditions?.fileUploadError?.["jobAction"], - dependencyAction: - result.body.exitConditions?.fileUploadError?.[ - "dependencyAction" - ], - }, - default: !result.body.exitConditions?.default - ? undefined - : { - jobAction: result.body.exitConditions?.default?.["jobAction"], - dependencyAction: - result.body.exitConditions?.default?.["dependencyAction"], - }, - }, - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - previousState: result.body["previousState"], - previousStateTransitionTime: - result.body["previousStateTransitionTime"] !== undefined - ? new Date(result.body["previousStateTransitionTime"]) - : undefined, - commandLine: result.body["commandLine"], - containerSettings: !result.body.containerSettings - ? undefined - : { - containerRunOptions: - result.body.containerSettings?.["containerRunOptions"], - imageName: result.body.containerSettings?.["imageName"], - registry: !result.body.containerSettings?.registry - ? undefined - : { - username: result.body.containerSettings?.registry?.["username"], - password: result.body.containerSettings?.registry?.["password"], - registryServer: - result.body.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: result.body.containerSettings?.["workingDirectory"], - }, - resourceFiles: - result.body["resourceFiles"] === undefined - ? result.body["resourceFiles"] - : result.body["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }; - }), - outputFiles: - result.body["outputFiles"] === undefined - ? result.body["outputFiles"] - : result.body["outputFiles"].map((p: any) => { - return { - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: - p.destination.container?.["uploadHeaders"] === undefined - ? p.destination.container?.["uploadHeaders"] - : p.destination.container?.["uploadHeaders"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - }; - }), - environmentSettings: - result.body["environmentSettings"] === undefined - ? result.body["environmentSettings"] - : result.body["environmentSettings"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - affinityInfo: !result.body.affinityInfo - ? undefined - : { affinityId: result.body.affinityInfo?.["affinityId"] }, - constraints: !result.body.constraints - ? undefined - : { - maxWallClockTime: result.body.constraints?.["maxWallClockTime"], - retentionTime: result.body.constraints?.["retentionTime"], - maxTaskRetryCount: result.body.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: result.body["requiredSlots"], - userIdentity: !result.body.userIdentity - ? undefined - : { - username: result.body.userIdentity?.["username"], - autoUser: !result.body.userIdentity?.autoUser - ? undefined - : { - scope: result.body.userIdentity?.autoUser?.["scope"], - elevationLevel: - result.body.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - executionInfo: !result.body.executionInfo - ? undefined - : { - startTime: - result.body.executionInfo?.["startTime"] !== undefined - ? new Date(result.body.executionInfo?.["startTime"]) - : undefined, - endTime: - result.body.executionInfo?.["endTime"] !== undefined - ? new Date(result.body.executionInfo?.["endTime"]) - : undefined, - exitCode: result.body.executionInfo?.["exitCode"], - containerInfo: !result.body.executionInfo?.containerInfo - ? undefined - : { - containerId: - result.body.executionInfo?.containerInfo?.["containerId"], - state: result.body.executionInfo?.containerInfo?.["state"], - error: result.body.executionInfo?.containerInfo?.["error"], - }, - failureInfo: !result.body.executionInfo?.failureInfo - ? undefined - : { - category: result.body.executionInfo?.failureInfo?.["category"], - code: result.body.executionInfo?.failureInfo?.["code"], - message: result.body.executionInfo?.failureInfo?.["message"], - details: - result.body.executionInfo?.failureInfo?.["details"] === - undefined - ? result.body.executionInfo?.failureInfo?.["details"] - : result.body.executionInfo?.failureInfo?.["details"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - }, - retryCount: result.body.executionInfo?.["retryCount"], - lastRetryTime: - result.body.executionInfo?.["lastRetryTime"] !== undefined - ? new Date(result.body.executionInfo?.["lastRetryTime"]) - : undefined, - requeueCount: result.body.executionInfo?.["requeueCount"], - lastRequeueTime: - result.body.executionInfo?.["lastRequeueTime"] !== undefined - ? new Date(result.body.executionInfo?.["lastRequeueTime"]) - : undefined, - result: result.body.executionInfo?.["result"], - }, - nodeInfo: !result.body.nodeInfo - ? undefined - : { - affinityId: result.body.nodeInfo?.["affinityId"], - nodeUrl: result.body.nodeInfo?.["nodeUrl"], - poolId: result.body.nodeInfo?.["poolId"], - nodeId: result.body.nodeInfo?.["nodeId"], - taskRootDirectory: result.body.nodeInfo?.["taskRootDirectory"], - taskRootDirectoryUrl: result.body.nodeInfo?.["taskRootDirectoryUrl"], - }, - multiInstanceSettings: !result.body.multiInstanceSettings - ? undefined - : { - numberOfInstances: - result.body.multiInstanceSettings?.["numberOfInstances"], - coordinationCommandLine: - result.body.multiInstanceSettings?.["coordinationCommandLine"], - commonResourceFiles: - result.body.multiInstanceSettings?.["commonResourceFiles"] === - undefined - ? result.body.multiInstanceSettings?.["commonResourceFiles"] - : result.body.multiInstanceSettings?.["commonResourceFiles"].map( - (p: any) => { - return { - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }; - }, - ), - }, - stats: !result.body.stats - ? undefined - : { - url: result.body.stats?.["url"], - startTime: new Date(result.body.stats?.["startTime"]), - lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), - userCPUTime: result.body.stats?.["userCPUTime"], - kernelCPUTime: result.body.stats?.["kernelCPUTime"], - wallClockTime: result.body.stats?.["wallClockTime"], - readIOps: result.body.stats?.["readIOps"], - writeIOps: result.body.stats?.["writeIOps"], - readIOGiB: result.body.stats?.["readIOGiB"], - writeIOGiB: result.body.stats?.["writeIOGiB"], - waitTime: result.body.stats?.["waitTime"], - }, - dependsOn: !result.body.dependsOn - ? undefined - : { - taskIds: result.body.dependsOn?.["taskIds"], - taskIdRanges: - result.body.dependsOn?.["taskIdRanges"] === undefined - ? result.body.dependsOn?.["taskIdRanges"] - : result.body.dependsOn?.["taskIdRanges"].map((p: any) => { - return { start: p["start"], end: p["end"] }; - }), - }, - applicationPackageReferences: - result.body["applicationPackageReferences"] === undefined - ? result.body["applicationPackageReferences"] - : result.body["applicationPackageReferences"].map((p: any) => { - return { applicationId: p["applicationId"], version: p["version"] }; - }), - authenticationTokenSettings: !result.body.authenticationTokenSettings - ? undefined - : { access: result.body.authenticationTokenSettings?.["access"] }, - }; + return batchTaskDeserializer(result.body); } /** @@ -11381,21 +3148,25 @@ export function _replaceTaskSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - constraints: !body.constraints - ? body.constraints - : taskConstraintsSerializer(body.constraints), - }, + body: batchTaskSerializer(body), }); } @@ -11435,7 +3206,11 @@ export function _listSubTasksSend( queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, - $select: options?.$select, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), }, }); } @@ -11448,64 +3223,7 @@ export async function _listSubTasksDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - id: p["id"], - nodeInfo: !p.nodeInfo - ? undefined - : { - affinityId: p.nodeInfo?.["affinityId"], - nodeUrl: p.nodeInfo?.["nodeUrl"], - poolId: p.nodeInfo?.["poolId"], - nodeId: p.nodeInfo?.["nodeId"], - taskRootDirectory: p.nodeInfo?.["taskRootDirectory"], - taskRootDirectoryUrl: p.nodeInfo?.["taskRootDirectoryUrl"], - }, - startTime: - p["startTime"] !== undefined - ? new Date(p["startTime"]) - : undefined, - endTime: - p["endTime"] !== undefined ? new Date(p["endTime"]) : undefined, - exitCode: p["exitCode"], - containerInfo: !p.containerInfo - ? undefined - : { - containerId: p.containerInfo?.["containerId"], - state: p.containerInfo?.["state"], - error: p.containerInfo?.["error"], - }, - failureInfo: !p.failureInfo - ? undefined - : { - category: p.failureInfo?.["category"], - code: p.failureInfo?.["code"], - message: p.failureInfo?.["message"], - details: - p.failureInfo?.["details"] === undefined - ? p.failureInfo?.["details"] - : p.failureInfo?.["details"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }, - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - result: p["result"], - }; - }), - }; + return batchTaskListSubtasksResultDeserializer(result.body); } /** If the Task is not a multi-instance Task then this returns an empty collection. */ @@ -11537,10 +3255,18 @@ export function _terminateTaskSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -11594,10 +3320,18 @@ export function _reactivateTaskSend( ? { "if-none-match": options?.ifNoneMatch } : {}), ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -11708,10 +3442,18 @@ export function _getTaskFileSend( ...operationOptionsToRequestParameters(options), headers: { ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), ...(options?.ocpRange !== undefined ? { "ocp-range": options?.ocpRange } @@ -11732,7 +3474,7 @@ export async function _getTaskFileDeserialize( throw createRestError(result); } - return result.body as any; + return result.body; } /** Returns the content of the specified Task file. */ @@ -11771,10 +3513,18 @@ export function _getTaskFilePropertiesSend( ...operationOptionsToRequestParameters(options), headers: { ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -11841,31 +3591,7 @@ export async function _listTaskFilesDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - name: p["name"], - url: p["url"], - isDirectory: p["isDirectory"], - properties: !p.properties - ? undefined - : { - creationTime: - p.properties?.["creationTime"] !== undefined - ? new Date(p.properties?.["creationTime"]) - : undefined, - lastModified: new Date(p.properties?.["lastModified"]), - contentLength: p.properties?.["contentLength"], - contentType: p.properties?.["contentType"], - fileMode: p.properties?.["fileMode"], - }, - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _nodeFileListResultDeserializer(result.body); } /** Lists the files in a Task's directory on its Compute Node. */ @@ -11902,13 +3628,7 @@ export function _createNodeUserSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - name: body["name"], - isAdmin: body["isAdmin"], - expiryTime: body["expiryTime"]?.toISOString(), - password: body["password"], - sshPublicKey: body["sshPublicKey"], - }, + body: batchNodeUserCreateOptionsSerializer(body), }); } @@ -12023,11 +3743,7 @@ export function _replaceNodeUserSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - password: body["password"], - expiryTime: body["expiryTime"]?.toISOString(), - sshPublicKey: body["sshPublicKey"], - }, + body: batchNodeUserUpdateOptionsSerializer(body), }); } @@ -12073,16 +3789,18 @@ export function _getNodeSend( nodeId: string, options: GetNodeOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/pools/{poolId}/nodes/{nodeId}", poolId, nodeId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: options?.$select, - }, - }); + return context.path("/pools/{poolId}/nodes/{nodeId}", poolId, nodeId).get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + }, + }); } export async function _getNodeDeserialize( @@ -12093,294 +3811,7 @@ export async function _getNodeDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - url: result.body["url"], - state: result.body["state"], - schedulingState: result.body["schedulingState"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - lastBootTime: - result.body["lastBootTime"] !== undefined - ? new Date(result.body["lastBootTime"]) - : undefined, - allocationTime: - result.body["allocationTime"] !== undefined - ? new Date(result.body["allocationTime"]) - : undefined, - ipAddress: result.body["ipAddress"], - affinityId: result.body["affinityId"], - vmSize: result.body["vmSize"], - totalTasksRun: result.body["totalTasksRun"], - runningTasksCount: result.body["runningTasksCount"], - runningTaskSlotsCount: result.body["runningTaskSlotsCount"], - totalTasksSucceeded: result.body["totalTasksSucceeded"], - recentTasks: - result.body["recentTasks"] === undefined - ? result.body["recentTasks"] - : result.body["recentTasks"].map((p: any) => { - return { - taskUrl: p["taskUrl"], - jobId: p["jobId"], - taskId: p["taskId"], - subtaskId: p["subtaskId"], - taskState: p["taskState"], - executionInfo: !p.executionInfo - ? undefined - : { - startTime: - p.executionInfo?.["startTime"] !== undefined - ? new Date(p.executionInfo?.["startTime"]) - : undefined, - endTime: - p.executionInfo?.["endTime"] !== undefined - ? new Date(p.executionInfo?.["endTime"]) - : undefined, - exitCode: p.executionInfo?.["exitCode"], - containerInfo: !p.executionInfo?.containerInfo - ? undefined - : { - containerId: - p.executionInfo?.containerInfo?.["containerId"], - state: p.executionInfo?.containerInfo?.["state"], - error: p.executionInfo?.containerInfo?.["error"], - }, - failureInfo: !p.executionInfo?.failureInfo - ? undefined - : { - category: p.executionInfo?.failureInfo?.["category"], - code: p.executionInfo?.failureInfo?.["code"], - message: p.executionInfo?.failureInfo?.["message"], - details: - p.executionInfo?.failureInfo?.["details"] === - undefined - ? p.executionInfo?.failureInfo?.["details"] - : p.executionInfo?.failureInfo?.["details"].map( - (p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }, - ), - }, - retryCount: p.executionInfo?.["retryCount"], - lastRetryTime: - p.executionInfo?.["lastRetryTime"] !== undefined - ? new Date(p.executionInfo?.["lastRetryTime"]) - : undefined, - requeueCount: p.executionInfo?.["requeueCount"], - lastRequeueTime: - p.executionInfo?.["lastRequeueTime"] !== undefined - ? new Date(p.executionInfo?.["lastRequeueTime"]) - : undefined, - result: p.executionInfo?.["result"], - }, - }; - }), - startTask: !result.body.startTask - ? undefined - : { - commandLine: result.body.startTask?.["commandLine"], - containerSettings: !result.body.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.startTask?.containerSettings?.["imageName"], - registry: !result.body.startTask?.containerSettings?.registry - ? undefined - : { - username: - result.body.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - result.body.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - result.body.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !result.body.startTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - result.body.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - result.body.startTask?.["resourceFiles"] === undefined - ? result.body.startTask?.["resourceFiles"] - : result.body.startTask?.["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }; - }), - environmentSettings: - result.body.startTask?.["environmentSettings"] === undefined - ? result.body.startTask?.["environmentSettings"] - : result.body.startTask?.["environmentSettings"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - userIdentity: !result.body.startTask?.userIdentity - ? undefined - : { - username: result.body.startTask?.userIdentity?.["username"], - autoUser: !result.body.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.startTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - result.body.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: result.body.startTask?.["maxTaskRetryCount"], - waitForSuccess: result.body.startTask?.["waitForSuccess"], - }, - startTaskInfo: !result.body.startTaskInfo - ? undefined - : { - state: result.body.startTaskInfo?.["state"], - startTime: new Date(result.body.startTaskInfo?.["startTime"]), - endTime: - result.body.startTaskInfo?.["endTime"] !== undefined - ? new Date(result.body.startTaskInfo?.["endTime"]) - : undefined, - exitCode: result.body.startTaskInfo?.["exitCode"], - containerInfo: !result.body.startTaskInfo?.containerInfo - ? undefined - : { - containerId: - result.body.startTaskInfo?.containerInfo?.["containerId"], - state: result.body.startTaskInfo?.containerInfo?.["state"], - error: result.body.startTaskInfo?.containerInfo?.["error"], - }, - failureInfo: !result.body.startTaskInfo?.failureInfo - ? undefined - : { - category: result.body.startTaskInfo?.failureInfo?.["category"], - code: result.body.startTaskInfo?.failureInfo?.["code"], - message: result.body.startTaskInfo?.failureInfo?.["message"], - details: - result.body.startTaskInfo?.failureInfo?.["details"] === - undefined - ? result.body.startTaskInfo?.failureInfo?.["details"] - : result.body.startTaskInfo?.failureInfo?.["details"].map( - (p: any) => { - return { name: p["name"], value: p["value"] }; - }, - ), - }, - retryCount: result.body.startTaskInfo?.["retryCount"], - lastRetryTime: - result.body.startTaskInfo?.["lastRetryTime"] !== undefined - ? new Date(result.body.startTaskInfo?.["lastRetryTime"]) - : undefined, - result: result.body.startTaskInfo?.["result"], - }, - certificateReferences: - result.body["certificateReferences"] === undefined - ? result.body["certificateReferences"] - : result.body["certificateReferences"].map((p: any) => { - return { - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }; - }), - errors: - result.body["errors"] === undefined - ? result.body["errors"] - : result.body["errors"].map((p: any) => { - return { - code: p["code"], - message: p["message"], - errorDetails: - p["errorDetails"] === undefined - ? p["errorDetails"] - : p["errorDetails"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }; - }), - isDedicated: result.body["isDedicated"], - endpointConfiguration: !result.body.endpointConfiguration - ? undefined - : { - inboundEndpoints: result.body.endpointConfiguration?.[ - "inboundEndpoints" - ].map((p: any) => { - return { - name: p["name"], - protocol: p["protocol"], - publicIpAddress: p["publicIPAddress"], - publicFQDN: p["publicFQDN"], - frontendPort: p["frontendPort"], - backendPort: p["backendPort"], - }; - }), - }, - nodeAgentInfo: !result.body.nodeAgentInfo - ? undefined - : { - version: result.body.nodeAgentInfo?.["version"], - lastUpdateTime: new Date( - result.body.nodeAgentInfo?.["lastUpdateTime"], - ), - }, - virtualMachineInfo: !result.body.virtualMachineInfo - ? undefined - : { - imageReference: !result.body.virtualMachineInfo?.imageReference - ? undefined - : { - publisher: - result.body.virtualMachineInfo?.imageReference?.["publisher"], - offer: - result.body.virtualMachineInfo?.imageReference?.["offer"], - sku: result.body.virtualMachineInfo?.imageReference?.["sku"], - version: - result.body.virtualMachineInfo?.imageReference?.["version"], - virtualMachineImageId: - result.body.virtualMachineInfo?.imageReference?.[ - "virtualMachineImageId" - ], - exactVersion: - result.body.virtualMachineInfo?.imageReference?.[ - "exactVersion" - ], - }, - }, - }; + return batchNodeDeserializer(result.body); } /** Gets information about the specified Compute Node. */ @@ -12412,10 +3843,7 @@ export function _rebootNodeSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: - body === undefined - ? body - : { nodeRebootOption: body["nodeRebootOption"] }, + body: !body ? body : nodeRebootOptionsSerializer(body), }); } @@ -12460,10 +3888,7 @@ export function _reimageNodeSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: - body === undefined - ? body - : { nodeReimageOption: body["nodeReimageOption"] }, + body: !body ? body : nodeReimageOptionsSerializer(body), }); } @@ -12512,12 +3937,7 @@ export function _disableNodeSchedulingSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: - body === undefined - ? body - : { - nodeDisableSchedulingOption: body["nodeDisableSchedulingOption"], - }, + body: !body ? body : nodeDisableSchedulingOptionsSerializer(body), }); } @@ -12625,10 +4045,7 @@ export async function _getNodeRemoteLoginSettingsDeserialize( throw createRestError(result); } - return { - remoteLoginIpAddress: result.body["remoteLoginIPAddress"], - remoteLoginPort: result.body["remoteLoginPort"], - }; + return batchNodeRemoteLoginSettingsResultDeserializer(result.body); } /** @@ -12726,14 +4143,7 @@ export function _uploadNodeLogsSend( "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, }, - body: { - containerUrl: body["containerUrl"], - startTime: body["startTime"].toISOString(), - endTime: body["endTime"]?.toISOString(), - identityReference: !body.identityReference - ? body.identityReference - : batchNodeIdentityReferenceSerializer(body.identityReference), - }, + body: uploadBatchServiceLogsOptionsSerializer(body), }); } @@ -12745,10 +4155,7 @@ export async function _uploadNodeLogsDeserialize( throw createRestError(result); } - return { - virtualDirectoryName: result.body["virtualDirectoryName"], - numberOfFilesUploaded: result.body["numberOfFilesUploaded"], - }; + return uploadBatchServiceLogsResultDeserializer(result.body); } /** @@ -12779,18 +4186,20 @@ export function _listNodesSend( poolId: string, options: ListNodesOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/pools/{poolId}/nodes", poolId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: options?.$select, - }, - }); + return context.path("/pools/{poolId}/nodes", poolId).get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + }, + }); } export async function _listNodesDeserialize( @@ -12801,326 +4210,7 @@ export async function _listNodesDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - id: p["id"], - url: p["url"], - state: p["state"], - schedulingState: p["schedulingState"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - lastBootTime: - p["lastBootTime"] !== undefined - ? new Date(p["lastBootTime"]) - : undefined, - allocationTime: - p["allocationTime"] !== undefined - ? new Date(p["allocationTime"]) - : undefined, - ipAddress: p["ipAddress"], - affinityId: p["affinityId"], - vmSize: p["vmSize"], - totalTasksRun: p["totalTasksRun"], - runningTasksCount: p["runningTasksCount"], - runningTaskSlotsCount: p["runningTaskSlotsCount"], - totalTasksSucceeded: p["totalTasksSucceeded"], - recentTasks: - p["recentTasks"] === undefined - ? p["recentTasks"] - : p["recentTasks"].map((p: any) => { - return { - taskUrl: p["taskUrl"], - jobId: p["jobId"], - taskId: p["taskId"], - subtaskId: p["subtaskId"], - taskState: p["taskState"], - executionInfo: !p.executionInfo - ? undefined - : { - startTime: - p.executionInfo?.["startTime"] !== undefined - ? new Date(p.executionInfo?.["startTime"]) - : undefined, - endTime: - p.executionInfo?.["endTime"] !== undefined - ? new Date(p.executionInfo?.["endTime"]) - : undefined, - exitCode: p.executionInfo?.["exitCode"], - containerInfo: !p.executionInfo?.containerInfo - ? undefined - : { - containerId: - p.executionInfo?.containerInfo?.[ - "containerId" - ], - state: - p.executionInfo?.containerInfo?.["state"], - error: - p.executionInfo?.containerInfo?.["error"], - }, - failureInfo: !p.executionInfo?.failureInfo - ? undefined - : { - category: - p.executionInfo?.failureInfo?.[ - "category" - ], - code: p.executionInfo?.failureInfo?.[ - "code" - ], - message: - p.executionInfo?.failureInfo?.["message"], - details: - p.executionInfo?.failureInfo?.[ - "details" - ] === undefined - ? p.executionInfo?.failureInfo?.[ - "details" - ] - : p.executionInfo?.failureInfo?.[ - "details" - ].map((p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }), - }, - retryCount: p.executionInfo?.["retryCount"], - lastRetryTime: - p.executionInfo?.["lastRetryTime"] !== undefined - ? new Date(p.executionInfo?.["lastRetryTime"]) - : undefined, - requeueCount: p.executionInfo?.["requeueCount"], - lastRequeueTime: - p.executionInfo?.["lastRequeueTime"] !== - undefined - ? new Date( - p.executionInfo?.["lastRequeueTime"], - ) - : undefined, - result: p.executionInfo?.["result"], - }, - }; - }), - startTask: !p.startTask - ? undefined - : { - commandLine: p.startTask?.["commandLine"], - containerSettings: !p.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.startTask?.containerSettings?.["imageName"], - registry: !p.startTask?.containerSettings?.registry - ? undefined - : { - username: - p.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - p.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.startTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - p.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.startTask?.["resourceFiles"] === undefined - ? p.startTask?.["resourceFiles"] - : p.startTask?.["resourceFiles"].map((p: any) => { - return { - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - }; - }), - environmentSettings: - p.startTask?.["environmentSettings"] === undefined - ? p.startTask?.["environmentSettings"] - : p.startTask?.["environmentSettings"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - userIdentity: !p.startTask?.userIdentity - ? undefined - : { - username: p.startTask?.userIdentity?.["username"], - autoUser: !p.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.startTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: p.startTask?.["maxTaskRetryCount"], - waitForSuccess: p.startTask?.["waitForSuccess"], - }, - startTaskInfo: !p.startTaskInfo - ? undefined - : { - state: p.startTaskInfo?.["state"], - startTime: new Date(p.startTaskInfo?.["startTime"]), - endTime: - p.startTaskInfo?.["endTime"] !== undefined - ? new Date(p.startTaskInfo?.["endTime"]) - : undefined, - exitCode: p.startTaskInfo?.["exitCode"], - containerInfo: !p.startTaskInfo?.containerInfo - ? undefined - : { - containerId: - p.startTaskInfo?.containerInfo?.["containerId"], - state: p.startTaskInfo?.containerInfo?.["state"], - error: p.startTaskInfo?.containerInfo?.["error"], - }, - failureInfo: !p.startTaskInfo?.failureInfo - ? undefined - : { - category: p.startTaskInfo?.failureInfo?.["category"], - code: p.startTaskInfo?.failureInfo?.["code"], - message: p.startTaskInfo?.failureInfo?.["message"], - details: - p.startTaskInfo?.failureInfo?.["details"] === - undefined - ? p.startTaskInfo?.failureInfo?.["details"] - : p.startTaskInfo?.failureInfo?.["details"].map( - (p: any) => { - return { - name: p["name"], - value: p["value"], - }; - }, - ), - }, - retryCount: p.startTaskInfo?.["retryCount"], - lastRetryTime: - p.startTaskInfo?.["lastRetryTime"] !== undefined - ? new Date(p.startTaskInfo?.["lastRetryTime"]) - : undefined, - result: p.startTaskInfo?.["result"], - }, - certificateReferences: - p["certificateReferences"] === undefined - ? p["certificateReferences"] - : p["certificateReferences"].map((p: any) => { - return { - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }; - }), - errors: - p["errors"] === undefined - ? p["errors"] - : p["errors"].map((p: any) => { - return { - code: p["code"], - message: p["message"], - errorDetails: - p["errorDetails"] === undefined - ? p["errorDetails"] - : p["errorDetails"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }; - }), - isDedicated: p["isDedicated"], - endpointConfiguration: !p.endpointConfiguration - ? undefined - : { - inboundEndpoints: p.endpointConfiguration?.[ - "inboundEndpoints" - ].map((p: any) => { - return { - name: p["name"], - protocol: p["protocol"], - publicIpAddress: p["publicIPAddress"], - publicFQDN: p["publicFQDN"], - frontendPort: p["frontendPort"], - backendPort: p["backendPort"], - }; - }), - }, - nodeAgentInfo: !p.nodeAgentInfo - ? undefined - : { - version: p.nodeAgentInfo?.["version"], - lastUpdateTime: new Date( - p.nodeAgentInfo?.["lastUpdateTime"], - ), - }, - virtualMachineInfo: !p.virtualMachineInfo - ? undefined - : { - imageReference: !p.virtualMachineInfo?.imageReference - ? undefined - : { - publisher: - p.virtualMachineInfo?.imageReference?.["publisher"], - offer: - p.virtualMachineInfo?.imageReference?.["offer"], - sku: p.virtualMachineInfo?.imageReference?.["sku"], - version: - p.virtualMachineInfo?.imageReference?.["version"], - virtualMachineImageId: - p.virtualMachineInfo?.imageReference?.[ - "virtualMachineImageId" - ], - exactVersion: - p.virtualMachineInfo?.imageReference?.[ - "exactVersion" - ], - }, - }, - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _batchNodeListResultDeserializer(result.body); } /** Lists the Compute Nodes in the specified Pool. */ @@ -13157,7 +4247,11 @@ export function _getNodeExtensionSend( queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, - $select: options?.$select, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), }, }); } @@ -13170,54 +4264,7 @@ export async function _getNodeExtensionDeserialize( throw createRestError(result); } - return { - provisioningState: result.body["provisioningState"], - vmExtension: !result.body.vmExtension - ? undefined - : { - name: result.body.vmExtension?.["name"], - publisher: result.body.vmExtension?.["publisher"], - type: result.body.vmExtension?.["type"], - typeHandlerVersion: result.body.vmExtension?.["typeHandlerVersion"], - autoUpgradeMinorVersion: - result.body.vmExtension?.["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - result.body.vmExtension?.["enableAutomaticUpgrade"], - settings: result.body.vmExtension?.["settings"], - protectedSettings: result.body.vmExtension?.["protectedSettings"], - provisionAfterExtensions: - result.body.vmExtension?.["provisionAfterExtensions"], - }, - instanceView: !result.body.instanceView - ? undefined - : { - name: result.body.instanceView?.["name"], - statuses: - result.body.instanceView?.["statuses"] === undefined - ? result.body.instanceView?.["statuses"] - : result.body.instanceView?.["statuses"].map((p: any) => { - return { - code: p["code"], - displayStatus: p["displayStatus"], - level: p["level"], - message: p["message"], - time: p["time"], - }; - }), - subStatuses: - result.body.instanceView?.["subStatuses"] === undefined - ? result.body.instanceView?.["subStatuses"] - : result.body.instanceView?.["subStatuses"].map((p: any) => { - return { - code: p["code"], - displayStatus: p["displayStatus"], - level: p["level"], - message: p["message"], - time: p["time"], - }; - }), - }, - }; + return nodeVMExtensionDeserializer(result.body); } /** Gets information about the specified Compute Node Extension. */ @@ -13251,7 +4298,11 @@ export function _listNodeExtensionsSend( queryParameters: { maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, - $select: options?.$select, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), }, }); } @@ -13264,62 +4315,7 @@ export async function _listNodeExtensionsDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - provisioningState: p["provisioningState"], - vmExtension: !p.vmExtension - ? undefined - : { - name: p.vmExtension?.["name"], - publisher: p.vmExtension?.["publisher"], - type: p.vmExtension?.["type"], - typeHandlerVersion: p.vmExtension?.["typeHandlerVersion"], - autoUpgradeMinorVersion: - p.vmExtension?.["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p.vmExtension?.["enableAutomaticUpgrade"], - settings: p.vmExtension?.["settings"], - protectedSettings: p.vmExtension?.["protectedSettings"], - provisionAfterExtensions: - p.vmExtension?.["provisionAfterExtensions"], - }, - instanceView: !p.instanceView - ? undefined - : { - name: p.instanceView?.["name"], - statuses: - p.instanceView?.["statuses"] === undefined - ? p.instanceView?.["statuses"] - : p.instanceView?.["statuses"].map((p: any) => { - return { - code: p["code"], - displayStatus: p["displayStatus"], - level: p["level"], - message: p["message"], - time: p["time"], - }; - }), - subStatuses: - p.instanceView?.["subStatuses"] === undefined - ? p.instanceView?.["subStatuses"] - : p.instanceView?.["subStatuses"].map((p: any) => { - return { - code: p["code"], - displayStatus: p["displayStatus"], - level: p["level"], - message: p["message"], - time: p["time"], - }; - }), - }, - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _nodeVMExtensionListDeserializer(result.body); } /** Lists the Compute Nodes Extensions in the specified Pool. */ @@ -13409,10 +4405,18 @@ export function _getNodeFileSend( ...operationOptionsToRequestParameters(options), headers: { ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), ...(options?.ocpRange !== undefined ? { "ocp-range": options?.ocpRange } @@ -13474,10 +4478,18 @@ export function _getNodeFilePropertiesSend( ...operationOptionsToRequestParameters(options), headers: { ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } : {}), ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } : {}), }, queryParameters: { @@ -13544,31 +4556,7 @@ export async function _listNodeFilesDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - name: p["name"], - url: p["url"], - isDirectory: p["isDirectory"], - properties: !p.properties - ? undefined - : { - creationTime: - p.properties?.["creationTime"] !== undefined - ? new Date(p.properties?.["creationTime"]) - : undefined, - lastModified: new Date(p.properties?.["lastModified"]), - contentLength: p.properties?.["contentLength"], - contentType: p.properties?.["contentType"], - fileMode: p.properties?.["fileMode"], - }, - }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _nodeFileListResultDeserializer(result.body); } /** Lists all of the files in Task directories on the specified Compute Node. */ diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/batchClient.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/batchClient.ts index 834d04e03d..26329f001b 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/batchClient.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/batchClient.ts @@ -1,128 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; -import { - BatchNodeUserCreateOptions, - BatchNodeUserUpdateOptions, - BatchNode, - NodeRebootOptions, - NodeReimageOptions, - NodeDisableSchedulingOptions, - BatchNodeRemoteLoginSettingsResult, - UploadBatchServiceLogsOptions, - UploadBatchServiceLogsResult, - NodeVMExtension, - NodeFile, - BatchTaskCreateOptions, - BatchTask, - BatchTaskCollection, - TaskAddCollectionResult, - BatchTaskListSubtasksResult, - BatchJobSchedule, - BatchJobScheduleUpdateOptions, - BatchJobScheduleCreateOptions, - BatchCertificate, - BatchJob, - BatchJobUpdateOptions, - BatchJobDisableOptions, - BatchJobTerminateOptions, - BatchJobCreateOptions, - JobPreparationAndReleaseTaskExecutionInformation, - TaskCountsResult, - ImageInformation, - PoolNodeCounts, - PoolUsageMetrics, - BatchPoolCreateOptions, - BatchPool, - AutoScaleRun, - BatchPoolUpdateOptions, - BatchPoolEnableAutoScaleOptions, - BatchPoolEvaluateAutoScaleOptions, - BatchPoolResizeOptions, - BatchPoolReplaceOptions, - NodeRemoveOptions, - BatchApplication, -} from "./models/models.js"; -import { - ListApplicationsOptionalParams, - GetApplicationOptionalParams, - ListPoolUsageMetricsOptionalParams, - CreatePoolOptionalParams, - ListPoolsOptionalParams, - DeletePoolOptionalParams, - PoolExistsOptionalParams, - GetPoolOptionalParams, - UpdatePoolOptionalParams, - DisablePoolAutoScaleOptionalParams, - EnablePoolAutoScaleOptionalParams, - EvaluatePoolAutoScaleOptionalParams, - ResizePoolOptionalParams, - StopPoolResizeOptionalParams, - ReplacePoolPropertiesOptionalParams, - RemoveNodesOptionalParams, - ListSupportedImagesOptionalParams, - ListPoolNodeCountsOptionalParams, - DeleteJobOptionalParams, - GetJobOptionalParams, - UpdateJobOptionalParams, - ReplaceJobOptionalParams, - DisableJobOptionalParams, - EnableJobOptionalParams, - TerminateJobOptionalParams, - CreateJobOptionalParams, - ListJobsOptionalParams, - ListJobsFromScheduleOptionalParams, - ListJobPreparationAndReleaseTaskStatusOptionalParams, - GetJobTaskCountsOptionalParams, - CreateCertificateOptionalParams, - ListCertificatesOptionalParams, - CancelCertificateDeletionOptionalParams, - DeleteCertificateOptionalParams, - GetCertificateOptionalParams, - JobScheduleExistsOptionalParams, - DeleteJobScheduleOptionalParams, - GetJobScheduleOptionalParams, - UpdateJobScheduleOptionalParams, - ReplaceJobScheduleOptionalParams, - DisableJobScheduleOptionalParams, - EnableJobScheduleOptionalParams, - TerminateJobScheduleOptionalParams, - CreateJobScheduleOptionalParams, - ListJobSchedulesOptionalParams, - CreateTaskOptionalParams, - ListTasksOptionalParams, - CreateTaskCollectionOptionalParams, - DeleteTaskOptionalParams, - GetTaskOptionalParams, - ReplaceTaskOptionalParams, - ListSubTasksOptionalParams, - TerminateTaskOptionalParams, - ReactivateTaskOptionalParams, - DeleteTaskFileOptionalParams, - GetTaskFileOptionalParams, - GetTaskFilePropertiesOptionalParams, - ListTaskFilesOptionalParams, - CreateNodeUserOptionalParams, - DeleteNodeUserOptionalParams, - ReplaceNodeUserOptionalParams, - GetNodeOptionalParams, - RebootNodeOptionalParams, - ReimageNodeOptionalParams, - DisableNodeSchedulingOptionalParams, - EnableNodeSchedulingOptionalParams, - GetNodeRemoteLoginSettingsOptionalParams, - GetNodeRemoteDesktopFileOptionalParams, - UploadNodeLogsOptionalParams, - ListNodesOptionalParams, - GetNodeExtensionOptionalParams, - ListNodeExtensionsOptionalParams, - DeleteNodeFileOptionalParams, - GetNodeFileOptionalParams, - GetNodeFilePropertiesOptionalParams, - ListNodeFilesOptionalParams, -} from "./models/options.js"; import { createBatch, BatchContext, @@ -203,8 +81,128 @@ import { getNodeFile, getNodeFileProperties, listNodeFiles, + ListApplicationsOptionalParams, + GetApplicationOptionalParams, + ListPoolUsageMetricsOptionalParams, + CreatePoolOptionalParams, + ListPoolsOptionalParams, + DeletePoolOptionalParams, + PoolExistsOptionalParams, + GetPoolOptionalParams, + UpdatePoolOptionalParams, + DisablePoolAutoScaleOptionalParams, + EnablePoolAutoScaleOptionalParams, + EvaluatePoolAutoScaleOptionalParams, + ResizePoolOptionalParams, + StopPoolResizeOptionalParams, + ReplacePoolPropertiesOptionalParams, + RemoveNodesOptionalParams, + ListSupportedImagesOptionalParams, + ListPoolNodeCountsOptionalParams, + DeleteJobOptionalParams, + GetJobOptionalParams, + UpdateJobOptionalParams, + ReplaceJobOptionalParams, + DisableJobOptionalParams, + EnableJobOptionalParams, + TerminateJobOptionalParams, + CreateJobOptionalParams, + ListJobsOptionalParams, + ListJobsFromScheduleOptionalParams, + ListJobPreparationAndReleaseTaskStatusOptionalParams, + GetJobTaskCountsOptionalParams, + CreateCertificateOptionalParams, + ListCertificatesOptionalParams, + CancelCertificateDeletionOptionalParams, + DeleteCertificateOptionalParams, + GetCertificateOptionalParams, + JobScheduleExistsOptionalParams, + DeleteJobScheduleOptionalParams, + GetJobScheduleOptionalParams, + UpdateJobScheduleOptionalParams, + ReplaceJobScheduleOptionalParams, + DisableJobScheduleOptionalParams, + EnableJobScheduleOptionalParams, + TerminateJobScheduleOptionalParams, + CreateJobScheduleOptionalParams, + ListJobSchedulesOptionalParams, + CreateTaskOptionalParams, + ListTasksOptionalParams, + CreateTaskCollectionOptionalParams, + DeleteTaskOptionalParams, + GetTaskOptionalParams, + ReplaceTaskOptionalParams, + ListSubTasksOptionalParams, + TerminateTaskOptionalParams, + ReactivateTaskOptionalParams, + DeleteTaskFileOptionalParams, + GetTaskFileOptionalParams, + GetTaskFilePropertiesOptionalParams, + ListTaskFilesOptionalParams, + CreateNodeUserOptionalParams, + DeleteNodeUserOptionalParams, + ReplaceNodeUserOptionalParams, + GetNodeOptionalParams, + RebootNodeOptionalParams, + ReimageNodeOptionalParams, + DisableNodeSchedulingOptionalParams, + EnableNodeSchedulingOptionalParams, + GetNodeRemoteLoginSettingsOptionalParams, + GetNodeRemoteDesktopFileOptionalParams, + UploadNodeLogsOptionalParams, + ListNodesOptionalParams, + GetNodeExtensionOptionalParams, + ListNodeExtensionsOptionalParams, + DeleteNodeFileOptionalParams, + GetNodeFileOptionalParams, + GetNodeFilePropertiesOptionalParams, + ListNodeFilesOptionalParams, } from "./api/index.js"; +import { + BatchNodeUserCreateOptions, + BatchNodeUserUpdateOptions, + BatchNode, + NodeRebootOptions, + NodeReimageOptions, + NodeDisableSchedulingOptions, + BatchNodeRemoteLoginSettingsResult, + UploadBatchServiceLogsOptions, + UploadBatchServiceLogsResult, + NodeVMExtension, + NodeFile, + BatchTaskCreateOptions, + BatchTask, + BatchTaskCollection, + TaskAddCollectionResult, + BatchTaskListSubtasksResult, + BatchJobSchedule, + BatchJobScheduleUpdateOptions, + BatchJobScheduleCreateOptions, + BatchCertificate, + BatchJob, + BatchJobUpdateOptions, + BatchJobDisableOptions, + BatchJobTerminateOptions, + BatchJobCreateOptions, + JobPreparationAndReleaseTaskExecutionInformation, + TaskCountsResult, + ImageInformation, + PoolNodeCounts, + PoolUsageMetrics, + BatchPoolCreateOptions, + BatchPool, + AutoScaleRun, + BatchPoolUpdateOptions, + BatchPoolEnableAutoScaleOptions, + BatchPoolEvaluateAutoScaleOptions, + BatchPoolResizeOptions, + BatchPoolReplaceOptions, + NodeRemoveOptions, + BatchApplication, +} from "./models/models.js"; import { PagedAsyncIterableIterator } from "./static-helpers/pagingHelpers.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TokenCredential } from "@azure/core-auth"; export { BatchClientOptionalParams } from "./api/batchContext.js"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts index 17603c26e2..f9b9845b5e 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts @@ -7,7 +7,7 @@ import { PagedAsyncIterableIterator, } from "./static-helpers/pagingHelpers.js"; -export { BatchClient, BatchClientOptionalParams } from "./batchClient.js"; +export { BatchClient } from "./batchClient.js"; export { BatchNodeUserCreateOptions, BatchError, @@ -200,7 +200,9 @@ export { BatchPoolReplaceOptions, NodeRemoveOptions, BatchApplication, - Versions, +} from "./models/index.js"; +export { + BatchClientOptionalParams, ListApplicationsOptionalParams, GetApplicationOptionalParams, ListPoolUsageMetricsOptionalParams, @@ -277,5 +279,5 @@ export { GetNodeFileOptionalParams, GetNodeFilePropertiesOptionalParams, ListNodeFilesOptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts index 1c1131b974..dcbfd2ea4d 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts @@ -193,83 +193,4 @@ export { BatchPoolReplaceOptions, NodeRemoveOptions, BatchApplication, - Versions, } from "./models.js"; -export { - ListApplicationsOptionalParams, - GetApplicationOptionalParams, - ListPoolUsageMetricsOptionalParams, - CreatePoolOptionalParams, - ListPoolsOptionalParams, - DeletePoolOptionalParams, - PoolExistsOptionalParams, - GetPoolOptionalParams, - UpdatePoolOptionalParams, - DisablePoolAutoScaleOptionalParams, - EnablePoolAutoScaleOptionalParams, - EvaluatePoolAutoScaleOptionalParams, - ResizePoolOptionalParams, - StopPoolResizeOptionalParams, - ReplacePoolPropertiesOptionalParams, - RemoveNodesOptionalParams, - ListSupportedImagesOptionalParams, - ListPoolNodeCountsOptionalParams, - DeleteJobOptionalParams, - GetJobOptionalParams, - UpdateJobOptionalParams, - ReplaceJobOptionalParams, - DisableJobOptionalParams, - EnableJobOptionalParams, - TerminateJobOptionalParams, - CreateJobOptionalParams, - ListJobsOptionalParams, - ListJobsFromScheduleOptionalParams, - ListJobPreparationAndReleaseTaskStatusOptionalParams, - GetJobTaskCountsOptionalParams, - CreateCertificateOptionalParams, - ListCertificatesOptionalParams, - CancelCertificateDeletionOptionalParams, - DeleteCertificateOptionalParams, - GetCertificateOptionalParams, - JobScheduleExistsOptionalParams, - DeleteJobScheduleOptionalParams, - GetJobScheduleOptionalParams, - UpdateJobScheduleOptionalParams, - ReplaceJobScheduleOptionalParams, - DisableJobScheduleOptionalParams, - EnableJobScheduleOptionalParams, - TerminateJobScheduleOptionalParams, - CreateJobScheduleOptionalParams, - ListJobSchedulesOptionalParams, - CreateTaskOptionalParams, - ListTasksOptionalParams, - CreateTaskCollectionOptionalParams, - DeleteTaskOptionalParams, - GetTaskOptionalParams, - ReplaceTaskOptionalParams, - ListSubTasksOptionalParams, - TerminateTaskOptionalParams, - ReactivateTaskOptionalParams, - DeleteTaskFileOptionalParams, - GetTaskFileOptionalParams, - GetTaskFilePropertiesOptionalParams, - ListTaskFilesOptionalParams, - CreateNodeUserOptionalParams, - DeleteNodeUserOptionalParams, - ReplaceNodeUserOptionalParams, - GetNodeOptionalParams, - RebootNodeOptionalParams, - ReimageNodeOptionalParams, - DisableNodeSchedulingOptionalParams, - EnableNodeSchedulingOptionalParams, - GetNodeRemoteLoginSettingsOptionalParams, - GetNodeRemoteDesktopFileOptionalParams, - UploadNodeLogsOptionalParams, - ListNodesOptionalParams, - GetNodeExtensionOptionalParams, - ListNodeExtensionsOptionalParams, - DeleteNodeFileOptionalParams, - GetNodeFileOptionalParams, - GetNodeFilePropertiesOptionalParams, - ListNodeFilesOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts index 7f676a34f2..c5384cb5b9 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts @@ -1,8 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { serializeRecord } from "../helpers/serializerHelpers.js"; -import { uint8ArrayToString } from "@azure/core-util"; +import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; /** Options for creating a user account for RDP or SSH access on an Azure Batch Compute Node. */ export interface BatchNodeUserCreateOptions { @@ -20,7 +19,7 @@ export interface BatchNodeUserCreateOptions { export function batchNodeUserCreateOptionsSerializer( item: BatchNodeUserCreateOptions, -): Record { +): any { return { name: item["name"], isAdmin: item["isAdmin"], @@ -40,6 +39,18 @@ export interface BatchError { values?: BatchErrorDetail[]; } +export function batchErrorDeserializer(item: any): BatchError { + return { + code: item["code"], + message: !item["message"] + ? item["message"] + : errorMessageDeserializer(item["message"]), + values: !item["values"] + ? item["values"] + : batchErrorDetailArrayDeserializer(item["values"]), + }; +} + /** An error message received in an Azure Batch error response. */ export interface ErrorMessage { /** The language code of the error message. */ @@ -48,6 +59,13 @@ export interface ErrorMessage { value?: string; } +export function errorMessageDeserializer(item: any): ErrorMessage { + return { + lang: item["lang"], + value: item["value"], + }; +} + /** An item of additional information included in an Azure Batch error response. */ export interface BatchErrorDetail { /** An identifier specifying the meaning of the Value property. */ @@ -56,6 +74,21 @@ export interface BatchErrorDetail { value?: string; } +export function batchErrorDetailDeserializer(item: any): BatchErrorDetail { + return { + key: item["key"], + value: item["value"], + }; +} + +export function batchErrorDetailArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return batchErrorDetailDeserializer(item); + }); +} + /** Options for updating a user account for RDP or SSH access on an Azure Batch Compute Node. */ export interface BatchNodeUserUpdateOptions { /** The password of the Account. The password is required for Windows Compute Nodes (those created with 'cloudServiceConfiguration', or created with 'virtualMachineConfiguration' using a Windows Image reference). For Linux Compute Nodes, the password can optionally be specified along with the sshPublicKey property. If omitted, any existing password is removed. */ @@ -68,7 +101,7 @@ export interface BatchNodeUserUpdateOptions { export function batchNodeUserUpdateOptionsSerializer( item: BatchNodeUserUpdateOptions, -): Record { +): any { return { password: item["password"], expiryTime: item["expiryTime"]?.toISOString(), @@ -131,6 +164,58 @@ export interface BatchNode { virtualMachineInfo?: VirtualMachineInfo; } +export function batchNodeDeserializer(item: any): BatchNode { + return { + id: item["id"], + url: item["url"], + state: item["state"], + schedulingState: item["schedulingState"], + stateTransitionTime: !item["stateTransitionTime"] + ? item["stateTransitionTime"] + : new Date(item["stateTransitionTime"]), + lastBootTime: !item["lastBootTime"] + ? item["lastBootTime"] + : new Date(item["lastBootTime"]), + allocationTime: !item["allocationTime"] + ? item["allocationTime"] + : new Date(item["allocationTime"]), + ipAddress: item["ipAddress"], + affinityId: item["affinityId"], + vmSize: item["vmSize"], + totalTasksRun: item["totalTasksRun"], + runningTasksCount: item["runningTasksCount"], + runningTaskSlotsCount: item["runningTaskSlotsCount"], + totalTasksSucceeded: item["totalTasksSucceeded"], + recentTasks: !item["recentTasks"] + ? item["recentTasks"] + : taskInformationArrayDeserializer(item["recentTasks"]), + startTask: !item["startTask"] + ? item["startTask"] + : startTaskDeserializer(item["startTask"]), + startTaskInfo: !item["startTaskInfo"] + ? item["startTaskInfo"] + : startTaskInformationDeserializer(item["startTaskInfo"]), + certificateReferences: !item["certificateReferences"] + ? item["certificateReferences"] + : certificateReferenceArrayDeserializer(item["certificateReferences"]), + errors: !item["errors"] + ? item["errors"] + : batchNodeErrorArrayDeserializer(item["errors"]), + isDedicated: item["isDedicated"], + endpointConfiguration: !item["endpointConfiguration"] + ? item["endpointConfiguration"] + : batchNodeEndpointConfigurationDeserializer( + item["endpointConfiguration"], + ), + nodeAgentInfo: !item["nodeAgentInfo"] + ? item["nodeAgentInfo"] + : nodeAgentInformationDeserializer(item["nodeAgentInfo"]), + virtualMachineInfo: !item["virtualMachineInfo"] + ? item["virtualMachineInfo"] + : virtualMachineInfoDeserializer(item["virtualMachineInfo"]), + }; +} + /** BatchNodeState enums */ export type BatchNodeState = | "idle" @@ -165,6 +250,19 @@ export interface TaskInformation { executionInfo?: TaskExecutionInformation; } +export function taskInformationDeserializer(item: any): TaskInformation { + return { + taskUrl: item["taskUrl"], + jobId: item["jobId"], + taskId: item["taskId"], + subtaskId: item["subtaskId"], + taskState: item["taskState"], + executionInfo: !item["executionInfo"] + ? item["executionInfo"] + : taskExecutionInformationDeserializer(item["executionInfo"]), + }; +} + /** TaskState enums */ export type TaskState = "active" | "preparing" | "running" | "completed"; @@ -192,6 +290,33 @@ export interface TaskExecutionInformation { result?: TaskExecutionResult; } +export function taskExecutionInformationDeserializer( + item: any, +): TaskExecutionInformation { + return { + startTime: !item["startTime"] + ? item["startTime"] + : new Date(item["startTime"]), + endTime: !item["endTime"] ? item["endTime"] : new Date(item["endTime"]), + exitCode: item["exitCode"], + containerInfo: !item["containerInfo"] + ? item["containerInfo"] + : taskContainerExecutionInformationDeserializer(item["containerInfo"]), + failureInfo: !item["failureInfo"] + ? item["failureInfo"] + : taskFailureInformationDeserializer(item["failureInfo"]), + retryCount: item["retryCount"], + lastRetryTime: !item["lastRetryTime"] + ? item["lastRetryTime"] + : new Date(item["lastRetryTime"]), + requeueCount: item["requeueCount"], + lastRequeueTime: !item["lastRequeueTime"] + ? item["lastRequeueTime"] + : new Date(item["lastRequeueTime"]), + result: item["result"], + }; +} + /** Contains information about the container which a Task is executing. */ export interface TaskContainerExecutionInformation { /** The ID of the container. */ @@ -202,6 +327,16 @@ export interface TaskContainerExecutionInformation { error?: string; } +export function taskContainerExecutionInformationDeserializer( + item: any, +): TaskContainerExecutionInformation { + return { + containerId: item["containerId"], + state: item["state"], + error: item["error"], + }; +} + /** Information about a Task failure. */ export interface TaskFailureInformation { /** The category of the Task error. */ @@ -214,6 +349,19 @@ export interface TaskFailureInformation { details?: NameValuePair[]; } +export function taskFailureInformationDeserializer( + item: any, +): TaskFailureInformation { + return { + category: item["category"], + code: item["code"], + message: item["message"], + details: !item["details"] + ? item["details"] + : nameValuePairArrayDeserializer(item["details"]), + }; +} + /** ErrorCategory enums */ export type ErrorCategory = "usererror" | "servererror"; @@ -225,9 +373,32 @@ export interface NameValuePair { value?: string; } +export function nameValuePairDeserializer(item: any): NameValuePair { + return { + name: item["name"], + value: item["value"], + }; +} + +export function nameValuePairArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return nameValuePairDeserializer(item); + }); +} + /** TaskExecutionResult enums */ export type TaskExecutionResult = "success" | "failure"; +export function taskInformationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return taskInformationDeserializer(item); + }); +} + /** * Batch will retry Tasks when a recovery operation is triggered on a Node. * Examples of recovery operations include (but are not limited to) when an @@ -260,23 +431,41 @@ export interface StartTask { waitForSuccess?: boolean; } -export function startTaskSerializer(item: StartTask): Record { +export function startTaskSerializer(item: StartTask): any { return { commandLine: item["commandLine"], - containerSettings: !item.containerSettings - ? item.containerSettings - : taskContainerSettingsSerializer(item.containerSettings), - resourceFiles: - item["resourceFiles"] === undefined - ? item["resourceFiles"] - : item["resourceFiles"].map(resourceFileSerializer), - environmentSettings: - item["environmentSettings"] === undefined - ? item["environmentSettings"] - : item["environmentSettings"].map(environmentSettingSerializer), - userIdentity: !item.userIdentity - ? item.userIdentity - : userIdentitySerializer(item.userIdentity), + containerSettings: !item["containerSettings"] + ? item["containerSettings"] + : taskContainerSettingsSerializer(item["containerSettings"]), + resourceFiles: !item["resourceFiles"] + ? item["resourceFiles"] + : resourceFileArraySerializer(item["resourceFiles"]), + environmentSettings: !item["environmentSettings"] + ? item["environmentSettings"] + : environmentSettingArraySerializer(item["environmentSettings"]), + userIdentity: !item["userIdentity"] + ? item["userIdentity"] + : userIdentitySerializer(item["userIdentity"]), + maxTaskRetryCount: item["maxTaskRetryCount"], + waitForSuccess: item["waitForSuccess"], + }; +} + +export function startTaskDeserializer(item: any): StartTask { + return { + commandLine: item["commandLine"], + containerSettings: !item["containerSettings"] + ? item["containerSettings"] + : taskContainerSettingsDeserializer(item["containerSettings"]), + resourceFiles: !item["resourceFiles"] + ? item["resourceFiles"] + : resourceFileArrayDeserializer(item["resourceFiles"]), + environmentSettings: !item["environmentSettings"] + ? item["environmentSettings"] + : environmentSettingArrayDeserializer(item["environmentSettings"]), + userIdentity: !item["userIdentity"] + ? item["userIdentity"] + : userIdentityDeserializer(item["userIdentity"]), maxTaskRetryCount: item["maxTaskRetryCount"], waitForSuccess: item["waitForSuccess"], }; @@ -296,13 +485,26 @@ export interface TaskContainerSettings { export function taskContainerSettingsSerializer( item: TaskContainerSettings, -): Record { +): any { return { containerRunOptions: item["containerRunOptions"], imageName: item["imageName"], - registry: !item.registry - ? item.registry - : containerRegistrySerializer(item.registry), + registry: !item["registry"] + ? item["registry"] + : containerRegistrySerializer(item["registry"]), + workingDirectory: item["workingDirectory"], + }; +} + +export function taskContainerSettingsDeserializer( + item: any, +): TaskContainerSettings { + return { + containerRunOptions: item["containerRunOptions"], + imageName: item["imageName"], + registry: !item["registry"] + ? item["registry"] + : containerRegistryDeserializer(item["registry"]), workingDirectory: item["workingDirectory"], }; } @@ -319,16 +521,25 @@ export interface ContainerRegistry { identityReference?: BatchNodeIdentityReference; } -export function containerRegistrySerializer( - item: ContainerRegistry, -): Record { +export function containerRegistrySerializer(item: ContainerRegistry): any { return { username: item["username"], password: item["password"], registryServer: item["registryServer"], - identityReference: !item.identityReference - ? item.identityReference - : batchNodeIdentityReferenceSerializer(item.identityReference), + identityReference: !item["identityReference"] + ? item["identityReference"] + : batchNodeIdentityReferenceSerializer(item["identityReference"]), + }; +} + +export function containerRegistryDeserializer(item: any): ContainerRegistry { + return { + username: item["username"], + password: item["password"], + registryServer: item["registryServer"], + identityReference: !item["identityReference"] + ? item["identityReference"] + : batchNodeIdentityReferenceDeserializer(item["identityReference"]), }; } @@ -343,7 +554,13 @@ export interface BatchNodeIdentityReference { export function batchNodeIdentityReferenceSerializer( item: BatchNodeIdentityReference, -): Record { +): any { + return { resourceId: item["resourceId"] }; +} + +export function batchNodeIdentityReferenceDeserializer( + item: any, +): BatchNodeIdentityReference { return { resourceId: item["resourceId"], }; @@ -372,9 +589,21 @@ export interface ResourceFile { identityReference?: BatchNodeIdentityReference; } -export function resourceFileSerializer( - item: ResourceFile, -): Record { +export function resourceFileSerializer(item: ResourceFile): any { + return { + autoStorageContainerName: item["autoStorageContainerName"], + storageContainerUrl: item["storageContainerUrl"], + httpUrl: item["httpUrl"], + blobPrefix: item["blobPrefix"], + filePath: item["filePath"], + fileMode: item["fileMode"], + identityReference: !item["identityReference"] + ? item["identityReference"] + : batchNodeIdentityReferenceSerializer(item["identityReference"]), + }; +} + +export function resourceFileDeserializer(item: any): ResourceFile { return { autoStorageContainerName: item["autoStorageContainerName"], storageContainerUrl: item["storageContainerUrl"], @@ -382,12 +611,28 @@ export function resourceFileSerializer( blobPrefix: item["blobPrefix"], filePath: item["filePath"], fileMode: item["fileMode"], - identityReference: !item.identityReference - ? item.identityReference - : batchNodeIdentityReferenceSerializer(item.identityReference), + identityReference: !item["identityReference"] + ? item["identityReference"] + : batchNodeIdentityReferenceDeserializer(item["identityReference"]), }; } +export function resourceFileArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return resourceFileSerializer(item); + }); +} + +export function resourceFileArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return resourceFileDeserializer(item); + }); +} + /** An environment variable to be set on a Task process. */ export interface EnvironmentSetting { /** The name of the environment variable. */ @@ -396,15 +641,33 @@ export interface EnvironmentSetting { value?: string; } -export function environmentSettingSerializer( - item: EnvironmentSetting, -): Record { +export function environmentSettingSerializer(item: EnvironmentSetting): any { + return { name: item["name"], value: item["value"] }; +} + +export function environmentSettingDeserializer(item: any): EnvironmentSetting { return { name: item["name"], value: item["value"], }; } +export function environmentSettingArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return environmentSettingSerializer(item); + }); +} + +export function environmentSettingArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return environmentSettingDeserializer(item); + }); +} + /** The definition of the user identity under which the Task is run. Specify either the userName or autoUser property, but not both. */ export interface UserIdentity { /** The name of the user identity under which the Task is run. The userName and autoUser properties are mutually exclusive; you must specify one but not both. */ @@ -413,14 +676,21 @@ export interface UserIdentity { autoUser?: AutoUserSpecification; } -export function userIdentitySerializer( - item: UserIdentity, -): Record { +export function userIdentitySerializer(item: UserIdentity): any { + return { + username: item["username"], + autoUser: !item["autoUser"] + ? item["autoUser"] + : autoUserSpecificationSerializer(item["autoUser"]), + }; +} + +export function userIdentityDeserializer(item: any): UserIdentity { return { username: item["username"], - autoUser: !item.autoUser - ? item.autoUser - : autoUserSpecificationSerializer(item.autoUser), + autoUser: !item["autoUser"] + ? item["autoUser"] + : autoUserSpecificationDeserializer(item["autoUser"]), }; } @@ -434,7 +704,13 @@ export interface AutoUserSpecification { export function autoUserSpecificationSerializer( item: AutoUserSpecification, -): Record { +): any { + return { scope: item["scope"], elevationLevel: item["elevationLevel"] }; +} + +export function autoUserSpecificationDeserializer( + item: any, +): AutoUserSpecification { return { scope: item["scope"], elevationLevel: item["elevationLevel"], @@ -468,6 +744,28 @@ export interface StartTaskInformation { result?: TaskExecutionResult; } +export function startTaskInformationDeserializer( + item: any, +): StartTaskInformation { + return { + state: item["state"], + startTime: new Date(item["startTime"]), + endTime: !item["endTime"] ? item["endTime"] : new Date(item["endTime"]), + exitCode: item["exitCode"], + containerInfo: !item["containerInfo"] + ? item["containerInfo"] + : taskContainerExecutionInformationDeserializer(item["containerInfo"]), + failureInfo: !item["failureInfo"] + ? item["failureInfo"] + : taskFailureInformationDeserializer(item["failureInfo"]), + retryCount: item["retryCount"], + lastRetryTime: !item["lastRetryTime"] + ? item["lastRetryTime"] + : new Date(item["lastRetryTime"]), + result: item["result"], + }; +} + /** StartTaskState enums */ export type StartTaskState = "running" | "completed"; @@ -487,13 +785,33 @@ export interface CertificateReference { export function certificateReferenceSerializer( item: CertificateReference, -): Record { +): any { return { thumbprint: item["thumbprint"], thumbprintAlgorithm: item["thumbprintAlgorithm"], storeLocation: item["storeLocation"], storeName: item["storeName"], - visibility: item["visibility"], + visibility: !item["visibility"] + ? item["visibility"] + : item["visibility"].map((p: any) => { + return p; + }), + }; +} + +export function certificateReferenceDeserializer( + item: any, +): CertificateReference { + return { + thumbprint: item["thumbprint"], + thumbprintAlgorithm: item["thumbprintAlgorithm"], + storeLocation: item["storeLocation"], + storeName: item["storeName"], + visibility: !item["visibility"] + ? item["visibility"] + : item["visibility"].map((p: any) => { + return p; + }), }; } @@ -502,6 +820,22 @@ export type CertificateStoreLocation = "currentuser" | "localmachine"; /** CertificateVisibility enums */ export type CertificateVisibility = "starttask" | "task" | "remoteuser"; +export function certificateReferenceArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return certificateReferenceSerializer(item); + }); +} + +export function certificateReferenceArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return certificateReferenceDeserializer(item); + }); +} + /** An error encountered by a Compute Node. */ export interface BatchNodeError { /** An identifier for the Compute Node error. Codes are invariant and are intended to be consumed programmatically. */ @@ -512,12 +846,40 @@ export interface BatchNodeError { errorDetails?: NameValuePair[]; } +export function batchNodeErrorDeserializer(item: any): BatchNodeError { + return { + code: item["code"], + message: item["message"], + errorDetails: !item["errorDetails"] + ? item["errorDetails"] + : nameValuePairArrayDeserializer(item["errorDetails"]), + }; +} + +export function batchNodeErrorArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return batchNodeErrorDeserializer(item); + }); +} + /** The endpoint configuration for the Compute Node. */ export interface BatchNodeEndpointConfiguration { /** The list of inbound endpoints that are accessible on the Compute Node. */ inboundEndpoints: InboundEndpoint[]; } +export function batchNodeEndpointConfigurationDeserializer( + item: any, +): BatchNodeEndpointConfiguration { + return { + inboundEndpoints: inboundEndpointArrayDeserializer( + item["inboundEndpoints"], + ), + }; +} + /** An inbound endpoint on a Compute Node. */ export interface InboundEndpoint { /** The name of the endpoint. */ @@ -534,9 +896,28 @@ export interface InboundEndpoint { backendPort: number; } +export function inboundEndpointDeserializer(item: any): InboundEndpoint { + return { + name: item["name"], + protocol: item["protocol"], + publicIpAddress: item["publicIPAddress"], + publicFQDN: item["publicFQDN"], + frontendPort: item["frontendPort"], + backendPort: item["backendPort"], + }; +} + /** InboundEndpointProtocol enums */ export type InboundEndpointProtocol = "tcp" | "udp"; +export function inboundEndpointArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return inboundEndpointDeserializer(item); + }); +} + /** * The Batch Compute Node agent is a program that runs on each Compute Node in the * Pool and provides Batch capability on the Compute Node. @@ -548,12 +929,29 @@ export interface NodeAgentInformation { lastUpdateTime: Date; } +export function nodeAgentInformationDeserializer( + item: any, +): NodeAgentInformation { + return { + version: item["version"], + lastUpdateTime: new Date(item["lastUpdateTime"]), + }; +} + /** Info about the current state of the virtual machine. */ export interface VirtualMachineInfo { /** The reference to the Azure Virtual Machine's Marketplace Image. */ imageReference?: ImageReference; } +export function virtualMachineInfoDeserializer(item: any): VirtualMachineInfo { + return { + imageReference: !item["imageReference"] + ? item["imageReference"] + : imageReferenceDeserializer(item["imageReference"]), + }; +} + /** * A reference to an Azure Virtual Machines Marketplace Image or a Shared Image * Gallery Image. To get the list of all Azure Marketplace Image references @@ -574,9 +972,7 @@ export interface ImageReference { readonly exactVersion?: string; } -export function imageReferenceSerializer( - item: ImageReference, -): Record { +export function imageReferenceSerializer(item: ImageReference): any { return { publisher: item["publisher"], offer: item["offer"], @@ -586,18 +982,25 @@ export function imageReferenceSerializer( }; } +export function imageReferenceDeserializer(item: any): ImageReference { + return { + publisher: item["publisher"], + offer: item["offer"], + sku: item["sku"], + version: item["version"], + virtualMachineImageId: item["virtualMachineImageId"], + exactVersion: item["exactVersion"], + }; +} + /** Options for rebooting an Azure Batch Compute Node. */ export interface NodeRebootOptions { /** When to reboot the Compute Node and what to do with currently running Tasks. The default value is requeue. */ nodeRebootOption?: BatchNodeRebootOption; } -export function nodeRebootOptionsSerializer( - item: NodeRebootOptions, -): Record { - return { - nodeRebootOption: item["nodeRebootOption"], - }; +export function nodeRebootOptionsSerializer(item: NodeRebootOptions): any { + return { nodeRebootOption: item["nodeRebootOption"] }; } /** BatchNodeRebootOption enums */ @@ -613,12 +1016,8 @@ export interface NodeReimageOptions { nodeReimageOption?: BatchNodeReimageOption; } -export function nodeReimageOptionsSerializer( - item: NodeReimageOptions, -): Record { - return { - nodeReimageOption: item["nodeReimageOption"], - }; +export function nodeReimageOptionsSerializer(item: NodeReimageOptions): any { + return { nodeReimageOption: item["nodeReimageOption"] }; } /** BatchNodeReimageOption enums */ @@ -636,10 +1035,8 @@ export interface NodeDisableSchedulingOptions { export function nodeDisableSchedulingOptionsSerializer( item: NodeDisableSchedulingOptions, -): Record { - return { - nodeDisableSchedulingOption: item["nodeDisableSchedulingOption"], - }; +): any { + return { nodeDisableSchedulingOption: item["nodeDisableSchedulingOption"] }; } /** DisableBatchNodeSchedulingOption enums */ @@ -656,6 +1053,15 @@ export interface BatchNodeRemoteLoginSettingsResult { remoteLoginPort: number; } +export function batchNodeRemoteLoginSettingsResultDeserializer( + item: any, +): BatchNodeRemoteLoginSettingsResult { + return { + remoteLoginIpAddress: item["remoteLoginIPAddress"], + remoteLoginPort: item["remoteLoginPort"], + }; +} + /** The Azure Batch service log files upload options for a Compute Node. */ export interface UploadBatchServiceLogsOptions { /** The URL of the container within Azure Blob Storage to which to upload the Batch Service log file(s). If a user assigned managed identity is not being used, the URL must include a Shared Access Signature (SAS) granting write permissions to the container. The SAS duration must allow enough time for the upload to finish. The start time for SAS is optional and recommended to not be specified. */ @@ -670,14 +1076,14 @@ export interface UploadBatchServiceLogsOptions { export function uploadBatchServiceLogsOptionsSerializer( item: UploadBatchServiceLogsOptions, -): Record { +): any { return { containerUrl: item["containerUrl"], startTime: item["startTime"].toISOString(), endTime: item["endTime"]?.toISOString(), - identityReference: !item.identityReference - ? item.identityReference - : batchNodeIdentityReferenceSerializer(item.identityReference), + identityReference: !item["identityReference"] + ? item["identityReference"] + : batchNodeIdentityReferenceSerializer(item["identityReference"]), }; } @@ -689,6 +1095,15 @@ export interface UploadBatchServiceLogsResult { numberOfFilesUploaded: number; } +export function uploadBatchServiceLogsResultDeserializer( + item: any, +): UploadBatchServiceLogsResult { + return { + virtualDirectoryName: item["virtualDirectoryName"], + numberOfFilesUploaded: item["numberOfFilesUploaded"], + }; +} + /** The result of listing the Compute Nodes in a Pool. */ export interface _BatchNodeListResult { /** The list of Compute Nodes. */ @@ -697,6 +1112,23 @@ export interface _BatchNodeListResult { "odata.nextLink"?: string; } +export function _batchNodeListResultDeserializer( + item: any, +): _BatchNodeListResult { + return { + value: !item["value"] + ? item["value"] + : batchNodeArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + +export function batchNodeArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return batchNodeDeserializer(item); + }); +} + /** The configuration for virtual machine extension instance view. */ export interface NodeVMExtension { /** The provisioning state of the virtual machine extension. */ @@ -707,6 +1139,18 @@ export interface NodeVMExtension { instanceView?: VMExtensionInstanceView; } +export function nodeVMExtensionDeserializer(item: any): NodeVMExtension { + return { + provisioningState: item["provisioningState"], + vmExtension: !item["vmExtension"] + ? item["vmExtension"] + : vMExtensionDeserializer(item["vmExtension"]), + instanceView: !item["instanceView"] + ? item["instanceView"] + : vMExtensionInstanceViewDeserializer(item["instanceView"]), + }; +} + /** The configuration for virtual machine extensions. */ export interface VMExtension { /** The name of the virtual machine extension. */ @@ -729,9 +1173,25 @@ export interface VMExtension { provisionAfterExtensions?: string[]; } -export function vMExtensionSerializer( - item: VMExtension, -): Record { +export function vMExtensionSerializer(item: VMExtension): any { + return { + name: item["name"], + publisher: item["publisher"], + type: item["type"], + typeHandlerVersion: item["typeHandlerVersion"], + autoUpgradeMinorVersion: item["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: item["enableAutomaticUpgrade"], + settings: item["settings"], + protectedSettings: item["protectedSettings"], + provisionAfterExtensions: !item["provisionAfterExtensions"] + ? item["provisionAfterExtensions"] + : item["provisionAfterExtensions"].map((p: any) => { + return p; + }), + }; +} + +export function vMExtensionDeserializer(item: any): VMExtension { return { name: item["name"], publisher: item["publisher"], @@ -739,13 +1199,13 @@ export function vMExtensionSerializer( typeHandlerVersion: item["typeHandlerVersion"], autoUpgradeMinorVersion: item["autoUpgradeMinorVersion"], enableAutomaticUpgrade: item["enableAutomaticUpgrade"], - settings: !item.settings - ? item.settings - : (serializeRecord(item.settings as any) as any), - protectedSettings: !item.protectedSettings - ? item.protectedSettings - : (serializeRecord(item.protectedSettings as any) as any), - provisionAfterExtensions: item["provisionAfterExtensions"], + settings: item["settings"], + protectedSettings: item["protectedSettings"], + provisionAfterExtensions: !item["provisionAfterExtensions"] + ? item["provisionAfterExtensions"] + : item["provisionAfterExtensions"].map((p: any) => { + return p; + }), }; } @@ -759,6 +1219,20 @@ export interface VMExtensionInstanceView { subStatuses?: InstanceViewStatus[]; } +export function vMExtensionInstanceViewDeserializer( + item: any, +): VMExtensionInstanceView { + return { + name: item["name"], + statuses: !item["statuses"] + ? item["statuses"] + : instanceViewStatusArrayDeserializer(item["statuses"]), + subStatuses: !item["subStatuses"] + ? item["subStatuses"] + : instanceViewStatusArrayDeserializer(item["subStatuses"]), + }; +} + /** The instance view status. */ export interface InstanceViewStatus { /** The status code. */ @@ -773,9 +1247,27 @@ export interface InstanceViewStatus { time?: string; } +export function instanceViewStatusDeserializer(item: any): InstanceViewStatus { + return { + code: item["code"], + displayStatus: item["displayStatus"], + level: item["level"], + message: item["message"], + time: item["time"], + }; +} + /** Level code. */ export type StatusLevelTypes = "Error" | "Info" | "Warning"; +export function instanceViewStatusArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return instanceViewStatusDeserializer(item); + }); +} + /** The result of listing the Compute Node extensions in a Node. */ export interface _NodeVMExtensionList { /** The list of Compute Node extensions. */ @@ -784,6 +1276,25 @@ export interface _NodeVMExtensionList { "odata.nextLink"?: string; } +export function _nodeVMExtensionListDeserializer( + item: any, +): _NodeVMExtensionList { + return { + value: !item["value"] + ? item["value"] + : nodeVMExtensionArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + +export function nodeVMExtensionArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return nodeVMExtensionDeserializer(item); + }); +} + /** * The result of listing the files on a Compute Node, or the files associated with * a Task on a Compute Node. @@ -795,6 +1306,17 @@ export interface _NodeFileListResult { "odata.nextLink"?: string; } +export function _nodeFileListResultDeserializer( + item: any, +): _NodeFileListResult { + return { + value: !item["value"] + ? item["value"] + : nodeFileArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + /** Information about a file or directory on a Compute Node. */ export interface NodeFile { /** The file path. */ @@ -807,6 +1329,17 @@ export interface NodeFile { properties?: FileProperties; } +export function nodeFileDeserializer(item: any): NodeFile { + return { + name: item["name"], + url: item["url"], + isDirectory: item["isDirectory"], + properties: !item["properties"] + ? item["properties"] + : filePropertiesDeserializer(item["properties"]), + }; +} + /** The properties of a file on a Compute Node. */ export interface FileProperties { /** The file creation time. The creation time is not returned for files on Linux Compute Nodes. */ @@ -821,6 +1354,24 @@ export interface FileProperties { fileMode?: string; } +export function filePropertiesDeserializer(item: any): FileProperties { + return { + creationTime: !item["creationTime"] + ? item["creationTime"] + : new Date(item["creationTime"]), + lastModified: new Date(item["lastModified"]), + contentLength: item["contentLength"], + contentType: item["contentType"], + fileMode: item["fileMode"], + }; +} + +export function nodeFileArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return nodeFileDeserializer(item); + }); +} + /** Options for creating an Azure Batch Task. */ export interface BatchTaskCreateOptions { /** A string that uniquely identifies the Task within the Job. The ID can contain any combination of alphanumeric characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and case-insensitive (that is, you may not have two IDs within a Job that differ only by case). */ @@ -859,54 +1410,52 @@ export interface BatchTaskCreateOptions { export function batchTaskCreateOptionsSerializer( item: BatchTaskCreateOptions, -): Record { +): any { return { id: item["id"], displayName: item["displayName"], - exitConditions: !item.exitConditions - ? item.exitConditions - : exitConditionsSerializer(item.exitConditions), + exitConditions: !item["exitConditions"] + ? item["exitConditions"] + : exitConditionsSerializer(item["exitConditions"]), commandLine: item["commandLine"], - containerSettings: !item.containerSettings - ? item.containerSettings - : taskContainerSettingsSerializer(item.containerSettings), - resourceFiles: - item["resourceFiles"] === undefined - ? item["resourceFiles"] - : item["resourceFiles"].map(resourceFileSerializer), - outputFiles: - item["outputFiles"] === undefined - ? item["outputFiles"] - : item["outputFiles"].map(outputFileSerializer), - environmentSettings: - item["environmentSettings"] === undefined - ? item["environmentSettings"] - : item["environmentSettings"].map(environmentSettingSerializer), - affinityInfo: !item.affinityInfo - ? item.affinityInfo - : affinityInformationSerializer(item.affinityInfo), - constraints: !item.constraints - ? item.constraints - : taskConstraintsSerializer(item.constraints), + containerSettings: !item["containerSettings"] + ? item["containerSettings"] + : taskContainerSettingsSerializer(item["containerSettings"]), + resourceFiles: !item["resourceFiles"] + ? item["resourceFiles"] + : resourceFileArraySerializer(item["resourceFiles"]), + outputFiles: !item["outputFiles"] + ? item["outputFiles"] + : outputFileArraySerializer(item["outputFiles"]), + environmentSettings: !item["environmentSettings"] + ? item["environmentSettings"] + : environmentSettingArraySerializer(item["environmentSettings"]), + affinityInfo: !item["affinityInfo"] + ? item["affinityInfo"] + : affinityInformationSerializer(item["affinityInfo"]), + constraints: !item["constraints"] + ? item["constraints"] + : taskConstraintsSerializer(item["constraints"]), requiredSlots: item["requiredSlots"], - userIdentity: !item.userIdentity - ? item.userIdentity - : userIdentitySerializer(item.userIdentity), - multiInstanceSettings: !item.multiInstanceSettings - ? item.multiInstanceSettings - : multiInstanceSettingsSerializer(item.multiInstanceSettings), - dependsOn: !item.dependsOn - ? item.dependsOn - : taskDependenciesSerializer(item.dependsOn), - applicationPackageReferences: - item["applicationPackageReferences"] === undefined - ? item["applicationPackageReferences"] - : item["applicationPackageReferences"].map( - applicationPackageReferenceSerializer, - ), - authenticationTokenSettings: !item.authenticationTokenSettings - ? item.authenticationTokenSettings - : authenticationTokenSettingsSerializer(item.authenticationTokenSettings), + userIdentity: !item["userIdentity"] + ? item["userIdentity"] + : userIdentitySerializer(item["userIdentity"]), + multiInstanceSettings: !item["multiInstanceSettings"] + ? item["multiInstanceSettings"] + : multiInstanceSettingsSerializer(item["multiInstanceSettings"]), + dependsOn: !item["dependsOn"] + ? item["dependsOn"] + : taskDependenciesSerializer(item["dependsOn"]), + applicationPackageReferences: !item["applicationPackageReferences"] + ? item["applicationPackageReferences"] + : applicationPackageReferenceArraySerializer( + item["applicationPackageReferences"], + ), + authenticationTokenSettings: !item["authenticationTokenSettings"] + ? item["authenticationTokenSettings"] + : authenticationTokenSettingsSerializer( + item["authenticationTokenSettings"], + ), }; } @@ -924,25 +1473,43 @@ export interface ExitConditions { default?: ExitOptions; } -export function exitConditionsSerializer( - item: ExitConditions, -): Record { +export function exitConditionsSerializer(item: ExitConditions): any { + return { + exitCodes: !item["exitCodes"] + ? item["exitCodes"] + : exitCodeMappingArraySerializer(item["exitCodes"]), + exitCodeRanges: !item["exitCodeRanges"] + ? item["exitCodeRanges"] + : exitCodeRangeMappingArraySerializer(item["exitCodeRanges"]), + preProcessingError: !item["preProcessingError"] + ? item["preProcessingError"] + : exitOptionsSerializer(item["preProcessingError"]), + fileUploadError: !item["fileUploadError"] + ? item["fileUploadError"] + : exitOptionsSerializer(item["fileUploadError"]), + default: !item["default"] + ? item["default"] + : exitOptionsSerializer(item["default"]), + }; +} + +export function exitConditionsDeserializer(item: any): ExitConditions { return { - exitCodes: - item["exitCodes"] === undefined - ? item["exitCodes"] - : item["exitCodes"].map(exitCodeMappingSerializer), - exitCodeRanges: - item["exitCodeRanges"] === undefined - ? item["exitCodeRanges"] - : item["exitCodeRanges"].map(exitCodeRangeMappingSerializer), - preProcessingError: !item.preProcessingError - ? item.preProcessingError - : exitOptionsSerializer(item.preProcessingError), - fileUploadError: !item.fileUploadError - ? item.fileUploadError - : exitOptionsSerializer(item.fileUploadError), - default: !item.default ? item.default : exitOptionsSerializer(item.default), + exitCodes: !item["exitCodes"] + ? item["exitCodes"] + : exitCodeMappingArrayDeserializer(item["exitCodes"]), + exitCodeRanges: !item["exitCodeRanges"] + ? item["exitCodeRanges"] + : exitCodeRangeMappingArrayDeserializer(item["exitCodeRanges"]), + preProcessingError: !item["preProcessingError"] + ? item["preProcessingError"] + : exitOptionsDeserializer(item["preProcessingError"]), + fileUploadError: !item["fileUploadError"] + ? item["fileUploadError"] + : exitOptionsDeserializer(item["fileUploadError"]), + default: !item["default"] + ? item["default"] + : exitOptionsDeserializer(item["default"]), }; } @@ -957,12 +1524,17 @@ export interface ExitCodeMapping { exitOptions: ExitOptions; } -export function exitCodeMappingSerializer( - item: ExitCodeMapping, -): Record { +export function exitCodeMappingSerializer(item: ExitCodeMapping): any { return { code: item["code"], - exitOptions: exitOptionsSerializer(item.exitOptions), + exitOptions: exitOptionsSerializer(item["exitOptions"]), + }; +} + +export function exitCodeMappingDeserializer(item: any): ExitCodeMapping { + return { + code: item["code"], + exitOptions: exitOptionsDeserializer(item["exitOptions"]), }; } @@ -974,9 +1546,14 @@ export interface ExitOptions { dependencyAction?: DependencyAction; } -export function exitOptionsSerializer( - item: ExitOptions, -): Record { +export function exitOptionsSerializer(item: ExitOptions): any { + return { + jobAction: item["jobAction"], + dependencyAction: item["dependencyAction"], + }; +} + +export function exitOptionsDeserializer(item: any): ExitOptions { return { jobAction: item["jobAction"], dependencyAction: item["dependencyAction"], @@ -988,6 +1565,22 @@ export type JobAction = "none" | "disable" | "terminate"; /** DependencyAction enums */ export type DependencyAction = "satisfy" | "block"; +export function exitCodeMappingArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return exitCodeMappingSerializer(item); + }); +} + +export function exitCodeMappingArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return exitCodeMappingDeserializer(item); + }); +} + /** * A range of exit codes and how the Batch service should respond to exit codes * within that range. @@ -1003,14 +1596,40 @@ export interface ExitCodeRangeMapping { export function exitCodeRangeMappingSerializer( item: ExitCodeRangeMapping, -): Record { +): any { return { start: item["start"], end: item["end"], - exitOptions: exitOptionsSerializer(item.exitOptions), + exitOptions: exitOptionsSerializer(item["exitOptions"]), }; } +export function exitCodeRangeMappingDeserializer( + item: any, +): ExitCodeRangeMapping { + return { + start: item["start"], + end: item["end"], + exitOptions: exitOptionsDeserializer(item["exitOptions"]), + }; +} + +export function exitCodeRangeMappingArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return exitCodeRangeMappingSerializer(item); + }); +} + +export function exitCodeRangeMappingArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return exitCodeRangeMappingDeserializer(item); + }); +} + /** On every file uploads, Batch service writes two log files to the compute node, 'fileuploadout.txt' and 'fileuploaderr.txt'. These log files are used to learn more about a specific failure. */ export interface OutputFile { /** A pattern indicating which file(s) to upload. Both relative and absolute paths are supported. Relative paths are relative to the Task working directory. The following wildcards are supported: * matches 0 or more characters (for example pattern abc* would match abc or abcdef), ** matches any directory, ? matches any single character, [abc] matches one character in the brackets, and [a-c] matches one character in the range. */ @@ -1021,13 +1640,19 @@ export interface OutputFile { uploadOptions: OutputFileUploadOptions; } -export function outputFileSerializer( - item: OutputFile, -): Record { +export function outputFileSerializer(item: OutputFile): any { + return { + filePattern: item["filePattern"], + destination: outputFileDestinationSerializer(item["destination"]), + uploadOptions: outputFileUploadOptionsSerializer(item["uploadOptions"]), + }; +} + +export function outputFileDeserializer(item: any): OutputFile { return { filePattern: item["filePattern"], - destination: outputFileDestinationSerializer(item.destination), - uploadOptions: outputFileUploadOptionsSerializer(item.uploadOptions), + destination: outputFileDestinationDeserializer(item["destination"]), + uploadOptions: outputFileUploadOptionsDeserializer(item["uploadOptions"]), }; } @@ -1039,11 +1664,21 @@ export interface OutputFileDestination { export function outputFileDestinationSerializer( item: OutputFileDestination, -): Record { +): any { + return { + container: !item["container"] + ? item["container"] + : outputFileBlobContainerDestinationSerializer(item["container"]), + }; +} + +export function outputFileDestinationDeserializer( + item: any, +): OutputFileDestination { return { - container: !item.container - ? item.container - : outputFileBlobContainerDestinationSerializer(item.container), + container: !item["container"] + ? item["container"] + : outputFileBlobContainerDestinationDeserializer(item["container"]), }; } @@ -1061,17 +1696,31 @@ export interface OutputFileBlobContainerDestination { export function outputFileBlobContainerDestinationSerializer( item: OutputFileBlobContainerDestination, -): Record { +): any { return { path: item["path"], containerUrl: item["containerUrl"], - identityReference: !item.identityReference - ? item.identityReference - : batchNodeIdentityReferenceSerializer(item.identityReference), - uploadHeaders: - item["uploadHeaders"] === undefined - ? item["uploadHeaders"] - : item["uploadHeaders"].map(httpHeaderSerializer), + identityReference: !item["identityReference"] + ? item["identityReference"] + : batchNodeIdentityReferenceSerializer(item["identityReference"]), + uploadHeaders: !item["uploadHeaders"] + ? item["uploadHeaders"] + : httpHeaderArraySerializer(item["uploadHeaders"]), + }; +} + +export function outputFileBlobContainerDestinationDeserializer( + item: any, +): OutputFileBlobContainerDestination { + return { + path: item["path"], + containerUrl: item["containerUrl"], + identityReference: !item["identityReference"] + ? item["identityReference"] + : batchNodeIdentityReferenceDeserializer(item["identityReference"]), + uploadHeaders: !item["uploadHeaders"] + ? item["uploadHeaders"] + : httpHeaderArrayDeserializer(item["uploadHeaders"]), }; } @@ -1083,15 +1732,29 @@ export interface HttpHeader { value?: string; } -export function httpHeaderSerializer( - item: HttpHeader, -): Record { +export function httpHeaderSerializer(item: HttpHeader): any { + return { name: item["name"], value: item["value"] }; +} + +export function httpHeaderDeserializer(item: any): HttpHeader { return { name: item["name"], value: item["value"], }; } +export function httpHeaderArraySerializer(result: Array): any[] { + return result.map((item) => { + return httpHeaderSerializer(item); + }); +} + +export function httpHeaderArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return httpHeaderDeserializer(item); + }); +} + /** * Options for an output file upload operation, including under what conditions * to perform the upload. @@ -1103,7 +1766,13 @@ export interface OutputFileUploadOptions { export function outputFileUploadOptionsSerializer( item: OutputFileUploadOptions, -): Record { +): any { + return { uploadCondition: item["uploadCondition"] }; +} + +export function outputFileUploadOptionsDeserializer( + item: any, +): OutputFileUploadOptions { return { uploadCondition: item["uploadCondition"], }; @@ -1115,6 +1784,18 @@ export type OutputFileUploadCondition = | "taskfailure" | "taskcompletion"; +export function outputFileArraySerializer(result: Array): any[] { + return result.map((item) => { + return outputFileSerializer(item); + }); +} + +export function outputFileArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return outputFileDeserializer(item); + }); +} + /** * A locality hint that can be used by the Batch service to select a Compute Node * on which to start a Task. @@ -1124,9 +1805,13 @@ export interface AffinityInformation { affinityId: string; } -export function affinityInformationSerializer( - item: AffinityInformation, -): Record { +export function affinityInformationSerializer(item: AffinityInformation): any { + return { affinityId: item["affinityId"] }; +} + +export function affinityInformationDeserializer( + item: any, +): AffinityInformation { return { affinityId: item["affinityId"], }; @@ -1142,9 +1827,15 @@ export interface TaskConstraints { maxTaskRetryCount?: number; } -export function taskConstraintsSerializer( - item: TaskConstraints, -): Record { +export function taskConstraintsSerializer(item: TaskConstraints): any { + return { + maxWallClockTime: item["maxWallClockTime"], + retentionTime: item["retentionTime"], + maxTaskRetryCount: item["maxTaskRetryCount"], + }; +} + +export function taskConstraintsDeserializer(item: any): TaskConstraints { return { maxWallClockTime: item["maxWallClockTime"], retentionTime: item["retentionTime"], @@ -1169,14 +1860,25 @@ export interface MultiInstanceSettings { export function multiInstanceSettingsSerializer( item: MultiInstanceSettings, -): Record { +): any { return { numberOfInstances: item["numberOfInstances"], coordinationCommandLine: item["coordinationCommandLine"], - commonResourceFiles: - item["commonResourceFiles"] === undefined - ? item["commonResourceFiles"] - : item["commonResourceFiles"].map(resourceFileSerializer), + commonResourceFiles: !item["commonResourceFiles"] + ? item["commonResourceFiles"] + : resourceFileArraySerializer(item["commonResourceFiles"]), + }; +} + +export function multiInstanceSettingsDeserializer( + item: any, +): MultiInstanceSettings { + return { + numberOfInstances: item["numberOfInstances"], + coordinationCommandLine: item["coordinationCommandLine"], + commonResourceFiles: !item["commonResourceFiles"] + ? item["commonResourceFiles"] + : resourceFileArrayDeserializer(item["commonResourceFiles"]), }; } @@ -1192,15 +1894,29 @@ export interface TaskDependencies { taskIdRanges?: TaskIdRange[]; } -export function taskDependenciesSerializer( - item: TaskDependencies, -): Record { +export function taskDependenciesSerializer(item: TaskDependencies): any { return { - taskIds: item["taskIds"], - taskIdRanges: - item["taskIdRanges"] === undefined - ? item["taskIdRanges"] - : item["taskIdRanges"].map(taskIdRangeSerializer), + taskIds: !item["taskIds"] + ? item["taskIds"] + : item["taskIds"].map((p: any) => { + return p; + }), + taskIdRanges: !item["taskIdRanges"] + ? item["taskIdRanges"] + : taskIdRangeArraySerializer(item["taskIdRanges"]), + }; +} + +export function taskDependenciesDeserializer(item: any): TaskDependencies { + return { + taskIds: !item["taskIds"] + ? item["taskIds"] + : item["taskIds"].map((p: any) => { + return p; + }), + taskIdRanges: !item["taskIdRanges"] + ? item["taskIdRanges"] + : taskIdRangeArrayDeserializer(item["taskIdRanges"]), }; } @@ -1215,15 +1931,31 @@ export interface TaskIdRange { end: number; } -export function taskIdRangeSerializer( - item: TaskIdRange, -): Record { +export function taskIdRangeSerializer(item: TaskIdRange): any { + return { start: item["start"], end: item["end"] }; +} + +export function taskIdRangeDeserializer(item: any): TaskIdRange { return { start: item["start"], end: item["end"], }; } +export function taskIdRangeArraySerializer(result: Array): any[] { + return result.map((item) => { + return taskIdRangeSerializer(item); + }); +} + +export function taskIdRangeArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return taskIdRangeDeserializer(item); + }); +} + /** A reference to an Package to be deployed to Compute Nodes. */ export interface ApplicationPackageReference { /** The ID of the application to deploy. When creating a pool, the package's application ID must be fully qualified (/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}). */ @@ -1234,13 +1966,35 @@ export interface ApplicationPackageReference { export function applicationPackageReferenceSerializer( item: ApplicationPackageReference, -): Record { +): any { + return { applicationId: item["applicationId"], version: item["version"] }; +} + +export function applicationPackageReferenceDeserializer( + item: any, +): ApplicationPackageReference { return { applicationId: item["applicationId"], version: item["version"], }; } +export function applicationPackageReferenceArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return applicationPackageReferenceSerializer(item); + }); +} + +export function applicationPackageReferenceArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return applicationPackageReferenceDeserializer(item); + }); +} + /** * The settings for an authentication token that the Task can use to perform Batch * service operations. @@ -1252,9 +2006,25 @@ export interface AuthenticationTokenSettings { export function authenticationTokenSettingsSerializer( item: AuthenticationTokenSettings, -): Record { +): any { return { - access: item["access"], + access: !item["access"] + ? item["access"] + : item["access"].map((p: any) => { + return p; + }), + }; +} + +export function authenticationTokenSettingsDeserializer( + item: any, +): AuthenticationTokenSettings { + return { + access: !item["access"] + ? item["access"] + : item["access"].map((p: any) => { + return p; + }), }; } @@ -1269,6 +2039,17 @@ export interface _BatchTaskListResult { "odata.nextLink"?: string; } +export function _batchTaskListResultDeserializer( + item: any, +): _BatchTaskListResult { + return { + value: !item["value"] + ? item["value"] + : batchTaskArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + /** * Batch will retry Tasks when a recovery operation is triggered on a Node. * Examples of recovery operations include (but are not limited to) when an @@ -1337,11 +2118,85 @@ export interface BatchTask { readonly authenticationTokenSettings?: AuthenticationTokenSettings; } -export function batchTaskSerializer(item: BatchTask): Record { +export function batchTaskSerializer(item: BatchTask): any { + return { + constraints: !item["constraints"] + ? item["constraints"] + : taskConstraintsSerializer(item["constraints"]), + }; +} + +export function batchTaskDeserializer(item: any): BatchTask { return { - constraints: !item.constraints - ? item.constraints - : taskConstraintsSerializer(item.constraints), + id: item["id"], + displayName: item["displayName"], + url: item["url"], + eTag: item["eTag"], + lastModified: !item["lastModified"] + ? item["lastModified"] + : new Date(item["lastModified"]), + creationTime: !item["creationTime"] + ? item["creationTime"] + : new Date(item["creationTime"]), + exitConditions: !item["exitConditions"] + ? item["exitConditions"] + : exitConditionsDeserializer(item["exitConditions"]), + state: item["state"], + stateTransitionTime: !item["stateTransitionTime"] + ? item["stateTransitionTime"] + : new Date(item["stateTransitionTime"]), + previousState: item["previousState"], + previousStateTransitionTime: !item["previousStateTransitionTime"] + ? item["previousStateTransitionTime"] + : new Date(item["previousStateTransitionTime"]), + commandLine: item["commandLine"], + containerSettings: !item["containerSettings"] + ? item["containerSettings"] + : taskContainerSettingsDeserializer(item["containerSettings"]), + resourceFiles: !item["resourceFiles"] + ? item["resourceFiles"] + : resourceFileArrayDeserializer(item["resourceFiles"]), + outputFiles: !item["outputFiles"] + ? item["outputFiles"] + : outputFileArrayDeserializer(item["outputFiles"]), + environmentSettings: !item["environmentSettings"] + ? item["environmentSettings"] + : environmentSettingArrayDeserializer(item["environmentSettings"]), + affinityInfo: !item["affinityInfo"] + ? item["affinityInfo"] + : affinityInformationDeserializer(item["affinityInfo"]), + constraints: !item["constraints"] + ? item["constraints"] + : taskConstraintsDeserializer(item["constraints"]), + requiredSlots: item["requiredSlots"], + userIdentity: !item["userIdentity"] + ? item["userIdentity"] + : userIdentityDeserializer(item["userIdentity"]), + executionInfo: !item["executionInfo"] + ? item["executionInfo"] + : taskExecutionInformationDeserializer(item["executionInfo"]), + nodeInfo: !item["nodeInfo"] + ? item["nodeInfo"] + : batchNodeInformationDeserializer(item["nodeInfo"]), + multiInstanceSettings: !item["multiInstanceSettings"] + ? item["multiInstanceSettings"] + : multiInstanceSettingsDeserializer(item["multiInstanceSettings"]), + stats: !item["stats"] + ? item["stats"] + : taskStatisticsDeserializer(item["stats"]), + dependsOn: !item["dependsOn"] + ? item["dependsOn"] + : taskDependenciesDeserializer(item["dependsOn"]), + applicationPackageReferences: !item["applicationPackageReferences"] + ? item["applicationPackageReferences"] + : applicationPackageReferenceArrayDeserializer( + item["applicationPackageReferences"], + ), + authenticationTokenSettings: !item["authenticationTokenSettings"] + ? item["authenticationTokenSettings"] + : authenticationTokenSettingsDeserializer( + item["authenticationTokenSettings"], + ), }; } @@ -1361,6 +2216,19 @@ export interface BatchNodeInformation { taskRootDirectoryUrl?: string; } +export function batchNodeInformationDeserializer( + item: any, +): BatchNodeInformation { + return { + affinityId: item["affinityId"], + nodeUrl: item["nodeUrl"], + poolId: item["poolId"], + nodeId: item["nodeId"], + taskRootDirectory: item["taskRootDirectory"], + taskRootDirectoryUrl: item["taskRootDirectoryUrl"], + }; +} + /** Resource usage statistics for a Task. */ export interface TaskStatistics { /** The URL of the statistics. */ @@ -1387,18 +2255,50 @@ export interface TaskStatistics { waitTime: string; } +export function taskStatisticsDeserializer(item: any): TaskStatistics { + return { + url: item["url"], + startTime: new Date(item["startTime"]), + lastUpdateTime: new Date(item["lastUpdateTime"]), + userCPUTime: item["userCPUTime"], + kernelCPUTime: item["kernelCPUTime"], + wallClockTime: item["wallClockTime"], + readIOps: item["readIOps"], + writeIOps: item["writeIOps"], + readIOGiB: item["readIOGiB"], + writeIOGiB: item["writeIOGiB"], + waitTime: item["waitTime"], + }; +} + +export function batchTaskArraySerializer(result: Array): any[] { + return result.map((item) => { + return batchTaskSerializer(item); + }); +} + +export function batchTaskArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return batchTaskDeserializer(item); + }); +} + /** A collection of Azure Batch Tasks to add. */ export interface BatchTaskCollection { /** The collection of Tasks to add. The maximum count of Tasks is 100. The total serialized size of this collection must be less than 1MB. If it is greater than 1MB (for example if each Task has 100's of resource files or environment variables), the request will fail with code 'RequestBodyTooLarge' and should be retried again with fewer Tasks. */ value: BatchTaskCreateOptions[]; } -export function batchTaskCollectionSerializer( - item: BatchTaskCollection, -): Record { - return { - value: item["value"].map(batchTaskCreateOptionsSerializer), - }; +export function batchTaskCollectionSerializer(item: BatchTaskCollection): any { + return { value: batchTaskCreateOptionsArraySerializer(item["value"]) }; +} + +export function batchTaskCreateOptionsArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return batchTaskCreateOptionsSerializer(item); + }); } /** The result of adding a collection of Tasks to a Job. */ @@ -1407,6 +2307,16 @@ export interface TaskAddCollectionResult { value?: TaskAddResult[]; } +export function taskAddCollectionResultDeserializer( + item: any, +): TaskAddCollectionResult { + return { + value: !item["value"] + ? item["value"] + : taskAddResultArrayDeserializer(item["value"]), + }; +} + /** Result for a single Task added as part of an add Task collection operation. */ export interface TaskAddResult { /** The status of the add Task request. */ @@ -1423,15 +2333,48 @@ export interface TaskAddResult { error?: BatchError; } +export function taskAddResultDeserializer(item: any): TaskAddResult { + return { + status: item["status"], + taskId: item["taskId"], + eTag: item["eTag"], + lastModified: !item["lastModified"] + ? item["lastModified"] + : new Date(item["lastModified"]), + location: item["location"], + error: !item["error"] + ? item["error"] + : batchErrorDeserializer(item["error"]), + }; +} + /** TaskAddStatus enums */ export type TaskAddStatus = "Success" | "clienterror" | "servererror"; +export function taskAddResultArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return taskAddResultDeserializer(item); + }); +} + /** The result of listing the subtasks of a Task. */ export interface BatchTaskListSubtasksResult { /** The list of subtasks. */ value?: SubtaskInformation[]; } +export function batchTaskListSubtasksResultDeserializer( + item: any, +): BatchTaskListSubtasksResult { + return { + value: !item["value"] + ? item["value"] + : subtaskInformationArrayDeserializer(item["value"]), + }; +} + /** Information about an Azure Batch subtask. */ export interface SubtaskInformation { /** The ID of the subtask. */ @@ -1460,9 +2403,46 @@ export interface SubtaskInformation { result?: TaskExecutionResult; } +export function subtaskInformationDeserializer(item: any): SubtaskInformation { + return { + id: item["id"], + nodeInfo: !item["nodeInfo"] + ? item["nodeInfo"] + : batchNodeInformationDeserializer(item["nodeInfo"]), + startTime: !item["startTime"] + ? item["startTime"] + : new Date(item["startTime"]), + endTime: !item["endTime"] ? item["endTime"] : new Date(item["endTime"]), + exitCode: item["exitCode"], + containerInfo: !item["containerInfo"] + ? item["containerInfo"] + : taskContainerExecutionInformationDeserializer(item["containerInfo"]), + failureInfo: !item["failureInfo"] + ? item["failureInfo"] + : taskFailureInformationDeserializer(item["failureInfo"]), + state: item["state"], + stateTransitionTime: !item["stateTransitionTime"] + ? item["stateTransitionTime"] + : new Date(item["stateTransitionTime"]), + previousState: item["previousState"], + previousStateTransitionTime: !item["previousStateTransitionTime"] + ? item["previousStateTransitionTime"] + : new Date(item["previousStateTransitionTime"]), + result: item["result"], + }; +} + /** SubtaskState enums */ export type SubtaskState = "preparing" | "running" | "completed"; +export function subtaskInformationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return subtaskInformationDeserializer(item); + }); +} + /** * A Job Schedule that allows recurring Jobs by specifying when to run Jobs and a * specification used to create each Job. @@ -1500,16 +2480,47 @@ export interface BatchJobSchedule { readonly stats?: JobScheduleStatistics; } -export function batchJobScheduleSerializer( - item: BatchJobSchedule, -): Record { +export function batchJobScheduleSerializer(item: BatchJobSchedule): any { + return { + schedule: scheduleSerializer(item["schedule"]), + jobSpecification: jobSpecificationSerializer(item["jobSpecification"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArraySerializer(item["metadata"]), + }; +} + +export function batchJobScheduleDeserializer(item: any): BatchJobSchedule { return { - schedule: scheduleSerializer(item.schedule), - jobSpecification: jobSpecificationSerializer(item.jobSpecification), - metadata: - item["metadata"] === undefined - ? item["metadata"] - : item["metadata"].map(metadataItemSerializer), + id: item["id"], + displayName: item["displayName"], + url: item["url"], + eTag: item["eTag"], + lastModified: !item["lastModified"] + ? item["lastModified"] + : new Date(item["lastModified"]), + creationTime: !item["creationTime"] + ? item["creationTime"] + : new Date(item["creationTime"]), + state: item["state"], + stateTransitionTime: !item["stateTransitionTime"] + ? item["stateTransitionTime"] + : new Date(item["stateTransitionTime"]), + previousState: item["previousState"], + previousStateTransitionTime: !item["previousStateTransitionTime"] + ? item["previousStateTransitionTime"] + : new Date(item["previousStateTransitionTime"]), + schedule: scheduleDeserializer(item["schedule"]), + jobSpecification: jobSpecificationDeserializer(item["jobSpecification"]), + executionInfo: !item["executionInfo"] + ? item["executionInfo"] + : jobScheduleExecutionInformationDeserializer(item["executionInfo"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArrayDeserializer(item["metadata"]), + stats: !item["stats"] + ? item["stats"] + : jobScheduleStatisticsDeserializer(item["stats"]), }; } @@ -1536,7 +2547,7 @@ export interface Schedule { recurrenceInterval?: string; } -export function scheduleSerializer(item: Schedule): Record { +export function scheduleSerializer(item: Schedule): any { return { doNotRunUntil: item["doNotRunUntil"]?.toISOString(), doNotRunAfter: item["doNotRunAfter"]?.toISOString(), @@ -1545,6 +2556,19 @@ export function scheduleSerializer(item: Schedule): Record { }; } +export function scheduleDeserializer(item: any): Schedule { + return { + doNotRunUntil: !item["doNotRunUntil"] + ? item["doNotRunUntil"] + : new Date(item["doNotRunUntil"]), + doNotRunAfter: !item["doNotRunAfter"] + ? item["doNotRunAfter"] + : new Date(item["doNotRunAfter"]), + startWindow: item["startWindow"], + recurrenceInterval: item["recurrenceInterval"], + }; +} + /** Specifies details of the Jobs to be created on a schedule. */ export interface JobSpecification { /** The priority of Jobs created under this schedule. Priority values can range from -1000 to 1000, with -1000 being the lowest priority and 1000 being the highest priority. The default value is 0. This priority is used as the default for all Jobs under the Job Schedule. You can update a Job's priority after it has been created using by using the update Job API. */ @@ -1579,9 +2603,41 @@ export interface JobSpecification { metadata?: MetadataItem[]; } -export function jobSpecificationSerializer( - item: JobSpecification, -): Record { +export function jobSpecificationSerializer(item: JobSpecification): any { + return { + priority: item["priority"], + allowTaskPreemption: item["allowTaskPreemption"], + maxParallelTasks: item["maxParallelTasks"], + displayName: item["displayName"], + usesTaskDependencies: item["usesTaskDependencies"], + onAllTasksComplete: item["onAllTasksComplete"], + onTaskFailure: item["onTaskFailure"], + networkConfiguration: !item["networkConfiguration"] + ? item["networkConfiguration"] + : jobNetworkConfigurationSerializer(item["networkConfiguration"]), + constraints: !item["constraints"] + ? item["constraints"] + : jobConstraintsSerializer(item["constraints"]), + jobManagerTask: !item["jobManagerTask"] + ? item["jobManagerTask"] + : jobManagerTaskSerializer(item["jobManagerTask"]), + jobPreparationTask: !item["jobPreparationTask"] + ? item["jobPreparationTask"] + : jobPreparationTaskSerializer(item["jobPreparationTask"]), + jobReleaseTask: !item["jobReleaseTask"] + ? item["jobReleaseTask"] + : jobReleaseTaskSerializer(item["jobReleaseTask"]), + commonEnvironmentSettings: !item["commonEnvironmentSettings"] + ? item["commonEnvironmentSettings"] + : environmentSettingArraySerializer(item["commonEnvironmentSettings"]), + poolInfo: poolInformationSerializer(item["poolInfo"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArraySerializer(item["metadata"]), + }; +} + +export function jobSpecificationDeserializer(item: any): JobSpecification { return { priority: item["priority"], allowTaskPreemption: item["allowTaskPreemption"], @@ -1590,30 +2646,28 @@ export function jobSpecificationSerializer( usesTaskDependencies: item["usesTaskDependencies"], onAllTasksComplete: item["onAllTasksComplete"], onTaskFailure: item["onTaskFailure"], - networkConfiguration: !item.networkConfiguration - ? item.networkConfiguration - : jobNetworkConfigurationSerializer(item.networkConfiguration), - constraints: !item.constraints - ? item.constraints - : jobConstraintsSerializer(item.constraints), - jobManagerTask: !item.jobManagerTask - ? item.jobManagerTask - : jobManagerTaskSerializer(item.jobManagerTask), - jobPreparationTask: !item.jobPreparationTask - ? item.jobPreparationTask - : jobPreparationTaskSerializer(item.jobPreparationTask), - jobReleaseTask: !item.jobReleaseTask - ? item.jobReleaseTask - : jobReleaseTaskSerializer(item.jobReleaseTask), - commonEnvironmentSettings: - item["commonEnvironmentSettings"] === undefined - ? item["commonEnvironmentSettings"] - : item["commonEnvironmentSettings"].map(environmentSettingSerializer), - poolInfo: poolInformationSerializer(item.poolInfo), - metadata: - item["metadata"] === undefined - ? item["metadata"] - : item["metadata"].map(metadataItemSerializer), + networkConfiguration: !item["networkConfiguration"] + ? item["networkConfiguration"] + : jobNetworkConfigurationDeserializer(item["networkConfiguration"]), + constraints: !item["constraints"] + ? item["constraints"] + : jobConstraintsDeserializer(item["constraints"]), + jobManagerTask: !item["jobManagerTask"] + ? item["jobManagerTask"] + : jobManagerTaskDeserializer(item["jobManagerTask"]), + jobPreparationTask: !item["jobPreparationTask"] + ? item["jobPreparationTask"] + : jobPreparationTaskDeserializer(item["jobPreparationTask"]), + jobReleaseTask: !item["jobReleaseTask"] + ? item["jobReleaseTask"] + : jobReleaseTaskDeserializer(item["jobReleaseTask"]), + commonEnvironmentSettings: !item["commonEnvironmentSettings"] + ? item["commonEnvironmentSettings"] + : environmentSettingArrayDeserializer(item["commonEnvironmentSettings"]), + poolInfo: poolInformationDeserializer(item["poolInfo"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArrayDeserializer(item["metadata"]), }; } @@ -1630,7 +2684,13 @@ export interface JobNetworkConfiguration { export function jobNetworkConfigurationSerializer( item: JobNetworkConfiguration, -): Record { +): any { + return { subnetId: item["subnetId"] }; +} + +export function jobNetworkConfigurationDeserializer( + item: any, +): JobNetworkConfiguration { return { subnetId: item["subnetId"], }; @@ -1644,9 +2704,14 @@ export interface JobConstraints { maxTaskRetryCount?: number; } -export function jobConstraintsSerializer( - item: JobConstraints, -): Record { +export function jobConstraintsSerializer(item: JobConstraints): any { + return { + maxWallClockTime: item["maxWallClockTime"], + maxTaskRetryCount: item["maxTaskRetryCount"], + }; +} + +export function jobConstraintsDeserializer(item: any): JobConstraints { return { maxWallClockTime: item["maxWallClockTime"], maxTaskRetryCount: item["maxTaskRetryCount"], @@ -1720,46 +2785,82 @@ export interface JobManagerTask { allowLowPriorityNode?: boolean; } -export function jobManagerTaskSerializer( - item: JobManagerTask, -): Record { +export function jobManagerTaskSerializer(item: JobManagerTask): any { + return { + id: item["id"], + displayName: item["displayName"], + commandLine: item["commandLine"], + containerSettings: !item["containerSettings"] + ? item["containerSettings"] + : taskContainerSettingsSerializer(item["containerSettings"]), + resourceFiles: !item["resourceFiles"] + ? item["resourceFiles"] + : resourceFileArraySerializer(item["resourceFiles"]), + outputFiles: !item["outputFiles"] + ? item["outputFiles"] + : outputFileArraySerializer(item["outputFiles"]), + environmentSettings: !item["environmentSettings"] + ? item["environmentSettings"] + : environmentSettingArraySerializer(item["environmentSettings"]), + constraints: !item["constraints"] + ? item["constraints"] + : taskConstraintsSerializer(item["constraints"]), + requiredSlots: item["requiredSlots"], + killJobOnCompletion: item["killJobOnCompletion"], + userIdentity: !item["userIdentity"] + ? item["userIdentity"] + : userIdentitySerializer(item["userIdentity"]), + runExclusive: item["runExclusive"], + applicationPackageReferences: !item["applicationPackageReferences"] + ? item["applicationPackageReferences"] + : applicationPackageReferenceArraySerializer( + item["applicationPackageReferences"], + ), + authenticationTokenSettings: !item["authenticationTokenSettings"] + ? item["authenticationTokenSettings"] + : authenticationTokenSettingsSerializer( + item["authenticationTokenSettings"], + ), + allowLowPriorityNode: item["allowLowPriorityNode"], + }; +} + +export function jobManagerTaskDeserializer(item: any): JobManagerTask { return { id: item["id"], displayName: item["displayName"], commandLine: item["commandLine"], - containerSettings: !item.containerSettings - ? item.containerSettings - : taskContainerSettingsSerializer(item.containerSettings), - resourceFiles: - item["resourceFiles"] === undefined - ? item["resourceFiles"] - : item["resourceFiles"].map(resourceFileSerializer), - outputFiles: - item["outputFiles"] === undefined - ? item["outputFiles"] - : item["outputFiles"].map(outputFileSerializer), - environmentSettings: - item["environmentSettings"] === undefined - ? item["environmentSettings"] - : item["environmentSettings"].map(environmentSettingSerializer), - constraints: !item.constraints - ? item.constraints - : taskConstraintsSerializer(item.constraints), + containerSettings: !item["containerSettings"] + ? item["containerSettings"] + : taskContainerSettingsDeserializer(item["containerSettings"]), + resourceFiles: !item["resourceFiles"] + ? item["resourceFiles"] + : resourceFileArrayDeserializer(item["resourceFiles"]), + outputFiles: !item["outputFiles"] + ? item["outputFiles"] + : outputFileArrayDeserializer(item["outputFiles"]), + environmentSettings: !item["environmentSettings"] + ? item["environmentSettings"] + : environmentSettingArrayDeserializer(item["environmentSettings"]), + constraints: !item["constraints"] + ? item["constraints"] + : taskConstraintsDeserializer(item["constraints"]), requiredSlots: item["requiredSlots"], killJobOnCompletion: item["killJobOnCompletion"], - userIdentity: !item.userIdentity - ? item.userIdentity - : userIdentitySerializer(item.userIdentity), + userIdentity: !item["userIdentity"] + ? item["userIdentity"] + : userIdentityDeserializer(item["userIdentity"]), runExclusive: item["runExclusive"], - applicationPackageReferences: - item["applicationPackageReferences"] === undefined - ? item["applicationPackageReferences"] - : item["applicationPackageReferences"].map( - applicationPackageReferenceSerializer, - ), - authenticationTokenSettings: !item.authenticationTokenSettings - ? item.authenticationTokenSettings - : authenticationTokenSettingsSerializer(item.authenticationTokenSettings), + applicationPackageReferences: !item["applicationPackageReferences"] + ? item["applicationPackageReferences"] + : applicationPackageReferenceArrayDeserializer( + item["applicationPackageReferences"], + ), + authenticationTokenSettings: !item["authenticationTokenSettings"] + ? item["authenticationTokenSettings"] + : authenticationTokenSettingsDeserializer( + item["authenticationTokenSettings"], + ), allowLowPriorityNode: item["allowLowPriorityNode"], }; } @@ -1813,30 +2914,50 @@ export interface JobPreparationTask { rerunOnNodeRebootAfterSuccess?: boolean; } -export function jobPreparationTaskSerializer( - item: JobPreparationTask, -): Record { +export function jobPreparationTaskSerializer(item: JobPreparationTask): any { + return { + id: item["id"], + commandLine: item["commandLine"], + containerSettings: !item["containerSettings"] + ? item["containerSettings"] + : taskContainerSettingsSerializer(item["containerSettings"]), + resourceFiles: !item["resourceFiles"] + ? item["resourceFiles"] + : resourceFileArraySerializer(item["resourceFiles"]), + environmentSettings: !item["environmentSettings"] + ? item["environmentSettings"] + : environmentSettingArraySerializer(item["environmentSettings"]), + constraints: !item["constraints"] + ? item["constraints"] + : taskConstraintsSerializer(item["constraints"]), + waitForSuccess: item["waitForSuccess"], + userIdentity: !item["userIdentity"] + ? item["userIdentity"] + : userIdentitySerializer(item["userIdentity"]), + rerunOnNodeRebootAfterSuccess: item["rerunOnNodeRebootAfterSuccess"], + }; +} + +export function jobPreparationTaskDeserializer(item: any): JobPreparationTask { return { id: item["id"], commandLine: item["commandLine"], - containerSettings: !item.containerSettings - ? item.containerSettings - : taskContainerSettingsSerializer(item.containerSettings), - resourceFiles: - item["resourceFiles"] === undefined - ? item["resourceFiles"] - : item["resourceFiles"].map(resourceFileSerializer), - environmentSettings: - item["environmentSettings"] === undefined - ? item["environmentSettings"] - : item["environmentSettings"].map(environmentSettingSerializer), - constraints: !item.constraints - ? item.constraints - : taskConstraintsSerializer(item.constraints), + containerSettings: !item["containerSettings"] + ? item["containerSettings"] + : taskContainerSettingsDeserializer(item["containerSettings"]), + resourceFiles: !item["resourceFiles"] + ? item["resourceFiles"] + : resourceFileArrayDeserializer(item["resourceFiles"]), + environmentSettings: !item["environmentSettings"] + ? item["environmentSettings"] + : environmentSettingArrayDeserializer(item["environmentSettings"]), + constraints: !item["constraints"] + ? item["constraints"] + : taskConstraintsDeserializer(item["constraints"]), waitForSuccess: item["waitForSuccess"], - userIdentity: !item.userIdentity - ? item.userIdentity - : userIdentitySerializer(item.userIdentity), + userIdentity: !item["userIdentity"] + ? item["userIdentity"] + : userIdentityDeserializer(item["userIdentity"]), rerunOnNodeRebootAfterSuccess: item["rerunOnNodeRebootAfterSuccess"], }; } @@ -1878,28 +2999,45 @@ export interface JobReleaseTask { userIdentity?: UserIdentity; } -export function jobReleaseTaskSerializer( - item: JobReleaseTask, -): Record { +export function jobReleaseTaskSerializer(item: JobReleaseTask): any { + return { + id: item["id"], + commandLine: item["commandLine"], + containerSettings: !item["containerSettings"] + ? item["containerSettings"] + : taskContainerSettingsSerializer(item["containerSettings"]), + resourceFiles: !item["resourceFiles"] + ? item["resourceFiles"] + : resourceFileArraySerializer(item["resourceFiles"]), + environmentSettings: !item["environmentSettings"] + ? item["environmentSettings"] + : environmentSettingArraySerializer(item["environmentSettings"]), + maxWallClockTime: item["maxWallClockTime"], + retentionTime: item["retentionTime"], + userIdentity: !item["userIdentity"] + ? item["userIdentity"] + : userIdentitySerializer(item["userIdentity"]), + }; +} + +export function jobReleaseTaskDeserializer(item: any): JobReleaseTask { return { id: item["id"], commandLine: item["commandLine"], - containerSettings: !item.containerSettings - ? item.containerSettings - : taskContainerSettingsSerializer(item.containerSettings), - resourceFiles: - item["resourceFiles"] === undefined - ? item["resourceFiles"] - : item["resourceFiles"].map(resourceFileSerializer), - environmentSettings: - item["environmentSettings"] === undefined - ? item["environmentSettings"] - : item["environmentSettings"].map(environmentSettingSerializer), + containerSettings: !item["containerSettings"] + ? item["containerSettings"] + : taskContainerSettingsDeserializer(item["containerSettings"]), + resourceFiles: !item["resourceFiles"] + ? item["resourceFiles"] + : resourceFileArrayDeserializer(item["resourceFiles"]), + environmentSettings: !item["environmentSettings"] + ? item["environmentSettings"] + : environmentSettingArrayDeserializer(item["environmentSettings"]), maxWallClockTime: item["maxWallClockTime"], retentionTime: item["retentionTime"], - userIdentity: !item.userIdentity - ? item.userIdentity - : userIdentitySerializer(item.userIdentity), + userIdentity: !item["userIdentity"] + ? item["userIdentity"] + : userIdentityDeserializer(item["userIdentity"]), }; } @@ -1911,14 +3049,21 @@ export interface PoolInformation { autoPoolSpecification?: AutoPoolSpecification; } -export function poolInformationSerializer( - item: PoolInformation, -): Record { +export function poolInformationSerializer(item: PoolInformation): any { + return { + poolId: item["poolId"], + autoPoolSpecification: !item["autoPoolSpecification"] + ? item["autoPoolSpecification"] + : autoPoolSpecificationSerializer(item["autoPoolSpecification"]), + }; +} + +export function poolInformationDeserializer(item: any): PoolInformation { return { poolId: item["poolId"], - autoPoolSpecification: !item.autoPoolSpecification - ? item.autoPoolSpecification - : autoPoolSpecificationSerializer(item.autoPoolSpecification), + autoPoolSpecification: !item["autoPoolSpecification"] + ? item["autoPoolSpecification"] + : autoPoolSpecificationDeserializer(item["autoPoolSpecification"]), }; } @@ -1939,12 +3084,27 @@ export interface AutoPoolSpecification { export function autoPoolSpecificationSerializer( item: AutoPoolSpecification, -): Record { +): any { return { autoPoolIdPrefix: item["autoPoolIdPrefix"], poolLifetimeOption: item["poolLifetimeOption"], keepAlive: item["keepAlive"], - pool: !item.pool ? item.pool : poolSpecificationSerializer(item.pool), + pool: !item["pool"] + ? item["pool"] + : poolSpecificationSerializer(item["pool"]), + }; +} + +export function autoPoolSpecificationDeserializer( + item: any, +): AutoPoolSpecification { + return { + autoPoolIdPrefix: item["autoPoolIdPrefix"], + poolLifetimeOption: item["poolLifetimeOption"], + keepAlive: item["keepAlive"], + pool: !item["pool"] + ? item["pool"] + : poolSpecificationDeserializer(item["pool"]), }; } @@ -2003,22 +3163,79 @@ export interface PoolSpecification { targetNodeCommunicationMode?: NodeCommunicationMode; } -export function poolSpecificationSerializer( - item: PoolSpecification, -): Record { +export function poolSpecificationSerializer(item: PoolSpecification): any { + return { + displayName: item["displayName"], + vmSize: item["vmSize"], + cloudServiceConfiguration: !item["cloudServiceConfiguration"] + ? item["cloudServiceConfiguration"] + : cloudServiceConfigurationSerializer(item["cloudServiceConfiguration"]), + virtualMachineConfiguration: !item["virtualMachineConfiguration"] + ? item["virtualMachineConfiguration"] + : virtualMachineConfigurationSerializer( + item["virtualMachineConfiguration"], + ), + taskSlotsPerNode: item["taskSlotsPerNode"], + taskSchedulingPolicy: !item["taskSchedulingPolicy"] + ? item["taskSchedulingPolicy"] + : taskSchedulingPolicySerializer(item["taskSchedulingPolicy"]), + resizeTimeout: item["resizeTimeout"], + targetDedicatedNodes: item["targetDedicatedNodes"], + targetLowPriorityNodes: item["targetLowPriorityNodes"], + enableAutoScale: item["enableAutoScale"], + autoScaleFormula: item["autoScaleFormula"], + autoScaleEvaluationInterval: item["autoScaleEvaluationInterval"], + enableInterNodeCommunication: item["enableInterNodeCommunication"], + networkConfiguration: !item["networkConfiguration"] + ? item["networkConfiguration"] + : networkConfigurationSerializer(item["networkConfiguration"]), + startTask: !item["startTask"] + ? item["startTask"] + : startTaskSerializer(item["startTask"]), + certificateReferences: !item["certificateReferences"] + ? item["certificateReferences"] + : certificateReferenceArraySerializer(item["certificateReferences"]), + applicationPackageReferences: !item["applicationPackageReferences"] + ? item["applicationPackageReferences"] + : applicationPackageReferenceArraySerializer( + item["applicationPackageReferences"], + ), + applicationLicenses: !item["applicationLicenses"] + ? item["applicationLicenses"] + : item["applicationLicenses"].map((p: any) => { + return p; + }), + userAccounts: !item["userAccounts"] + ? item["userAccounts"] + : userAccountArraySerializer(item["userAccounts"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArraySerializer(item["metadata"]), + mountConfiguration: !item["mountConfiguration"] + ? item["mountConfiguration"] + : mountConfigurationArraySerializer(item["mountConfiguration"]), + targetNodeCommunicationMode: item["targetNodeCommunicationMode"], + }; +} + +export function poolSpecificationDeserializer(item: any): PoolSpecification { return { displayName: item["displayName"], vmSize: item["vmSize"], - cloudServiceConfiguration: !item.cloudServiceConfiguration - ? item.cloudServiceConfiguration - : cloudServiceConfigurationSerializer(item.cloudServiceConfiguration), - virtualMachineConfiguration: !item.virtualMachineConfiguration - ? item.virtualMachineConfiguration - : virtualMachineConfigurationSerializer(item.virtualMachineConfiguration), + cloudServiceConfiguration: !item["cloudServiceConfiguration"] + ? item["cloudServiceConfiguration"] + : cloudServiceConfigurationDeserializer( + item["cloudServiceConfiguration"], + ), + virtualMachineConfiguration: !item["virtualMachineConfiguration"] + ? item["virtualMachineConfiguration"] + : virtualMachineConfigurationDeserializer( + item["virtualMachineConfiguration"], + ), taskSlotsPerNode: item["taskSlotsPerNode"], - taskSchedulingPolicy: !item.taskSchedulingPolicy - ? item.taskSchedulingPolicy - : taskSchedulingPolicySerializer(item.taskSchedulingPolicy), + taskSchedulingPolicy: !item["taskSchedulingPolicy"] + ? item["taskSchedulingPolicy"] + : taskSchedulingPolicyDeserializer(item["taskSchedulingPolicy"]), resizeTimeout: item["resizeTimeout"], targetDedicatedNodes: item["targetDedicatedNodes"], targetLowPriorityNodes: item["targetLowPriorityNodes"], @@ -2026,35 +3243,34 @@ export function poolSpecificationSerializer( autoScaleFormula: item["autoScaleFormula"], autoScaleEvaluationInterval: item["autoScaleEvaluationInterval"], enableInterNodeCommunication: item["enableInterNodeCommunication"], - networkConfiguration: !item.networkConfiguration - ? item.networkConfiguration - : networkConfigurationSerializer(item.networkConfiguration), - startTask: !item.startTask - ? item.startTask - : startTaskSerializer(item.startTask), - certificateReferences: - item["certificateReferences"] === undefined - ? item["certificateReferences"] - : item["certificateReferences"].map(certificateReferenceSerializer), - applicationPackageReferences: - item["applicationPackageReferences"] === undefined - ? item["applicationPackageReferences"] - : item["applicationPackageReferences"].map( - applicationPackageReferenceSerializer, - ), - applicationLicenses: item["applicationLicenses"], - userAccounts: - item["userAccounts"] === undefined - ? item["userAccounts"] - : item["userAccounts"].map(userAccountSerializer), - metadata: - item["metadata"] === undefined - ? item["metadata"] - : item["metadata"].map(metadataItemSerializer), - mountConfiguration: - item["mountConfiguration"] === undefined - ? item["mountConfiguration"] - : item["mountConfiguration"].map(mountConfigurationSerializer), + networkConfiguration: !item["networkConfiguration"] + ? item["networkConfiguration"] + : networkConfigurationDeserializer(item["networkConfiguration"]), + startTask: !item["startTask"] + ? item["startTask"] + : startTaskDeserializer(item["startTask"]), + certificateReferences: !item["certificateReferences"] + ? item["certificateReferences"] + : certificateReferenceArrayDeserializer(item["certificateReferences"]), + applicationPackageReferences: !item["applicationPackageReferences"] + ? item["applicationPackageReferences"] + : applicationPackageReferenceArrayDeserializer( + item["applicationPackageReferences"], + ), + applicationLicenses: !item["applicationLicenses"] + ? item["applicationLicenses"] + : item["applicationLicenses"].map((p: any) => { + return p; + }), + userAccounts: !item["userAccounts"] + ? item["userAccounts"] + : userAccountArrayDeserializer(item["userAccounts"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArrayDeserializer(item["metadata"]), + mountConfiguration: !item["mountConfiguration"] + ? item["mountConfiguration"] + : mountConfigurationArrayDeserializer(item["mountConfiguration"]), targetNodeCommunicationMode: item["targetNodeCommunicationMode"], }; } @@ -2084,7 +3300,13 @@ export interface CloudServiceConfiguration { export function cloudServiceConfigurationSerializer( item: CloudServiceConfiguration, -): Record { +): any { + return { osFamily: item["osFamily"], osVersion: item["osVersion"] }; +} + +export function cloudServiceConfigurationDeserializer( + item: any, +): CloudServiceConfiguration { return { osFamily: item["osFamily"], osVersion: item["osVersion"], @@ -2130,32 +3352,69 @@ export interface VirtualMachineConfiguration { export function virtualMachineConfigurationSerializer( item: VirtualMachineConfiguration, -): Record { +): any { return { - imageReference: imageReferenceSerializer(item.imageReference), + imageReference: imageReferenceSerializer(item["imageReference"]), nodeAgentSKUId: item["nodeAgentSkuId"], - windowsConfiguration: !item.windowsConfiguration - ? item.windowsConfiguration - : windowsConfigurationSerializer(item.windowsConfiguration), - dataDisks: - item["dataDisks"] === undefined - ? item["dataDisks"] - : item["dataDisks"].map(dataDiskSerializer), + windowsConfiguration: !item["windowsConfiguration"] + ? item["windowsConfiguration"] + : windowsConfigurationSerializer(item["windowsConfiguration"]), + dataDisks: !item["dataDisks"] + ? item["dataDisks"] + : dataDiskArraySerializer(item["dataDisks"]), + licenseType: item["licenseType"], + containerConfiguration: !item["containerConfiguration"] + ? item["containerConfiguration"] + : containerConfigurationSerializer(item["containerConfiguration"]), + diskEncryptionConfiguration: !item["diskEncryptionConfiguration"] + ? item["diskEncryptionConfiguration"] + : diskEncryptionConfigurationSerializer( + item["diskEncryptionConfiguration"], + ), + nodePlacementConfiguration: !item["nodePlacementConfiguration"] + ? item["nodePlacementConfiguration"] + : nodePlacementConfigurationSerializer( + item["nodePlacementConfiguration"], + ), + extensions: !item["extensions"] + ? item["extensions"] + : vMExtensionArraySerializer(item["extensions"]), + osDisk: !item["osDisk"] ? item["osDisk"] : oSDiskSerializer(item["osDisk"]), + }; +} + +export function virtualMachineConfigurationDeserializer( + item: any, +): VirtualMachineConfiguration { + return { + imageReference: imageReferenceDeserializer(item["imageReference"]), + nodeAgentSkuId: item["nodeAgentSKUId"], + windowsConfiguration: !item["windowsConfiguration"] + ? item["windowsConfiguration"] + : windowsConfigurationDeserializer(item["windowsConfiguration"]), + dataDisks: !item["dataDisks"] + ? item["dataDisks"] + : dataDiskArrayDeserializer(item["dataDisks"]), licenseType: item["licenseType"], - containerConfiguration: !item.containerConfiguration - ? item.containerConfiguration - : containerConfigurationSerializer(item.containerConfiguration), - diskEncryptionConfiguration: !item.diskEncryptionConfiguration - ? item.diskEncryptionConfiguration - : diskEncryptionConfigurationSerializer(item.diskEncryptionConfiguration), - nodePlacementConfiguration: !item.nodePlacementConfiguration - ? item.nodePlacementConfiguration - : nodePlacementConfigurationSerializer(item.nodePlacementConfiguration), - extensions: - item["extensions"] === undefined - ? item["extensions"] - : item["extensions"].map(vMExtensionSerializer), - osDisk: !item.osDisk ? item.osDisk : oSDiskSerializer(item.osDisk), + containerConfiguration: !item["containerConfiguration"] + ? item["containerConfiguration"] + : containerConfigurationDeserializer(item["containerConfiguration"]), + diskEncryptionConfiguration: !item["diskEncryptionConfiguration"] + ? item["diskEncryptionConfiguration"] + : diskEncryptionConfigurationDeserializer( + item["diskEncryptionConfiguration"], + ), + nodePlacementConfiguration: !item["nodePlacementConfiguration"] + ? item["nodePlacementConfiguration"] + : nodePlacementConfigurationDeserializer( + item["nodePlacementConfiguration"], + ), + extensions: !item["extensions"] + ? item["extensions"] + : vMExtensionArrayDeserializer(item["extensions"]), + osDisk: !item["osDisk"] + ? item["osDisk"] + : oSDiskDeserializer(item["osDisk"]), }; } @@ -2167,7 +3426,13 @@ export interface WindowsConfiguration { export function windowsConfigurationSerializer( item: WindowsConfiguration, -): Record { +): any { + return { enableAutomaticUpdates: item["enableAutomaticUpdates"] }; +} + +export function windowsConfigurationDeserializer( + item: any, +): WindowsConfiguration { return { enableAutomaticUpdates: item["enableAutomaticUpdates"], }; @@ -2189,7 +3454,7 @@ export interface DataDisk { storageAccountType?: StorageAccountType; } -export function dataDiskSerializer(item: DataDisk): Record { +export function dataDiskSerializer(item: DataDisk): any { return { lun: item["lun"], caching: item["caching"], @@ -2198,11 +3463,32 @@ export function dataDiskSerializer(item: DataDisk): Record { }; } +export function dataDiskDeserializer(item: any): DataDisk { + return { + lun: item["lun"], + caching: item["caching"], + diskSizeGb: item["diskSizeGB"], + storageAccountType: item["storageAccountType"], + }; +} + /** CachingType enums */ export type CachingType = "none" | "readonly" | "readwrite"; /** StorageAccountType enums */ export type StorageAccountType = "standard_lrs" | "premium_lrs"; +export function dataDiskArraySerializer(result: Array): any[] { + return result.map((item) => { + return dataDiskSerializer(item); + }); +} + +export function dataDiskArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return dataDiskDeserializer(item); + }); +} + /** The configuration for container-enabled Pools. */ export interface ContainerConfiguration { /** The container technology to be used. */ @@ -2215,20 +3501,55 @@ export interface ContainerConfiguration { export function containerConfigurationSerializer( item: ContainerConfiguration, -): Record { +): any { + return { + type: item["type"], + containerImageNames: !item["containerImageNames"] + ? item["containerImageNames"] + : item["containerImageNames"].map((p: any) => { + return p; + }), + containerRegistries: !item["containerRegistries"] + ? item["containerRegistries"] + : containerRegistryArraySerializer(item["containerRegistries"]), + }; +} + +export function containerConfigurationDeserializer( + item: any, +): ContainerConfiguration { return { type: item["type"], - containerImageNames: item["containerImageNames"], - containerRegistries: - item["containerRegistries"] === undefined - ? item["containerRegistries"] - : item["containerRegistries"].map(containerRegistrySerializer), + containerImageNames: !item["containerImageNames"] + ? item["containerImageNames"] + : item["containerImageNames"].map((p: any) => { + return p; + }), + containerRegistries: !item["containerRegistries"] + ? item["containerRegistries"] + : containerRegistryArrayDeserializer(item["containerRegistries"]), }; } /** ContainerType enums */ export type ContainerType = "dockerCompatible" | "criCompatible"; +export function containerRegistryArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return containerRegistrySerializer(item); + }); +} + +export function containerRegistryArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return containerRegistryDeserializer(item); + }); +} + /** * The disk encryption configuration applied on compute nodes in the pool. Disk * encryption configuration is not supported on Linux pool created with Shared @@ -2241,9 +3562,25 @@ export interface DiskEncryptionConfiguration { export function diskEncryptionConfigurationSerializer( item: DiskEncryptionConfiguration, -): Record { +): any { + return { + targets: !item["targets"] + ? item["targets"] + : item["targets"].map((p: any) => { + return p; + }), + }; +} + +export function diskEncryptionConfigurationDeserializer( + item: any, +): DiskEncryptionConfiguration { return { - targets: item["targets"], + targets: !item["targets"] + ? item["targets"] + : item["targets"].map((p: any) => { + return p; + }), }; } @@ -2262,7 +3599,13 @@ export interface NodePlacementConfiguration { export function nodePlacementConfigurationSerializer( item: NodePlacementConfiguration, -): Record { +): any { + return { policy: item["policy"] }; +} + +export function nodePlacementConfigurationDeserializer( + item: any, +): NodePlacementConfiguration { return { policy: item["policy"], }; @@ -2271,17 +3614,39 @@ export function nodePlacementConfigurationSerializer( /** NodePlacementPolicyType enums */ export type NodePlacementPolicyType = "regional" | "zonal"; +export function vMExtensionArraySerializer(result: Array): any[] { + return result.map((item) => { + return vMExtensionSerializer(item); + }); +} + +export function vMExtensionArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return vMExtensionDeserializer(item); + }); +} + /** Settings for the operating system disk of the compute node (VM). */ export interface OSDisk { /** Specifies the ephemeral Disk Settings for the operating system disk used by the compute node (VM). */ ephemeralOSDiskSettings?: DiffDiskSettings; } -export function oSDiskSerializer(item: OSDisk): Record { +export function oSDiskSerializer(item: OSDisk): any { + return { + ephemeralOSDiskSettings: !item["ephemeralOSDiskSettings"] + ? item["ephemeralOSDiskSettings"] + : diffDiskSettingsSerializer(item["ephemeralOSDiskSettings"]), + }; +} + +export function oSDiskDeserializer(item: any): OSDisk { return { - ephemeralOSDiskSettings: !item.ephemeralOSDiskSettings - ? item.ephemeralOSDiskSettings - : diffDiskSettingsSerializer(item.ephemeralOSDiskSettings), + ephemeralOSDiskSettings: !item["ephemeralOSDiskSettings"] + ? item["ephemeralOSDiskSettings"] + : diffDiskSettingsDeserializer(item["ephemeralOSDiskSettings"]), }; } @@ -2294,9 +3659,11 @@ export interface DiffDiskSettings { placement?: DiffDiskPlacement; } -export function diffDiskSettingsSerializer( - item: DiffDiskSettings, -): Record { +export function diffDiskSettingsSerializer(item: DiffDiskSettings): any { + return { placement: item["placement"] }; +} + +export function diffDiskSettingsDeserializer(item: any): DiffDiskSettings { return { placement: item["placement"], }; @@ -2313,7 +3680,13 @@ export interface TaskSchedulingPolicy { export function taskSchedulingPolicySerializer( item: TaskSchedulingPolicy, -): Record { +): any { + return { nodeFillType: item["nodeFillType"] }; +} + +export function taskSchedulingPolicyDeserializer( + item: any, +): TaskSchedulingPolicy { return { nodeFillType: item["nodeFillType"], }; @@ -2338,17 +3711,35 @@ export interface NetworkConfiguration { export function networkConfigurationSerializer( item: NetworkConfiguration, -): Record { +): any { return { subnetId: item["subnetId"], dynamicVNetAssignmentScope: item["dynamicVNetAssignmentScope"], - endpointConfiguration: !item.endpointConfiguration - ? item.endpointConfiguration - : poolEndpointConfigurationSerializer(item.endpointConfiguration), - publicIPAddressConfiguration: !item.publicIpAddressConfiguration - ? item.publicIpAddressConfiguration + endpointConfiguration: !item["endpointConfiguration"] + ? item["endpointConfiguration"] + : poolEndpointConfigurationSerializer(item["endpointConfiguration"]), + publicIPAddressConfiguration: !item["publicIpAddressConfiguration"] + ? item["publicIpAddressConfiguration"] : publicIpAddressConfigurationSerializer( - item.publicIpAddressConfiguration, + item["publicIpAddressConfiguration"], + ), + enableAcceleratedNetworking: item["enableAcceleratedNetworking"], + }; +} + +export function networkConfigurationDeserializer( + item: any, +): NetworkConfiguration { + return { + subnetId: item["subnetId"], + dynamicVNetAssignmentScope: item["dynamicVNetAssignmentScope"], + endpointConfiguration: !item["endpointConfiguration"] + ? item["endpointConfiguration"] + : poolEndpointConfigurationDeserializer(item["endpointConfiguration"]), + publicIpAddressConfiguration: !item["publicIPAddressConfiguration"] + ? item["publicIPAddressConfiguration"] + : publicIpAddressConfigurationDeserializer( + item["publicIPAddressConfiguration"], ), enableAcceleratedNetworking: item["enableAcceleratedNetworking"], }; @@ -2365,9 +3756,17 @@ export interface PoolEndpointConfiguration { export function poolEndpointConfigurationSerializer( item: PoolEndpointConfiguration, -): Record { +): any { + return { + inboundNATPools: inboundNATPoolArraySerializer(item["inboundNatPools"]), + }; +} + +export function poolEndpointConfigurationDeserializer( + item: any, +): PoolEndpointConfiguration { return { - inboundNATPools: item["inboundNatPools"].map(inboundNATPoolSerializer), + inboundNatPools: inboundNATPoolArrayDeserializer(item["inboundNATPools"]), }; } @@ -2390,21 +3789,33 @@ export interface InboundNATPool { networkSecurityGroupRules?: NetworkSecurityGroupRule[]; } -export function inboundNATPoolSerializer( - item: InboundNATPool, -): Record { +export function inboundNATPoolSerializer(item: InboundNATPool): any { + return { + name: item["name"], + protocol: item["protocol"], + backendPort: item["backendPort"], + frontendPortRangeStart: item["frontendPortRangeStart"], + frontendPortRangeEnd: item["frontendPortRangeEnd"], + networkSecurityGroupRules: !item["networkSecurityGroupRules"] + ? item["networkSecurityGroupRules"] + : networkSecurityGroupRuleArraySerializer( + item["networkSecurityGroupRules"], + ), + }; +} + +export function inboundNATPoolDeserializer(item: any): InboundNATPool { return { name: item["name"], protocol: item["protocol"], backendPort: item["backendPort"], frontendPortRangeStart: item["frontendPortRangeStart"], frontendPortRangeEnd: item["frontendPortRangeEnd"], - networkSecurityGroupRules: - item["networkSecurityGroupRules"] === undefined - ? item["networkSecurityGroupRules"] - : item["networkSecurityGroupRules"].map( - networkSecurityGroupRuleSerializer, - ), + networkSecurityGroupRules: !item["networkSecurityGroupRules"] + ? item["networkSecurityGroupRules"] + : networkSecurityGroupRuleArrayDeserializer( + item["networkSecurityGroupRules"], + ), }; } @@ -2422,32 +3833,100 @@ export interface NetworkSecurityGroupRule { export function networkSecurityGroupRuleSerializer( item: NetworkSecurityGroupRule, -): Record { +): any { + return { + priority: item["priority"], + access: item["access"], + sourceAddressPrefix: item["sourceAddressPrefix"], + sourcePortRanges: !item["sourcePortRanges"] + ? item["sourcePortRanges"] + : item["sourcePortRanges"].map((p: any) => { + return p; + }), + }; +} + +export function networkSecurityGroupRuleDeserializer( + item: any, +): NetworkSecurityGroupRule { return { priority: item["priority"], access: item["access"], sourceAddressPrefix: item["sourceAddressPrefix"], - sourcePortRanges: item["sourcePortRanges"], + sourcePortRanges: !item["sourcePortRanges"] + ? item["sourcePortRanges"] + : item["sourcePortRanges"].map((p: any) => { + return p; + }), }; } /** NetworkSecurityGroupRuleAccess enums */ export type NetworkSecurityGroupRuleAccess = "allow" | "deny"; +export function networkSecurityGroupRuleArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return networkSecurityGroupRuleSerializer(item); + }); +} + +export function networkSecurityGroupRuleArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return networkSecurityGroupRuleDeserializer(item); + }); +} + +export function inboundNATPoolArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return inboundNATPoolSerializer(item); + }); +} + +export function inboundNATPoolArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return inboundNATPoolDeserializer(item); + }); +} + /** The public IP Address configuration of the networking configuration of a Pool. */ export interface PublicIpAddressConfiguration { /** The provisioning type for Public IP Addresses for the Pool. The default value is BatchManaged. */ - ipAddressProvisioningType?: IpAddressProvisioningType; + IpAddressProvisioningType?: IpAddressProvisioningType; /** The list of public IPs which the Batch service will use when provisioning Compute Nodes. The number of IPs specified here limits the maximum size of the Pool - 100 dedicated nodes or 100 Spot/Low-priority nodes can be allocated for each public IP. For example, a pool needing 250 dedicated VMs would need at least 3 public IPs specified. Each element of this collection is of the form: /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}. */ ipAddressIds?: string[]; } export function publicIpAddressConfigurationSerializer( item: PublicIpAddressConfiguration, -): Record { +): any { + return { + provision: item["IpAddressProvisioningType"], + ipAddressIds: !item["ipAddressIds"] + ? item["ipAddressIds"] + : item["ipAddressIds"].map((p: any) => { + return p; + }), + }; +} + +export function publicIpAddressConfigurationDeserializer( + item: any, +): PublicIpAddressConfiguration { return { - provision: item["ipAddressProvisioningType"], - ipAddressIds: item["ipAddressIds"], + IpAddressProvisioningType: item["provision"], + ipAddressIds: !item["ipAddressIds"] + ? item["ipAddressIds"] + : item["ipAddressIds"].map((p: any) => { + return p; + }), }; } @@ -2474,19 +3953,31 @@ export interface UserAccount { windowsUserConfiguration?: WindowsUserConfiguration; } -export function userAccountSerializer( - item: UserAccount, -): Record { +export function userAccountSerializer(item: UserAccount): any { return { name: item["name"], password: item["password"], elevationLevel: item["elevationLevel"], - linuxUserConfiguration: !item.linuxUserConfiguration - ? item.linuxUserConfiguration - : linuxUserConfigurationSerializer(item.linuxUserConfiguration), - windowsUserConfiguration: !item.windowsUserConfiguration - ? item.windowsUserConfiguration - : windowsUserConfigurationSerializer(item.windowsUserConfiguration), + linuxUserConfiguration: !item["linuxUserConfiguration"] + ? item["linuxUserConfiguration"] + : linuxUserConfigurationSerializer(item["linuxUserConfiguration"]), + windowsUserConfiguration: !item["windowsUserConfiguration"] + ? item["windowsUserConfiguration"] + : windowsUserConfigurationSerializer(item["windowsUserConfiguration"]), + }; +} + +export function userAccountDeserializer(item: any): UserAccount { + return { + name: item["name"], + password: item["password"], + elevationLevel: item["elevationLevel"], + linuxUserConfiguration: !item["linuxUserConfiguration"] + ? item["linuxUserConfiguration"] + : linuxUserConfigurationDeserializer(item["linuxUserConfiguration"]), + windowsUserConfiguration: !item["windowsUserConfiguration"] + ? item["windowsUserConfiguration"] + : windowsUserConfigurationDeserializer(item["windowsUserConfiguration"]), }; } @@ -2502,7 +3993,17 @@ export interface LinuxUserConfiguration { export function linuxUserConfigurationSerializer( item: LinuxUserConfiguration, -): Record { +): any { + return { + uid: item["uid"], + gid: item["gid"], + sshPrivateKey: item["sshPrivateKey"], + }; +} + +export function linuxUserConfigurationDeserializer( + item: any, +): LinuxUserConfiguration { return { uid: item["uid"], gid: item["gid"], @@ -2518,7 +4019,13 @@ export interface WindowsUserConfiguration { export function windowsUserConfigurationSerializer( item: WindowsUserConfiguration, -): Record { +): any { + return { loginMode: item["loginMode"] }; +} + +export function windowsUserConfigurationDeserializer( + item: any, +): WindowsUserConfiguration { return { loginMode: item["loginMode"], }; @@ -2527,6 +4034,20 @@ export function windowsUserConfigurationSerializer( /** LoginMode enums */ export type LoginMode = "batch" | "interactive"; +export function userAccountArraySerializer(result: Array): any[] { + return result.map((item) => { + return userAccountSerializer(item); + }); +} + +export function userAccountArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return userAccountDeserializer(item); + }); +} + /** * The Batch service does not assign any meaning to this metadata; it is solely * for the use of user code. @@ -2538,15 +4059,33 @@ export interface MetadataItem { value: string; } -export function metadataItemSerializer( - item: MetadataItem, -): Record { +export function metadataItemSerializer(item: MetadataItem): any { + return { name: item["name"], value: item["value"] }; +} + +export function metadataItemDeserializer(item: any): MetadataItem { return { name: item["name"], value: item["value"], }; } +export function metadataItemArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return metadataItemSerializer(item); + }); +} + +export function metadataItemArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return metadataItemDeserializer(item); + }); +} + /** The file system to mount on each node. */ export interface MountConfiguration { /** The Azure Storage Container to mount using blob FUSE on each node. This property is mutually exclusive with all other properties. */ @@ -2559,24 +4098,45 @@ export interface MountConfiguration { azureFileShareConfiguration?: AzureFileShareConfiguration; } -export function mountConfigurationSerializer( - item: MountConfiguration, -): Record { +export function mountConfigurationSerializer(item: MountConfiguration): any { return { - azureBlobFileSystemConfiguration: !item.azureBlobFileSystemConfiguration - ? item.azureBlobFileSystemConfiguration + azureBlobFileSystemConfiguration: !item["azureBlobFileSystemConfiguration"] + ? item["azureBlobFileSystemConfiguration"] : azureBlobFileSystemConfigurationSerializer( - item.azureBlobFileSystemConfiguration, + item["azureBlobFileSystemConfiguration"], + ), + nfsMountConfiguration: !item["nfsMountConfiguration"] + ? item["nfsMountConfiguration"] + : nfsMountConfigurationSerializer(item["nfsMountConfiguration"]), + cifsMountConfiguration: !item["cifsMountConfiguration"] + ? item["cifsMountConfiguration"] + : cifsMountConfigurationSerializer(item["cifsMountConfiguration"]), + azureFileShareConfiguration: !item["azureFileShareConfiguration"] + ? item["azureFileShareConfiguration"] + : azureFileShareConfigurationSerializer( + item["azureFileShareConfiguration"], + ), + }; +} + +export function mountConfigurationDeserializer(item: any): MountConfiguration { + return { + azureBlobFileSystemConfiguration: !item["azureBlobFileSystemConfiguration"] + ? item["azureBlobFileSystemConfiguration"] + : azureBlobFileSystemConfigurationDeserializer( + item["azureBlobFileSystemConfiguration"], + ), + nfsMountConfiguration: !item["nfsMountConfiguration"] + ? item["nfsMountConfiguration"] + : nfsMountConfigurationDeserializer(item["nfsMountConfiguration"]), + cifsMountConfiguration: !item["cifsMountConfiguration"] + ? item["cifsMountConfiguration"] + : cifsMountConfigurationDeserializer(item["cifsMountConfiguration"]), + azureFileShareConfiguration: !item["azureFileShareConfiguration"] + ? item["azureFileShareConfiguration"] + : azureFileShareConfigurationDeserializer( + item["azureFileShareConfiguration"], ), - nfsMountConfiguration: !item.nfsMountConfiguration - ? item.nfsMountConfiguration - : nfsMountConfigurationSerializer(item.nfsMountConfiguration), - cifsMountConfiguration: !item.cifsMountConfiguration - ? item.cifsMountConfiguration - : cifsMountConfigurationSerializer(item.cifsMountConfiguration), - azureFileShareConfiguration: !item.azureFileShareConfiguration - ? item.azureFileShareConfiguration - : azureFileShareConfigurationSerializer(item.azureFileShareConfiguration), }; } @@ -2600,7 +4160,23 @@ export interface AzureBlobFileSystemConfiguration { export function azureBlobFileSystemConfigurationSerializer( item: AzureBlobFileSystemConfiguration, -): Record { +): any { + return { + accountName: item["accountName"], + containerName: item["containerName"], + accountKey: item["accountKey"], + sasKey: item["sasKey"], + blobfuseOptions: item["blobfuseOptions"], + relativeMountPath: item["relativeMountPath"], + identityReference: !item["identityReference"] + ? item["identityReference"] + : batchNodeIdentityReferenceSerializer(item["identityReference"]), + }; +} + +export function azureBlobFileSystemConfigurationDeserializer( + item: any, +): AzureBlobFileSystemConfiguration { return { accountName: item["accountName"], containerName: item["containerName"], @@ -2608,9 +4184,9 @@ export function azureBlobFileSystemConfigurationSerializer( sasKey: item["sasKey"], blobfuseOptions: item["blobfuseOptions"], relativeMountPath: item["relativeMountPath"], - identityReference: !item.identityReference - ? item.identityReference - : batchNodeIdentityReferenceSerializer(item.identityReference), + identityReference: !item["identityReference"] + ? item["identityReference"] + : batchNodeIdentityReferenceDeserializer(item["identityReference"]), }; } @@ -2626,7 +4202,17 @@ export interface NfsMountConfiguration { export function nfsMountConfigurationSerializer( item: NfsMountConfiguration, -): Record { +): any { + return { + source: item["source"], + relativeMountPath: item["relativeMountPath"], + mountOptions: item["mountOptions"], + }; +} + +export function nfsMountConfigurationDeserializer( + item: any, +): NfsMountConfiguration { return { source: item["source"], relativeMountPath: item["relativeMountPath"], @@ -2648,9 +4234,21 @@ export interface CifsMountConfiguration { password: string; } -export function cifsMountConfigurationSerializer( - item: CifsMountConfiguration, -): Record { +export function cifsMountConfigurationSerializer( + item: CifsMountConfiguration, +): any { + return { + username: item["username"], + source: item["source"], + relativeMountPath: item["relativeMountPath"], + mountOptions: item["mountOptions"], + password: item["password"], + }; +} + +export function cifsMountConfigurationDeserializer( + item: any, +): CifsMountConfiguration { return { username: item["username"], source: item["source"], @@ -2676,7 +4274,19 @@ export interface AzureFileShareConfiguration { export function azureFileShareConfigurationSerializer( item: AzureFileShareConfiguration, -): Record { +): any { + return { + accountName: item["accountName"], + azureFileUrl: item["azureFileUrl"], + accountKey: item["accountKey"], + relativeMountPath: item["relativeMountPath"], + mountOptions: item["mountOptions"], + }; +} + +export function azureFileShareConfigurationDeserializer( + item: any, +): AzureFileShareConfiguration { return { accountName: item["accountName"], azureFileUrl: item["azureFileUrl"], @@ -2686,6 +4296,22 @@ export function azureFileShareConfigurationSerializer( }; } +export function mountConfigurationArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return mountConfigurationSerializer(item); + }); +} + +export function mountConfigurationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return mountConfigurationDeserializer(item); + }); +} + /** NodeCommunicationMode enums */ export type NodeCommunicationMode = "default" | "classic" | "simplified"; @@ -2702,6 +4328,20 @@ export interface JobScheduleExecutionInformation { endTime?: Date; } +export function jobScheduleExecutionInformationDeserializer( + item: any, +): JobScheduleExecutionInformation { + return { + nextRunTime: !item["nextRunTime"] + ? item["nextRunTime"] + : new Date(item["nextRunTime"]), + recentJob: !item["recentJob"] + ? item["recentJob"] + : recentJobDeserializer(item["recentJob"]), + endTime: !item["endTime"] ? item["endTime"] : new Date(item["endTime"]), + }; +} + /** Information about the most recent Job to run under the Job Schedule. */ export interface RecentJob { /** The ID of the Job. */ @@ -2710,6 +4350,13 @@ export interface RecentJob { url?: string; } +export function recentJobDeserializer(item: any): RecentJob { + return { + id: item["id"], + url: item["url"], + }; +} + /** Resource usage statistics for a Job Schedule. */ export interface JobScheduleStatistics { /** The URL of the statistics. */ @@ -2742,6 +4389,27 @@ export interface JobScheduleStatistics { waitTime: string; } +export function jobScheduleStatisticsDeserializer( + item: any, +): JobScheduleStatistics { + return { + url: item["url"], + startTime: new Date(item["startTime"]), + lastUpdateTime: new Date(item["lastUpdateTime"]), + userCPUTime: item["userCPUTime"], + kernelCPUTime: item["kernelCPUTime"], + wallClockTime: item["wallClockTime"], + readIOps: item["readIOps"], + writeIOps: item["writeIOps"], + readIOGiB: item["readIOGiB"], + writeIOGiB: item["writeIOGiB"], + numSucceededTasks: item["numSucceededTasks"], + numFailedTasks: item["numFailedTasks"], + numTaskRetries: item["numTaskRetries"], + waitTime: item["waitTime"], + }; +} + /** Options for updating an Azure Batch Job Schedule. */ export interface BatchJobScheduleUpdateOptions { /** The schedule according to which Jobs will be created. All times are fixed respective to UTC and are not impacted by daylight saving time. If you do not specify this element, the existing schedule is left unchanged. */ @@ -2754,18 +4422,17 @@ export interface BatchJobScheduleUpdateOptions { export function batchJobScheduleUpdateOptionsSerializer( item: BatchJobScheduleUpdateOptions, -): Record { +): any { return { - schedule: !item.schedule - ? item.schedule - : scheduleSerializer(item.schedule), - jobSpecification: !item.jobSpecification - ? item.jobSpecification - : jobSpecificationSerializer(item.jobSpecification), - metadata: - item["metadata"] === undefined - ? item["metadata"] - : item["metadata"].map(metadataItemSerializer), + schedule: !item["schedule"] + ? item["schedule"] + : scheduleSerializer(item["schedule"]), + jobSpecification: !item["jobSpecification"] + ? item["jobSpecification"] + : jobSpecificationSerializer(item["jobSpecification"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArraySerializer(item["metadata"]), }; } @@ -2785,16 +4452,15 @@ export interface BatchJobScheduleCreateOptions { export function batchJobScheduleCreateOptionsSerializer( item: BatchJobScheduleCreateOptions, -): Record { +): any { return { id: item["id"], displayName: item["displayName"], - schedule: scheduleSerializer(item.schedule), - jobSpecification: jobSpecificationSerializer(item.jobSpecification), - metadata: - item["metadata"] === undefined - ? item["metadata"] - : item["metadata"].map(metadataItemSerializer), + schedule: scheduleSerializer(item["schedule"]), + jobSpecification: jobSpecificationSerializer(item["jobSpecification"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArraySerializer(item["metadata"]), }; } @@ -2806,6 +4472,33 @@ export interface _BatchJobScheduleListResult { "odata.nextLink"?: string; } +export function _batchJobScheduleListResultDeserializer( + item: any, +): _BatchJobScheduleListResult { + return { + value: !item["value"] + ? item["value"] + : batchJobScheduleArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + +export function batchJobScheduleArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return batchJobScheduleSerializer(item); + }); +} + +export function batchJobScheduleArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return batchJobScheduleDeserializer(item); + }); +} + /** * A Certificate that can be installed on Compute Nodes and can be used to * authenticate operations on the machine. @@ -2837,9 +4530,7 @@ export interface BatchCertificate { password?: string; } -export function batchCertificateSerializer( - item: BatchCertificate, -): Record { +export function batchCertificateSerializer(item: BatchCertificate): any { return { thumbprint: item["thumbprint"], thumbprintAlgorithm: item["thumbprintAlgorithm"], @@ -2849,6 +4540,36 @@ export function batchCertificateSerializer( }; } +export function batchCertificateDeserializer(item: any): BatchCertificate { + return { + thumbprint: item["thumbprint"], + thumbprintAlgorithm: item["thumbprintAlgorithm"], + url: item["url"], + state: item["state"], + stateTransitionTime: !item["stateTransitionTime"] + ? item["stateTransitionTime"] + : new Date(item["stateTransitionTime"]), + previousState: item["previousState"], + previousStateTransitionTime: !item["previousStateTransitionTime"] + ? item["previousStateTransitionTime"] + : new Date(item["previousStateTransitionTime"]), + publicData: !item["publicData"] + ? item["publicData"] + : typeof item["publicData"] === "string" + ? stringToUint8Array(item["publicData"], "base64") + : item["publicData"], + deleteCertificateError: !item["deleteCertificateError"] + ? item["deleteCertificateError"] + : deleteCertificateErrorDeserializer(item["deleteCertificateError"]), + data: + typeof item["data"] === "string" + ? stringToUint8Array(item["data"], "base64") + : item["data"], + certificateFormat: item["certificateFormat"], + password: item["password"], + }; +} + /** CertificateState enums */ export type CertificateState = "active" | "deleting" | "deletefailed"; @@ -2862,6 +4583,18 @@ export interface DeleteCertificateError { values?: NameValuePair[]; } +export function deleteCertificateErrorDeserializer( + item: any, +): DeleteCertificateError { + return { + code: item["code"], + message: item["message"], + values: !item["values"] + ? item["values"] + : nameValuePairArrayDeserializer(item["values"]), + }; +} + /** CertificateFormat enums */ export type CertificateFormat = "pfx" | "cer"; @@ -2873,6 +4606,33 @@ export interface _CertificateListResult { "odata.nextLink"?: string; } +export function _certificateListResultDeserializer( + item: any, +): _CertificateListResult { + return { + value: !item["value"] + ? item["value"] + : batchCertificateArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + +export function batchCertificateArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return batchCertificateSerializer(item); + }); +} + +export function batchCertificateArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return batchCertificateDeserializer(item); + }); +} + /** An Azure Batch Job. */ export interface BatchJob { /** A string that uniquely identifies the Job within the Account. The ID is case-preserving and case-insensitive (that is, you may not have two IDs within an Account that differ only by case). */ @@ -2929,20 +4689,76 @@ export interface BatchJob { readonly stats?: JobStatistics; } -export function batchJobSerializer(item: BatchJob): Record { +export function batchJobSerializer(item: BatchJob): any { + return { + priority: item["priority"], + allowTaskPreemption: item["allowTaskPreemption"], + maxParallelTasks: item["maxParallelTasks"], + constraints: !item["constraints"] + ? item["constraints"] + : jobConstraintsSerializer(item["constraints"]), + poolInfo: poolInformationSerializer(item["poolInfo"]), + onAllTasksComplete: item["onAllTasksComplete"], + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArraySerializer(item["metadata"]), + }; +} + +export function batchJobDeserializer(item: any): BatchJob { return { + id: item["id"], + displayName: item["displayName"], + usesTaskDependencies: item["usesTaskDependencies"], + url: item["url"], + eTag: item["eTag"], + lastModified: !item["lastModified"] + ? item["lastModified"] + : new Date(item["lastModified"]), + creationTime: !item["creationTime"] + ? item["creationTime"] + : new Date(item["creationTime"]), + state: item["state"], + stateTransitionTime: !item["stateTransitionTime"] + ? item["stateTransitionTime"] + : new Date(item["stateTransitionTime"]), + previousState: item["previousState"], + previousStateTransitionTime: !item["previousStateTransitionTime"] + ? item["previousStateTransitionTime"] + : new Date(item["previousStateTransitionTime"]), priority: item["priority"], allowTaskPreemption: item["allowTaskPreemption"], maxParallelTasks: item["maxParallelTasks"], - constraints: !item.constraints - ? item.constraints - : jobConstraintsSerializer(item.constraints), - poolInfo: poolInformationSerializer(item.poolInfo), + constraints: !item["constraints"] + ? item["constraints"] + : jobConstraintsDeserializer(item["constraints"]), + jobManagerTask: !item["jobManagerTask"] + ? item["jobManagerTask"] + : jobManagerTaskDeserializer(item["jobManagerTask"]), + jobPreparationTask: !item["jobPreparationTask"] + ? item["jobPreparationTask"] + : jobPreparationTaskDeserializer(item["jobPreparationTask"]), + jobReleaseTask: !item["jobReleaseTask"] + ? item["jobReleaseTask"] + : jobReleaseTaskDeserializer(item["jobReleaseTask"]), + commonEnvironmentSettings: !item["commonEnvironmentSettings"] + ? item["commonEnvironmentSettings"] + : environmentSettingArrayDeserializer(item["commonEnvironmentSettings"]), + poolInfo: poolInformationDeserializer(item["poolInfo"]), onAllTasksComplete: item["onAllTasksComplete"], - metadata: - item["metadata"] === undefined - ? item["metadata"] - : item["metadata"].map(metadataItemSerializer), + onTaskFailure: item["onTaskFailure"], + networkConfiguration: !item["networkConfiguration"] + ? item["networkConfiguration"] + : jobNetworkConfigurationDeserializer(item["networkConfiguration"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArrayDeserializer(item["metadata"]), + executionInfo: !item["executionInfo"] + ? item["executionInfo"] + : jobExecutionInformationDeserializer(item["executionInfo"]), + stats: !item["stats"] + ? item["stats"] + : jobStatisticsDeserializer(item["stats"]), }; } @@ -2970,6 +4786,20 @@ export interface JobExecutionInformation { terminateReason?: string; } +export function jobExecutionInformationDeserializer( + item: any, +): JobExecutionInformation { + return { + startTime: new Date(item["startTime"]), + endTime: !item["endTime"] ? item["endTime"] : new Date(item["endTime"]), + poolId: item["poolId"], + schedulingError: !item["schedulingError"] + ? item["schedulingError"] + : jobSchedulingErrorDeserializer(item["schedulingError"]), + terminateReason: item["terminateReason"], + }; +} + /** An error encountered by the Batch service when scheduling a Job. */ export interface JobSchedulingError { /** The category of the Job scheduling error. */ @@ -2982,6 +4812,17 @@ export interface JobSchedulingError { details?: NameValuePair[]; } +export function jobSchedulingErrorDeserializer(item: any): JobSchedulingError { + return { + category: item["category"], + code: item["code"], + message: item["message"], + details: !item["details"] + ? item["details"] + : nameValuePairArrayDeserializer(item["details"]), + }; +} + /** Resource usage statistics for a Job. */ export interface JobStatistics { /** The URL of the statistics. */ @@ -3014,6 +4855,25 @@ export interface JobStatistics { waitTime: string; } +export function jobStatisticsDeserializer(item: any): JobStatistics { + return { + url: item["url"], + startTime: new Date(item["startTime"]), + lastUpdateTime: new Date(item["lastUpdateTime"]), + userCPUTime: item["userCPUTime"], + kernelCPUTime: item["kernelCPUTime"], + wallClockTime: item["wallClockTime"], + readIOps: item["readIOps"], + writeIOps: item["writeIOps"], + readIOGiB: item["readIOGiB"], + writeIOGiB: item["writeIOGiB"], + numSucceededTasks: item["numSucceededTasks"], + numFailedTasks: item["numFailedTasks"], + numTaskRetries: item["numTaskRetries"], + waitTime: item["waitTime"], + }; +} + /** Options for updating an Azure Batch Job. */ export interface BatchJobUpdateOptions { /** The priority of the Job. Priority values can range from -1000 to 1000, with -1000 being the lowest priority and 1000 being the highest priority. If omitted, the priority of the Job is left unchanged. */ @@ -3034,22 +4894,21 @@ export interface BatchJobUpdateOptions { export function batchJobUpdateOptionsSerializer( item: BatchJobUpdateOptions, -): Record { +): any { return { priority: item["priority"], allowTaskPreemption: item["allowTaskPreemption"], maxParallelTasks: item["maxParallelTasks"], - constraints: !item.constraints - ? item.constraints - : jobConstraintsSerializer(item.constraints), - poolInfo: !item.poolInfo - ? item.poolInfo - : poolInformationSerializer(item.poolInfo), + constraints: !item["constraints"] + ? item["constraints"] + : jobConstraintsSerializer(item["constraints"]), + poolInfo: !item["poolInfo"] + ? item["poolInfo"] + : poolInformationSerializer(item["poolInfo"]), onAllTasksComplete: item["onAllTasksComplete"], - metadata: - item["metadata"] === undefined - ? item["metadata"] - : item["metadata"].map(metadataItemSerializer), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArraySerializer(item["metadata"]), }; } @@ -3061,10 +4920,8 @@ export interface BatchJobDisableOptions { export function batchJobDisableOptionsSerializer( item: BatchJobDisableOptions, -): Record { - return { - disableTasks: item["disableTasks"], - }; +): any { + return { disableTasks: item["disableTasks"] }; } /** DisableJobOption enums */ @@ -3078,10 +4935,8 @@ export interface BatchJobTerminateOptions { export function batchJobTerminateOptionsSerializer( item: BatchJobTerminateOptions, -): Record { - return { - terminateReason: item["terminateReason"], - }; +): any { + return { terminateReason: item["terminateReason"] }; } /** Options for creating an Azure Batch Job. */ @@ -3122,7 +4977,7 @@ export interface BatchJobCreateOptions { export function batchJobCreateOptionsSerializer( item: BatchJobCreateOptions, -): Record { +): any { return { id: item["id"], displayName: item["displayName"], @@ -3130,32 +4985,30 @@ export function batchJobCreateOptionsSerializer( priority: item["priority"], allowTaskPreemption: item["allowTaskPreemption"], maxParallelTasks: item["maxParallelTasks"], - constraints: !item.constraints - ? item.constraints - : jobConstraintsSerializer(item.constraints), - jobManagerTask: !item.jobManagerTask - ? item.jobManagerTask - : jobManagerTaskSerializer(item.jobManagerTask), - jobPreparationTask: !item.jobPreparationTask - ? item.jobPreparationTask - : jobPreparationTaskSerializer(item.jobPreparationTask), - jobReleaseTask: !item.jobReleaseTask - ? item.jobReleaseTask - : jobReleaseTaskSerializer(item.jobReleaseTask), - commonEnvironmentSettings: - item["commonEnvironmentSettings"] === undefined - ? item["commonEnvironmentSettings"] - : item["commonEnvironmentSettings"].map(environmentSettingSerializer), - poolInfo: poolInformationSerializer(item.poolInfo), + constraints: !item["constraints"] + ? item["constraints"] + : jobConstraintsSerializer(item["constraints"]), + jobManagerTask: !item["jobManagerTask"] + ? item["jobManagerTask"] + : jobManagerTaskSerializer(item["jobManagerTask"]), + jobPreparationTask: !item["jobPreparationTask"] + ? item["jobPreparationTask"] + : jobPreparationTaskSerializer(item["jobPreparationTask"]), + jobReleaseTask: !item["jobReleaseTask"] + ? item["jobReleaseTask"] + : jobReleaseTaskSerializer(item["jobReleaseTask"]), + commonEnvironmentSettings: !item["commonEnvironmentSettings"] + ? item["commonEnvironmentSettings"] + : environmentSettingArraySerializer(item["commonEnvironmentSettings"]), + poolInfo: poolInformationSerializer(item["poolInfo"]), onAllTasksComplete: item["onAllTasksComplete"], onTaskFailure: item["onTaskFailure"], - networkConfiguration: !item.networkConfiguration - ? item.networkConfiguration - : jobNetworkConfigurationSerializer(item.networkConfiguration), - metadata: - item["metadata"] === undefined - ? item["metadata"] - : item["metadata"].map(metadataItemSerializer), + networkConfiguration: !item["networkConfiguration"] + ? item["networkConfiguration"] + : jobNetworkConfigurationSerializer(item["networkConfiguration"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArraySerializer(item["metadata"]), }; } @@ -3167,6 +5020,29 @@ export interface _BatchJobListResult { "odata.nextLink"?: string; } +export function _batchJobListResultDeserializer( + item: any, +): _BatchJobListResult { + return { + value: !item["value"] + ? item["value"] + : batchJobArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + +export function batchJobArraySerializer(result: Array): any[] { + return result.map((item) => { + return batchJobSerializer(item); + }); +} + +export function batchJobArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return batchJobDeserializer(item); + }); +} + /** * The result of listing the status of the Job Preparation and Job Release Tasks * for a Job. @@ -3178,6 +5054,19 @@ export interface _BatchJobListPreparationAndReleaseTaskStatusResult { "odata.nextLink"?: string; } +export function _batchJobListPreparationAndReleaseTaskStatusResultDeserializer( + item: any, +): _BatchJobListPreparationAndReleaseTaskStatusResult { + return { + value: !item["value"] + ? item["value"] + : jobPreparationAndReleaseTaskExecutionInformationArrayDeserializer( + item["value"], + ), + "odata.nextLink": item["odata.nextLink"], + }; +} + /** The status of the Job Preparation and Job Release Tasks on a Compute Node. */ export interface JobPreparationAndReleaseTaskExecutionInformation { /** The ID of the Pool containing the Compute Node to which this entry refers. */ @@ -3192,6 +5081,26 @@ export interface JobPreparationAndReleaseTaskExecutionInformation { jobReleaseTaskExecutionInfo?: JobReleaseTaskExecutionInformation; } +export function jobPreparationAndReleaseTaskExecutionInformationDeserializer( + item: any, +): JobPreparationAndReleaseTaskExecutionInformation { + return { + poolId: item["poolId"], + nodeId: item["nodeId"], + nodeUrl: item["nodeUrl"], + jobPreparationTaskExecutionInfo: !item["jobPreparationTaskExecutionInfo"] + ? item["jobPreparationTaskExecutionInfo"] + : jobPreparationTaskExecutionInformationDeserializer( + item["jobPreparationTaskExecutionInfo"], + ), + jobReleaseTaskExecutionInfo: !item["jobReleaseTaskExecutionInfo"] + ? item["jobReleaseTaskExecutionInfo"] + : jobReleaseTaskExecutionInformationDeserializer( + item["jobReleaseTaskExecutionInfo"], + ), + }; +} + /** * Contains information about the execution of a Job Preparation Task on a Compute * Node. @@ -3221,6 +5130,30 @@ export interface JobPreparationTaskExecutionInformation { result?: TaskExecutionResult; } +export function jobPreparationTaskExecutionInformationDeserializer( + item: any, +): JobPreparationTaskExecutionInformation { + return { + startTime: new Date(item["startTime"]), + endTime: !item["endTime"] ? item["endTime"] : new Date(item["endTime"]), + state: item["state"], + taskRootDirectory: item["taskRootDirectory"], + taskRootDirectoryUrl: item["taskRootDirectoryUrl"], + exitCode: item["exitCode"], + containerInfo: !item["containerInfo"] + ? item["containerInfo"] + : taskContainerExecutionInformationDeserializer(item["containerInfo"]), + failureInfo: !item["failureInfo"] + ? item["failureInfo"] + : taskFailureInformationDeserializer(item["failureInfo"]), + retryCount: item["retryCount"], + lastRetryTime: !item["lastRetryTime"] + ? item["lastRetryTime"] + : new Date(item["lastRetryTime"]), + result: item["result"], + }; +} + /** JobPreparationTaskState enums */ export type JobPreparationTaskState = "running" | "completed"; @@ -3249,9 +5182,37 @@ export interface JobReleaseTaskExecutionInformation { result?: TaskExecutionResult; } +export function jobReleaseTaskExecutionInformationDeserializer( + item: any, +): JobReleaseTaskExecutionInformation { + return { + startTime: new Date(item["startTime"]), + endTime: !item["endTime"] ? item["endTime"] : new Date(item["endTime"]), + state: item["state"], + taskRootDirectory: item["taskRootDirectory"], + taskRootDirectoryUrl: item["taskRootDirectoryUrl"], + exitCode: item["exitCode"], + containerInfo: !item["containerInfo"] + ? item["containerInfo"] + : taskContainerExecutionInformationDeserializer(item["containerInfo"]), + failureInfo: !item["failureInfo"] + ? item["failureInfo"] + : taskFailureInformationDeserializer(item["failureInfo"]), + result: item["result"], + }; +} + /** JobReleaseTaskState enums */ export type JobReleaseTaskState = "running" | "completed"; +export function jobPreparationAndReleaseTaskExecutionInformationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return jobPreparationAndReleaseTaskExecutionInformationDeserializer(item); + }); +} + /** The Task and TaskSlot counts for a Job. */ export interface TaskCountsResult { /** The number of Tasks per state. */ @@ -3260,6 +5221,13 @@ export interface TaskCountsResult { taskSlotCounts: TaskSlotCounts; } +export function taskCountsResultDeserializer(item: any): TaskCountsResult { + return { + taskCounts: taskCountsDeserializer(item["taskCounts"]), + taskSlotCounts: taskSlotCountsDeserializer(item["taskSlotCounts"]), + }; +} + /** The Task counts for a Job. */ export interface TaskCounts { /** The number of Tasks in the active state. */ @@ -3274,6 +5242,16 @@ export interface TaskCounts { failed: number; } +export function taskCountsDeserializer(item: any): TaskCounts { + return { + active: item["active"], + running: item["running"], + completed: item["completed"], + succeeded: item["succeeded"], + failed: item["failed"], + }; +} + /** The TaskSlot counts for a Job. */ export interface TaskSlotCounts { /** The number of TaskSlots for active Tasks. */ @@ -3288,6 +5266,16 @@ export interface TaskSlotCounts { failed: number; } +export function taskSlotCountsDeserializer(item: any): TaskSlotCounts { + return { + active: item["active"], + running: item["running"], + completed: item["completed"], + succeeded: item["succeeded"], + failed: item["failed"], + }; +} + /** The result of listing the supported Virtual Machine Images. */ export interface _AccountListSupportedImagesResult { /** The list of supported Virtual Machine Images. */ @@ -3296,6 +5284,17 @@ export interface _AccountListSupportedImagesResult { "odata.nextLink"?: string; } +export function _accountListSupportedImagesResultDeserializer( + item: any, +): _AccountListSupportedImagesResult { + return { + value: !item["value"] + ? item["value"] + : imageInformationArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + /** * A reference to the Azure Virtual Machines Marketplace Image and additional * information about the Image. @@ -3315,11 +5314,36 @@ export interface ImageInformation { verificationType: VerificationType; } +export function imageInformationDeserializer(item: any): ImageInformation { + return { + nodeAgentSkuId: item["nodeAgentSKUId"], + imageReference: imageReferenceDeserializer(item["imageReference"]), + osType: item["osType"], + capabilities: !item["capabilities"] + ? item["capabilities"] + : item["capabilities"].map((p: any) => { + return p; + }), + batchSupportEndOfLife: !item["batchSupportEndOfLife"] + ? item["batchSupportEndOfLife"] + : new Date(item["batchSupportEndOfLife"]), + verificationType: item["verificationType"], + }; +} + /** OSType enums */ export type OSType = "linux" | "windows"; /** VerificationType enums */ export type VerificationType = "verified" | "unverified"; +export function imageInformationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return imageInformationDeserializer(item); + }); +} + /** The result of listing the Compute Node counts in the Account. */ export interface _PoolNodeCountsListResult { /** A list of Compute Node counts by Pool. */ @@ -3328,6 +5352,17 @@ export interface _PoolNodeCountsListResult { "odata.nextLink"?: string; } +export function _poolNodeCountsListResultDeserializer( + item: any, +): _PoolNodeCountsListResult { + return { + value: !item["value"] + ? item["value"] + : poolNodeCountsArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + /** The number of Compute Nodes in each state for a Pool. */ export interface PoolNodeCounts { /** The ID of the Pool. */ @@ -3338,6 +5373,18 @@ export interface PoolNodeCounts { lowPriority?: NodeCounts; } +export function poolNodeCountsDeserializer(item: any): PoolNodeCounts { + return { + poolId: item["poolId"], + dedicated: !item["dedicated"] + ? item["dedicated"] + : nodeCountsDeserializer(item["dedicated"]), + lowPriority: !item["lowPriority"] + ? item["lowPriority"] + : nodeCountsDeserializer(item["lowPriority"]), + }; +} + /** The number of Compute Nodes in each Compute Node state. */ export interface NodeCounts { /** The number of Compute Nodes in the creating state. */ @@ -3370,6 +5417,33 @@ export interface NodeCounts { total: number; } +export function nodeCountsDeserializer(item: any): NodeCounts { + return { + creating: item["creating"], + idle: item["idle"], + offline: item["offline"], + preempted: item["preempted"], + rebooting: item["rebooting"], + reimaging: item["reimaging"], + running: item["running"], + starting: item["starting"], + startTaskFailed: item["startTaskFailed"], + leavingPool: item["leavingPool"], + unknown: item["unknown"], + unusable: item["unusable"], + waitingForStartTask: item["waitingForStartTask"], + total: item["total"], + }; +} + +export function poolNodeCountsArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return poolNodeCountsDeserializer(item); + }); +} + /** The result of a listing the usage metrics for an Account. */ export interface _PoolListUsageMetricsResult { /** The Pool usage metrics data. */ @@ -3378,6 +5452,17 @@ export interface _PoolListUsageMetricsResult { "odata.nextLink"?: string; } +export function _poolListUsageMetricsResultDeserializer( + item: any, +): _PoolListUsageMetricsResult { + return { + value: !item["value"] + ? item["value"] + : poolUsageMetricsArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + /** Usage metrics for a Pool across an aggregation interval. */ export interface PoolUsageMetrics { /** The ID of the Pool whose metrics are aggregated in this entry. */ @@ -3392,6 +5477,24 @@ export interface PoolUsageMetrics { totalCoreHours: number; } +export function poolUsageMetricsDeserializer(item: any): PoolUsageMetrics { + return { + poolId: item["poolId"], + startTime: new Date(item["startTime"]), + endTime: new Date(item["endTime"]), + vmSize: item["vmSize"], + totalCoreHours: item["totalCoreHours"], + }; +} + +export function poolUsageMetricsArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return poolUsageMetricsDeserializer(item); + }); +} + /** Options for creating an Azure Batch Pool. */ export interface BatchPoolCreateOptions { /** A string that uniquely identifies the Pool within the Account. The ID can contain any combination of alphanumeric characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and case-insensitive (that is, you may not have two Pool IDs within an Account that differ only by case). */ @@ -3449,17 +5552,19 @@ export interface BatchPoolCreateOptions { export function batchPoolCreateOptionsSerializer( item: BatchPoolCreateOptions, -): Record { +): any { return { id: item["id"], displayName: item["displayName"], vmSize: item["vmSize"], - cloudServiceConfiguration: !item.cloudServiceConfiguration - ? item.cloudServiceConfiguration - : cloudServiceConfigurationSerializer(item.cloudServiceConfiguration), - virtualMachineConfiguration: !item.virtualMachineConfiguration - ? item.virtualMachineConfiguration - : virtualMachineConfigurationSerializer(item.virtualMachineConfiguration), + cloudServiceConfiguration: !item["cloudServiceConfiguration"] + ? item["cloudServiceConfiguration"] + : cloudServiceConfigurationSerializer(item["cloudServiceConfiguration"]), + virtualMachineConfiguration: !item["virtualMachineConfiguration"] + ? item["virtualMachineConfiguration"] + : virtualMachineConfigurationSerializer( + item["virtualMachineConfiguration"], + ), resizeTimeout: item["resizeTimeout"], targetDedicatedNodes: item["targetDedicatedNodes"], targetLowPriorityNodes: item["targetLowPriorityNodes"], @@ -3467,39 +5572,38 @@ export function batchPoolCreateOptionsSerializer( autoScaleFormula: item["autoScaleFormula"], autoScaleEvaluationInterval: item["autoScaleEvaluationInterval"], enableInterNodeCommunication: item["enableInterNodeCommunication"], - networkConfiguration: !item.networkConfiguration - ? item.networkConfiguration - : networkConfigurationSerializer(item.networkConfiguration), - startTask: !item.startTask - ? item.startTask - : startTaskSerializer(item.startTask), - certificateReferences: - item["certificateReferences"] === undefined - ? item["certificateReferences"] - : item["certificateReferences"].map(certificateReferenceSerializer), - applicationPackageReferences: - item["applicationPackageReferences"] === undefined - ? item["applicationPackageReferences"] - : item["applicationPackageReferences"].map( - applicationPackageReferenceSerializer, - ), - applicationLicenses: item["applicationLicenses"], + networkConfiguration: !item["networkConfiguration"] + ? item["networkConfiguration"] + : networkConfigurationSerializer(item["networkConfiguration"]), + startTask: !item["startTask"] + ? item["startTask"] + : startTaskSerializer(item["startTask"]), + certificateReferences: !item["certificateReferences"] + ? item["certificateReferences"] + : certificateReferenceArraySerializer(item["certificateReferences"]), + applicationPackageReferences: !item["applicationPackageReferences"] + ? item["applicationPackageReferences"] + : applicationPackageReferenceArraySerializer( + item["applicationPackageReferences"], + ), + applicationLicenses: !item["applicationLicenses"] + ? item["applicationLicenses"] + : item["applicationLicenses"].map((p: any) => { + return p; + }), taskSlotsPerNode: item["taskSlotsPerNode"], - taskSchedulingPolicy: !item.taskSchedulingPolicy - ? item.taskSchedulingPolicy - : taskSchedulingPolicySerializer(item.taskSchedulingPolicy), - userAccounts: - item["userAccounts"] === undefined - ? item["userAccounts"] - : item["userAccounts"].map(userAccountSerializer), - metadata: - item["metadata"] === undefined - ? item["metadata"] - : item["metadata"].map(metadataItemSerializer), - mountConfiguration: - item["mountConfiguration"] === undefined - ? item["mountConfiguration"] - : item["mountConfiguration"].map(mountConfigurationSerializer), + taskSchedulingPolicy: !item["taskSchedulingPolicy"] + ? item["taskSchedulingPolicy"] + : taskSchedulingPolicySerializer(item["taskSchedulingPolicy"]), + userAccounts: !item["userAccounts"] + ? item["userAccounts"] + : userAccountArraySerializer(item["userAccounts"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArraySerializer(item["metadata"]), + mountConfiguration: !item["mountConfiguration"] + ? item["mountConfiguration"] + : mountConfigurationArraySerializer(item["mountConfiguration"]), targetNodeCommunicationMode: item["targetNodeCommunicationMode"], }; } @@ -3512,6 +5616,17 @@ export interface _BatchPoolListResult { "odata.nextLink"?: string; } +export function _batchPoolListResultDeserializer( + item: any, +): _BatchPoolListResult { + return { + value: !item["value"] + ? item["value"] + : batchPoolArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + /** A Pool in the Azure Batch service. */ export interface BatchPool { /** A string that uniquely identifies the Pool within the Account. The ID can contain any combination of alphanumeric characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and case-insensitive (that is, you may not have two IDs within an Account that differ only by case). */ @@ -3597,6 +5712,95 @@ export interface BatchPool { readonly currentNodeCommunicationMode?: NodeCommunicationMode; } +export function batchPoolDeserializer(item: any): BatchPool { + return { + id: item["id"], + displayName: item["displayName"], + url: item["url"], + eTag: item["eTag"], + lastModified: !item["lastModified"] + ? item["lastModified"] + : new Date(item["lastModified"]), + creationTime: !item["creationTime"] + ? item["creationTime"] + : new Date(item["creationTime"]), + state: item["state"], + stateTransitionTime: !item["stateTransitionTime"] + ? item["stateTransitionTime"] + : new Date(item["stateTransitionTime"]), + allocationState: item["allocationState"], + allocationStateTransitionTime: !item["allocationStateTransitionTime"] + ? item["allocationStateTransitionTime"] + : new Date(item["allocationStateTransitionTime"]), + vmSize: item["vmSize"], + cloudServiceConfiguration: !item["cloudServiceConfiguration"] + ? item["cloudServiceConfiguration"] + : cloudServiceConfigurationDeserializer( + item["cloudServiceConfiguration"], + ), + virtualMachineConfiguration: !item["virtualMachineConfiguration"] + ? item["virtualMachineConfiguration"] + : virtualMachineConfigurationDeserializer( + item["virtualMachineConfiguration"], + ), + resizeTimeout: item["resizeTimeout"], + resizeErrors: !item["resizeErrors"] + ? item["resizeErrors"] + : resizeErrorArrayDeserializer(item["resizeErrors"]), + currentDedicatedNodes: item["currentDedicatedNodes"], + currentLowPriorityNodes: item["currentLowPriorityNodes"], + targetDedicatedNodes: item["targetDedicatedNodes"], + targetLowPriorityNodes: item["targetLowPriorityNodes"], + enableAutoScale: item["enableAutoScale"], + autoScaleFormula: item["autoScaleFormula"], + autoScaleEvaluationInterval: item["autoScaleEvaluationInterval"], + autoScaleRun: !item["autoScaleRun"] + ? item["autoScaleRun"] + : autoScaleRunDeserializer(item["autoScaleRun"]), + enableInterNodeCommunication: item["enableInterNodeCommunication"], + networkConfiguration: !item["networkConfiguration"] + ? item["networkConfiguration"] + : networkConfigurationDeserializer(item["networkConfiguration"]), + startTask: !item["startTask"] + ? item["startTask"] + : startTaskDeserializer(item["startTask"]), + certificateReferences: !item["certificateReferences"] + ? item["certificateReferences"] + : certificateReferenceArrayDeserializer(item["certificateReferences"]), + applicationPackageReferences: !item["applicationPackageReferences"] + ? item["applicationPackageReferences"] + : applicationPackageReferenceArrayDeserializer( + item["applicationPackageReferences"], + ), + applicationLicenses: !item["applicationLicenses"] + ? item["applicationLicenses"] + : item["applicationLicenses"].map((p: any) => { + return p; + }), + taskSlotsPerNode: item["taskSlotsPerNode"], + taskSchedulingPolicy: !item["taskSchedulingPolicy"] + ? item["taskSchedulingPolicy"] + : taskSchedulingPolicyDeserializer(item["taskSchedulingPolicy"]), + userAccounts: !item["userAccounts"] + ? item["userAccounts"] + : userAccountArrayDeserializer(item["userAccounts"]), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArrayDeserializer(item["metadata"]), + stats: !item["stats"] + ? item["stats"] + : poolStatisticsDeserializer(item["stats"]), + mountConfiguration: !item["mountConfiguration"] + ? item["mountConfiguration"] + : mountConfigurationArrayDeserializer(item["mountConfiguration"]), + identity: !item["identity"] + ? item["identity"] + : batchPoolIdentityDeserializer(item["identity"]), + targetNodeCommunicationMode: item["targetNodeCommunicationMode"], + currentNodeCommunicationMode: item["currentNodeCommunicationMode"], + }; +} + /** PoolState enums */ export type PoolState = "active" | "deleting"; /** AllocationState enums */ @@ -3612,6 +5816,24 @@ export interface ResizeError { values?: NameValuePair[]; } +export function resizeErrorDeserializer(item: any): ResizeError { + return { + code: item["code"], + message: item["message"], + values: !item["values"] + ? item["values"] + : nameValuePairArrayDeserializer(item["values"]), + }; +} + +export function resizeErrorArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return resizeErrorDeserializer(item); + }); +} + /** The results and errors from an execution of a Pool autoscale formula. */ export interface AutoScaleRun { /** The time at which the autoscale formula was last evaluated. */ @@ -3622,6 +5844,16 @@ export interface AutoScaleRun { error?: AutoScaleRunError; } +export function autoScaleRunDeserializer(item: any): AutoScaleRun { + return { + timestamp: new Date(item["timestamp"]), + results: item["results"], + error: !item["error"] + ? item["error"] + : autoScaleRunErrorDeserializer(item["error"]), + }; +} + /** An error that occurred when executing or evaluating a Pool autoscale formula. */ export interface AutoScaleRunError { /** An identifier for the autoscale error. Codes are invariant and are intended to be consumed programmatically. */ @@ -3632,6 +5864,16 @@ export interface AutoScaleRunError { values?: NameValuePair[]; } +export function autoScaleRunErrorDeserializer(item: any): AutoScaleRunError { + return { + code: item["code"], + message: item["message"], + values: !item["values"] + ? item["values"] + : nameValuePairArrayDeserializer(item["values"]), + }; +} + /** Contains utilization and resource usage statistics for the lifetime of a Pool. */ export interface PoolStatistics { /** The URL for the statistics. */ @@ -3646,6 +5888,20 @@ export interface PoolStatistics { resourceStats?: ResourceStatistics; } +export function poolStatisticsDeserializer(item: any): PoolStatistics { + return { + url: item["url"], + startTime: new Date(item["startTime"]), + lastUpdateTime: new Date(item["lastUpdateTime"]), + usageStats: !item["usageStats"] + ? item["usageStats"] + : usageStatisticsDeserializer(item["usageStats"]), + resourceStats: !item["resourceStats"] + ? item["resourceStats"] + : resourceStatisticsDeserializer(item["resourceStats"]), + }; +} + /** Statistics related to Pool usage information. */ export interface UsageStatistics { /** The start time of the time range covered by the statistics. */ @@ -3656,6 +5912,14 @@ export interface UsageStatistics { dedicatedCoreTime: string; } +export function usageStatisticsDeserializer(item: any): UsageStatistics { + return { + startTime: new Date(item["startTime"]), + lastUpdateTime: new Date(item["lastUpdateTime"]), + dedicatedCoreTime: item["dedicatedCoreTime"], + }; +} + /** Statistics related to resource consumption by Compute Nodes in a Pool. */ export interface ResourceStatistics { /** The start time of the time range covered by the statistics. */ @@ -3686,6 +5950,24 @@ export interface ResourceStatistics { networkWriteGiB: number; } +export function resourceStatisticsDeserializer(item: any): ResourceStatistics { + return { + startTime: new Date(item["startTime"]), + lastUpdateTime: new Date(item["lastUpdateTime"]), + avgCpuPercentage: item["avgCPUPercentage"], + avgMemoryGiB: item["avgMemoryGiB"], + peakMemoryGiB: item["peakMemoryGiB"], + avgDiskGiB: item["avgDiskGiB"], + peakDiskGiB: item["peakDiskGiB"], + diskReadIOps: item["diskReadIOps"], + diskWriteIOps: item["diskWriteIOps"], + diskReadGiB: item["diskReadGiB"], + diskWriteGiB: item["diskWriteGiB"], + networkReadGiB: item["networkReadGiB"], + networkWriteGiB: item["networkWriteGiB"], + }; +} + /** The identity of the Batch pool, if configured. */ export interface BatchPoolIdentity { /** The identity of the Batch pool, if configured. The list of user identities associated with the Batch pool. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. */ @@ -3694,6 +5976,15 @@ export interface BatchPoolIdentity { userAssignedIdentities?: UserAssignedIdentity[]; } +export function batchPoolIdentityDeserializer(item: any): BatchPoolIdentity { + return { + type: item["type"], + userAssignedIdentities: !item["userAssignedIdentities"] + ? item["userAssignedIdentities"] + : userAssignedIdentityArrayDeserializer(item["userAssignedIdentities"]), + }; +} + /** PoolIdentityType enums */ export type PoolIdentityType = "UserAssigned" | "None"; @@ -3707,6 +5998,30 @@ export interface UserAssignedIdentity { readonly principalId?: string; } +export function userAssignedIdentityDeserializer( + item: any, +): UserAssignedIdentity { + return { + resourceId: item["resourceId"], + clientId: item["clientId"], + principalId: item["principalId"], + }; +} + +export function userAssignedIdentityArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return userAssignedIdentityDeserializer(item); + }); +} + +export function batchPoolArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return batchPoolDeserializer(item); + }); +} + /** Options for updating an Azure Batch Pool. */ export interface BatchPoolUpdateOptions { /** A Task to run on each Compute Node as it joins the Pool. The Task runs when the Compute Node is added to the Pool or when the Compute Node is restarted. If this element is present, it overwrites any existing StartTask. If omitted, any existing StartTask is left unchanged. */ @@ -3730,25 +6045,22 @@ export interface BatchPoolUpdateOptions { export function batchPoolUpdateOptionsSerializer( item: BatchPoolUpdateOptions, -): Record { - return { - startTask: !item.startTask - ? item.startTask - : startTaskSerializer(item.startTask), - certificateReferences: - item["certificateReferences"] === undefined - ? item["certificateReferences"] - : item["certificateReferences"].map(certificateReferenceSerializer), - applicationPackageReferences: - item["applicationPackageReferences"] === undefined - ? item["applicationPackageReferences"] - : item["applicationPackageReferences"].map( - applicationPackageReferenceSerializer, - ), - metadata: - item["metadata"] === undefined - ? item["metadata"] - : item["metadata"].map(metadataItemSerializer), +): any { + return { + startTask: !item["startTask"] + ? item["startTask"] + : startTaskSerializer(item["startTask"]), + certificateReferences: !item["certificateReferences"] + ? item["certificateReferences"] + : certificateReferenceArraySerializer(item["certificateReferences"]), + applicationPackageReferences: !item["applicationPackageReferences"] + ? item["applicationPackageReferences"] + : applicationPackageReferenceArraySerializer( + item["applicationPackageReferences"], + ), + metadata: !item["metadata"] + ? item["metadata"] + : metadataItemArraySerializer(item["metadata"]), targetNodeCommunicationMode: item["targetNodeCommunicationMode"], }; } @@ -3763,7 +6075,7 @@ export interface BatchPoolEnableAutoScaleOptions { export function batchPoolEnableAutoScaleOptionsSerializer( item: BatchPoolEnableAutoScaleOptions, -): Record { +): any { return { autoScaleFormula: item["autoScaleFormula"], autoScaleEvaluationInterval: item["autoScaleEvaluationInterval"], @@ -3778,10 +6090,8 @@ export interface BatchPoolEvaluateAutoScaleOptions { export function batchPoolEvaluateAutoScaleOptionsSerializer( item: BatchPoolEvaluateAutoScaleOptions, -): Record { - return { - autoScaleFormula: item["autoScaleFormula"], - }; +): any { + return { autoScaleFormula: item["autoScaleFormula"] }; } /** Options for changing the size of an Azure Batch Pool. */ @@ -3798,7 +6108,7 @@ export interface BatchPoolResizeOptions { export function batchPoolResizeOptionsSerializer( item: BatchPoolResizeOptions, -): Record { +): any { return { targetDedicatedNodes: item["targetDedicatedNodes"], targetLowPriorityNodes: item["targetLowPriorityNodes"], @@ -3837,18 +6147,18 @@ export interface BatchPoolReplaceOptions { export function batchPoolReplaceOptionsSerializer( item: BatchPoolReplaceOptions, -): Record { +): any { return { - startTask: !item.startTask - ? item.startTask - : startTaskSerializer(item.startTask), - certificateReferences: item["certificateReferences"].map( - certificateReferenceSerializer, + startTask: !item["startTask"] + ? item["startTask"] + : startTaskSerializer(item["startTask"]), + certificateReferences: certificateReferenceArraySerializer( + item["certificateReferences"], ), - applicationPackageReferences: item["applicationPackageReferences"].map( - applicationPackageReferenceSerializer, + applicationPackageReferences: applicationPackageReferenceArraySerializer( + item["applicationPackageReferences"], ), - metadata: item["metadata"].map(metadataItemSerializer), + metadata: metadataItemArraySerializer(item["metadata"]), targetNodeCommunicationMode: item["targetNodeCommunicationMode"], }; } @@ -3863,11 +6173,11 @@ export interface NodeRemoveOptions { nodeDeallocationOption?: BatchNodeDeallocationOption; } -export function nodeRemoveOptionsSerializer( - item: NodeRemoveOptions, -): Record { +export function nodeRemoveOptionsSerializer(item: NodeRemoveOptions): any { return { - nodeList: item["nodeList"], + nodeList: item["nodeList"].map((p: any) => { + return p; + }), resizeTimeout: item["resizeTimeout"], nodeDeallocationOption: item["nodeDeallocationOption"], }; @@ -3881,6 +6191,17 @@ export interface _ApplicationListResult { "odata.nextLink"?: string; } +export function _applicationListResultDeserializer( + item: any, +): _ApplicationListResult { + return { + value: !item["value"] + ? item["value"] + : batchApplicationArrayDeserializer(item["value"]), + "odata.nextLink": item["odata.nextLink"], + }; +} + /** Contains information about an application in an Azure Batch Account. */ export interface BatchApplication { /** A string that uniquely identifies the application within the Account. */ @@ -3891,5 +6212,20 @@ export interface BatchApplication { versions: string[]; } -/** The Azure Batch service version. */ -export type Versions = "2023-05-01.17.0"; +export function batchApplicationDeserializer(item: any): BatchApplication { + return { + id: item["id"], + displayName: item["displayName"], + versions: item["versions"].map((p: any) => { + return p; + }), + }; +} + +export function batchApplicationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return batchApplicationDeserializer(item); + }); +} diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/review/ai-chat-protocol.api.md b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/review/ai-chat-protocol.api.md index db193cafd8..a2d4b709b0 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/review/ai-chat-protocol.api.md +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/review/ai-chat-protocol.api.md @@ -10,9 +10,6 @@ import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; import { TokenCredential } from '@azure/core-auth'; -// @public -export type APIVersion = "2023-10-01-preview"; - // @public export interface ChatChoiceRecord { context?: Record; diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts index 3a4575a130..302e3e3730 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential, KeyCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { KeyCredential, TokenCredential } from "@azure/core-auth"; +/** Azure APIs for the Azure Chat protocol. */ export interface ChatProtocolContext extends Client {} /** Optional parameters for the client. */ diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/index.ts index a04957faff..22560e6770 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/index.ts @@ -7,3 +7,7 @@ export { ChatProtocolClientOptionalParams, } from "./chatProtocolContext.js"; export { createStreaming, create } from "./operations.js"; +export { + CreateStreamingOptionalParams, + CreateOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts index e5ca2514b7..c5dbadb244 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts @@ -2,24 +2,26 @@ // Licensed under the MIT License. import { - chatMessageSerializer, + ChatProtocolContext as Client, + CreateOptionalParams, + CreateStreamingOptionalParams, +} from "./index.js"; +import { StreamingChatCompletionOptionsRecord, + streamingChatCompletionOptionsRecordSerializer, ChatCompletionChunkRecord, + chatCompletionChunkRecordDeserializer, ChatCompletionOptionsRecord, + chatCompletionOptionsRecordSerializer, ChatCompletionRecord, + chatCompletionRecordDeserializer, } from "../models/models.js"; -import { ChatProtocolContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { serializeRecord } from "../helpers/serializerHelpers.js"; -import { - CreateStreamingOptionalParams, - CreateOptionalParams, -} from "../models/options.js"; export function _createStreamingSend( context: Client, @@ -30,14 +32,7 @@ export function _createStreamingSend( .path("/chat") .post({ ...operationOptionsToRequestParameters(options), - body: { - messages: body["messages"].map(chatMessageSerializer), - stream: body["stream"], - session_state: body["sessionState"], - context: !body.context - ? body.context - : (serializeRecord(body.context as any) as any), - }, + body: streamingChatCompletionOptionsRecordSerializer(body), }); } @@ -49,21 +44,7 @@ export async function _createStreamingDeserialize( throw createRestError(result); } - return { - choices: result.body["choices"].map((p: any) => { - return { - index: p["index"], - delta: { - content: p.delta["content"], - role: p.delta["role"], - sessionState: p.delta["session_state"], - }, - sessionState: p["session_state"], - context: p["context"], - finishReason: p["finish_reason"], - }; - }), - }; + return chatCompletionChunkRecordDeserializer(result.body); } /** Creates a new streaming chat completion. */ @@ -85,14 +66,7 @@ export function _createSend( .path("/chat") .post({ ...operationOptionsToRequestParameters(options), - body: { - messages: body["messages"].map(chatMessageSerializer), - stream: body["stream"], - session_state: body["sessionState"], - context: !body.context - ? body.context - : (serializeRecord(body.context as any) as any), - }, + body: chatCompletionOptionsRecordSerializer(body), }); } @@ -104,21 +78,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - choices: result.body["choices"].map((p: any) => { - return { - index: p["index"], - message: { - content: p.message["content"], - role: p.message["role"], - sessionState: p.message["session_state"], - }, - sessionState: p["session_state"], - context: p["context"], - finishReason: p["finish_reason"], - }; - }), - }; + return chatCompletionRecordDeserializer(result.body); } /** Creates a new chat completion. */ diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/chatProtocolClient.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/chatProtocolClient.ts index 1e444eb071..5cbfdccbd5 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/chatProtocolClient.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/chatProtocolClient.ts @@ -1,25 +1,23 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential, KeyCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; -import { - StreamingChatCompletionOptionsRecord, - ChatCompletionChunkRecord, - ChatCompletionOptionsRecord, - ChatCompletionRecord, -} from "./models/models.js"; -import { - CreateStreamingOptionalParams, - CreateOptionalParams, -} from "./models/options.js"; import { createChatProtocol, ChatProtocolContext, ChatProtocolClientOptionalParams, createStreaming, create, + CreateStreamingOptionalParams, + CreateOptionalParams, } from "./api/index.js"; +import { + StreamingChatCompletionOptionsRecord, + ChatCompletionChunkRecord, + ChatCompletionOptionsRecord, + ChatCompletionRecord, +} from "./models/models.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { KeyCredential, TokenCredential } from "@azure/core-auth"; export { ChatProtocolClientOptionalParams } from "./api/chatProtocolContext.js"; diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/index.ts index da775536fe..d487c082e0 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/index.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -export { - ChatProtocolClient, - ChatProtocolClientOptionalParams, -} from "./chatProtocolClient.js"; +export { ChatProtocolClient } from "./chatProtocolClient.js"; export { StreamingChatCompletionOptionsRecord, ChatMessage, @@ -16,7 +13,9 @@ export { ChatCompletionOptionsRecord, ChatCompletionRecord, ChatChoiceRecord, - APIVersion, +} from "./models/index.js"; +export { + ChatProtocolClientOptionalParams, CreateStreamingOptionalParams, CreateOptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/index.ts index cd036c824a..065271d212 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/index.ts @@ -12,9 +12,4 @@ export { ChatCompletionOptionsRecord, ChatCompletionRecord, ChatChoiceRecord, - APIVersion, } from "./models.js"; -export { - CreateStreamingOptionalParams, - CreateOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/models.ts index 554804afbb..09333b27d6 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/models.ts @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { serializeRecord } from "../helpers/serializerHelpers.js"; - /** The configuration for a streaming chat completion request. */ export interface StreamingChatCompletionOptionsRecord { /** The collection of context messages associated with this completion request. */ @@ -25,14 +23,12 @@ export interface StreamingChatCompletionOptionsRecord { export function streamingChatCompletionOptionsRecordSerializer( item: StreamingChatCompletionOptionsRecord, -): Record { +): any { return { - messages: item["messages"].map(chatMessageSerializer), + messages: chatMessageArraySerializer(item["messages"]), stream: item["stream"], session_state: item["sessionState"], - context: !item.context - ? item.context - : (serializeRecord(item.context as any) as any), + context: item["context"], }; } @@ -51,9 +47,7 @@ export interface ChatMessage { sessionState?: any; } -export function chatMessageSerializer( - item: ChatMessage, -): Record { +export function chatMessageSerializer(item: ChatMessage): any { return { content: item["content"], role: item["role"], @@ -61,15 +55,45 @@ export function chatMessageSerializer( }; } +export function chatMessageDeserializer(item: any): ChatMessage { + return { + content: item["content"], + role: item["role"], + sessionState: item["session_state"], + }; +} + /** A representation of the intended purpose of a message. */ export type ChatRole = "user" | "system" | "assistant"; +export function chatMessageArraySerializer(result: Array): any[] { + return result.map((item) => { + return chatMessageSerializer(item); + }); +} + +export function chatMessageArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return chatMessageDeserializer(item); + }); +} + /** A single response to a streaming completion request. */ export interface ChatCompletionChunkRecord { /** The collection of choice deltas received in this chunk. */ choices: ChoiceDeltaRecord[]; } +export function chatCompletionChunkRecordDeserializer( + item: any, +): ChatCompletionChunkRecord { + return { + choices: choiceDeltaRecordArrayDeserializer(item["choices"]), + }; +} + /** The representation of an incremental choice received in a streaming completion. */ export interface ChoiceDeltaRecord { /** The index of the of the chat choice, relative to the other choices in the same completion. */ @@ -92,6 +116,16 @@ export interface ChoiceDeltaRecord { finishReason?: FinishReason; } +export function choiceDeltaRecordDeserializer(item: any): ChoiceDeltaRecord { + return { + index: item["index"], + delta: chatMessageDeltaDeserializer(item["delta"]), + sessionState: item["session_state"], + context: item["context"], + finishReason: item["finish_reason"], + }; +} + /** The representation of a delta message received in a streaming completion. */ export interface ChatMessageDelta { /** An incremental part of the text associated with the message. */ @@ -107,9 +141,25 @@ export interface ChatMessageDelta { sessionState?: any; } +export function chatMessageDeltaDeserializer(item: any): ChatMessageDelta { + return { + content: item["content"], + role: item["role"], + sessionState: item["session_state"], + }; +} + /** Representation of the reason why a chat session has finished processing. */ export type FinishReason = "stop" | "length"; +export function choiceDeltaRecordArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return choiceDeltaRecordDeserializer(item); + }); +} + /** The configuration for a chat completion request. */ export interface ChatCompletionOptionsRecord { /** The collection of context messages associated with this completion request. */ @@ -132,14 +182,12 @@ export interface ChatCompletionOptionsRecord { export function chatCompletionOptionsRecordSerializer( item: ChatCompletionOptionsRecord, -): Record { +): any { return { - messages: item["messages"].map(chatMessageSerializer), + messages: chatMessageArraySerializer(item["messages"]), stream: item["stream"], session_state: item["sessionState"], - context: !item.context - ? item.context - : (serializeRecord(item.context as any) as any), + context: item["context"], }; } @@ -149,6 +197,14 @@ export interface ChatCompletionRecord { choices: ChatChoiceRecord[]; } +export function chatCompletionRecordDeserializer( + item: any, +): ChatCompletionRecord { + return { + choices: chatChoiceRecordArrayDeserializer(item["choices"]), + }; +} + /** The representation of a single generated completion. */ export interface ChatChoiceRecord { /** The index of the of the chat choice, relative to the other choices in the same completion. */ @@ -171,5 +227,20 @@ export interface ChatChoiceRecord { finishReason: FinishReason; } -/** Type of APIVersion */ -export type APIVersion = "2023-10-01-preview"; +export function chatChoiceRecordDeserializer(item: any): ChatChoiceRecord { + return { + index: item["index"], + message: chatMessageDeserializer(item["message"]), + sessionState: item["session_state"], + context: item["context"], + finishReason: item["finish_reason"], + }; +} + +export function chatChoiceRecordArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return chatChoiceRecordDeserializer(item); + }); +} diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md index d5edf61b20..9b2cbda61e 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md @@ -190,9 +190,6 @@ export interface TextBlocklistMatchResult { // @public export type TextCategory = "Hate" | "SelfHarm" | "Sexual" | "Violence"; -// @public -export type Versions = "2023-10-01"; - // (No @packageDocumentation comment for this package) ``` diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts index 14eeb6ece1..4ebd63ae7b 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential, KeyCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { KeyCredential, TokenCredential } from "@azure/core-auth"; +/** Analyze harmful content */ export interface ContentSafetyContext extends Client {} /** Optional parameters for the client. */ diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/index.ts index 5870f21c18..cfe55ac498 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/index.ts @@ -18,3 +18,15 @@ export { getTextBlocklistItem, listTextBlocklistItems, } from "./operations.js"; +export { + AnalyzeTextOptionalParams, + AnalyzeImageOptionalParams, + GetTextBlocklistOptionalParams, + CreateOrUpdateTextBlocklistOptionalParams, + DeleteTextBlocklistOptionalParams, + ListTextBlocklistsOptionalParams, + AddOrUpdateBlockItemsOptionalParams, + RemoveBlockItemsOptionalParams, + GetTextBlocklistItemOptionalParams, + ListTextBlocklistItemsOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts index 3d23058b4e..f92786355a 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts @@ -2,43 +2,53 @@ // Licensed under the MIT License. import { - textBlockItemInfoSerializer, - imageDataSerializer, + AddOrUpdateBlockItemsOptionalParams, + AnalyzeImageOptionalParams, + AnalyzeTextOptionalParams, + ContentSafetyContext as Client, + CreateOrUpdateTextBlocklistOptionalParams, + DeleteTextBlocklistOptionalParams, + GetTextBlocklistItemOptionalParams, + GetTextBlocklistOptionalParams, + ListTextBlocklistItemsOptionalParams, + ListTextBlocklistsOptionalParams, + RemoveBlockItemsOptionalParams, +} from "./index.js"; +import { TextBlocklist, + textBlocklistSerializer, + textBlocklistDeserializer, AddOrUpdateBlockItemsOptions, + addOrUpdateBlockItemsOptionsSerializer, AddOrUpdateBlockItemsResult, + addOrUpdateBlockItemsResultDeserializer, TextBlockItem, + textBlockItemDeserializer, RemoveBlockItemsOptions, + removeBlockItemsOptionsSerializer, AnalyzeImageOptions, + analyzeImageOptionsSerializer, AnalyzeImageResult, + analyzeImageResultDeserializer, AnalyzeTextOptions, + analyzeTextOptionsSerializer, AnalyzeTextResult, - _PagedTextBlockItem, + analyzeTextResultDeserializer, _PagedTextBlocklist, + _pagedTextBlocklistDeserializer, + _PagedTextBlockItem, + _pagedTextBlockItemDeserializer, } from "../models/models.js"; -import { ContentSafetyContext as Client } from "./index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../static-helpers/pagingHelpers.js"; import { - AnalyzeTextOptionalParams, - AnalyzeImageOptionalParams, - GetTextBlocklistOptionalParams, - CreateOrUpdateTextBlocklistOptionalParams, - DeleteTextBlocklistOptionalParams, - ListTextBlocklistsOptionalParams, - AddOrUpdateBlockItemsOptionalParams, - RemoveBlockItemsOptionalParams, - GetTextBlocklistItemOptionalParams, - ListTextBlocklistItemsOptionalParams, -} from "../models/options.js"; + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; export function _analyzeTextSend( context: Client, @@ -49,13 +59,7 @@ export function _analyzeTextSend( .path("/text:analyze") .post({ ...operationOptionsToRequestParameters(options), - body: { - text: body["text"], - categories: body["categories"], - blocklistNames: body["blocklistNames"], - breakByBlocklists: body["breakByBlocklists"], - outputType: body["outputType"], - }, + body: analyzeTextOptionsSerializer(body), }); } @@ -67,21 +71,7 @@ export async function _analyzeTextDeserialize( throw createRestError(result); } - return { - blocklistsMatchResults: - result.body["blocklistsMatchResults"] === undefined - ? result.body["blocklistsMatchResults"] - : result.body["blocklistsMatchResults"].map((p: any) => { - return { - blocklistName: p["blocklistName"], - blockItemId: p["blockItemId"], - blockItemText: p["blockItemText"], - }; - }), - analyzeResults: result.body["analyzeResults"].map((p: any) => { - return { category: p["category"], severity: p["severity"] }; - }), - }; + return analyzeTextResultDeserializer(result.body); } /** A sync API for harmful content analysis for text. Currently, we support four categories: Hate, SelfHarm, Sexual, Violence. */ @@ -103,11 +93,7 @@ export function _analyzeImageSend( .path("/image:analyze") .post({ ...operationOptionsToRequestParameters(options), - body: { - image: imageDataSerializer(body.image), - categories: body["categories"], - outputType: body["outputType"], - }, + body: analyzeImageOptionsSerializer(body), }); } @@ -119,11 +105,7 @@ export async function _analyzeImageDeserialize( throw createRestError(result); } - return { - analyzeResults: result.body["analyzeResults"].map((p: any) => { - return { category: p["category"], severity: p["severity"] }; - }), - }; + return analyzeImageResultDeserializer(result.body); } /** A sync API for harmful content analysis for image. Currently, we support four categories: Hate, SelfHarm, Sexual, Violence. */ @@ -154,10 +136,7 @@ export async function _getTextBlocklistDeserialize( throw createRestError(result); } - return { - blocklistName: result.body["blocklistName"], - description: result.body["description"], - }; + return textBlocklistDeserializer(result.body); } /** Returns text blocklist details. */ @@ -182,10 +161,7 @@ export function _createOrUpdateTextBlocklistSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { - blocklistName: resource["blocklistName"], - description: resource["description"], - }, + body: textBlocklistSerializer(resource), }); } @@ -197,10 +173,7 @@ export async function _createOrUpdateTextBlocklistDeserialize( throw createRestError(result); } - return { - blocklistName: result.body["blocklistName"], - description: result.body["description"], - }; + return textBlocklistDeserializer(result.body); } /** Updates a text blocklist, if blocklistName does not exist, create a new blocklist. */ @@ -271,15 +244,7 @@ export async function _listTextBlocklistsDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - blocklistName: p["blocklistName"], - description: p["description"], - }; - }), - nextLink: result.body["nextLink"], - }; + return _pagedTextBlocklistDeserializer(result.body); } /** Get all text blocklists details. */ @@ -309,7 +274,7 @@ export function _addOrUpdateBlockItemsSend( ) .post({ ...operationOptionsToRequestParameters(options), - body: { blockItems: body["blockItems"].map(textBlockItemInfoSerializer) }, + body: addOrUpdateBlockItemsOptionsSerializer(body), }); } @@ -321,18 +286,7 @@ export async function _addOrUpdateBlockItemsDeserialize( throw createRestError(result); } - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p: any) => { - return { - blockItemId: p["blockItemId"], - description: p["description"], - text: p["text"], - }; - }), - }; + return addOrUpdateBlockItemsResultDeserializer(result.body); } /** Add or update blockItems to a text blocklist. You can add or update at most 100 BlockItems in one request. */ @@ -361,7 +315,7 @@ export function _removeBlockItemsSend( .path("/text/blocklists/{blocklistName}:removeBlockItems", blocklistName) .post({ ...operationOptionsToRequestParameters(options), - body: { blockItemIds: body["blockItemIds"] }, + body: removeBlockItemsOptionsSerializer(body), }); } @@ -415,11 +369,7 @@ export async function _getTextBlocklistItemDeserialize( throw createRestError(result); } - return { - blockItemId: result.body["blockItemId"], - description: result.body["description"], - text: result.body["text"], - }; + return textBlockItemDeserializer(result.body); } /** Get blockItem By blockItemId from a text blocklist. */ @@ -463,16 +413,7 @@ export async function _listTextBlocklistItemsDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - blockItemId: p["blockItemId"], - description: p["description"], - text: p["text"], - }; - }), - nextLink: result.body["nextLink"], - }; + return _pagedTextBlockItemDeserializer(result.body); } /** Get all blockItems in a text blocklist */ diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/contentSafetyClient.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/contentSafetyClient.ts index ce54785dce..f5058f9951 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/contentSafetyClient.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/contentSafetyClient.ts @@ -1,31 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential, KeyCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; -import { - TextBlocklist, - AddOrUpdateBlockItemsOptions, - AddOrUpdateBlockItemsResult, - TextBlockItem, - RemoveBlockItemsOptions, - AnalyzeImageOptions, - AnalyzeImageResult, - AnalyzeTextOptions, - AnalyzeTextResult, -} from "./models/models.js"; -import { - AnalyzeTextOptionalParams, - AnalyzeImageOptionalParams, - GetTextBlocklistOptionalParams, - CreateOrUpdateTextBlocklistOptionalParams, - DeleteTextBlocklistOptionalParams, - ListTextBlocklistsOptionalParams, - AddOrUpdateBlockItemsOptionalParams, - RemoveBlockItemsOptionalParams, - GetTextBlocklistItemOptionalParams, - ListTextBlocklistItemsOptionalParams, -} from "./models/options.js"; import { createContentSafety, ContentSafetyContext, @@ -40,8 +15,31 @@ import { removeBlockItems, getTextBlocklistItem, listTextBlocklistItems, + AnalyzeTextOptionalParams, + AnalyzeImageOptionalParams, + GetTextBlocklistOptionalParams, + CreateOrUpdateTextBlocklistOptionalParams, + DeleteTextBlocklistOptionalParams, + ListTextBlocklistsOptionalParams, + AddOrUpdateBlockItemsOptionalParams, + RemoveBlockItemsOptionalParams, + GetTextBlocklistItemOptionalParams, + ListTextBlocklistItemsOptionalParams, } from "./api/index.js"; +import { + TextBlocklist, + AddOrUpdateBlockItemsOptions, + AddOrUpdateBlockItemsResult, + TextBlockItem, + RemoveBlockItemsOptions, + AnalyzeImageOptions, + AnalyzeImageResult, + AnalyzeTextOptions, + AnalyzeTextResult, +} from "./models/models.js"; import { PagedAsyncIterableIterator } from "./static-helpers/pagingHelpers.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { KeyCredential, TokenCredential } from "@azure/core-auth"; export { ContentSafetyClientOptionalParams } from "./api/contentSafetyContext.js"; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts index fce387fdca..bcb48c877d 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts @@ -7,10 +7,7 @@ import { PagedAsyncIterableIterator, } from "./static-helpers/pagingHelpers.js"; -export { - ContentSafetyClient, - ContentSafetyClientOptionalParams, -} from "./contentSafetyClient.js"; +export { ContentSafetyClient } from "./contentSafetyClient.js"; export { TextBlocklist, AddOrUpdateBlockItemsOptions, @@ -30,7 +27,9 @@ export { AnalyzeTextResult, TextBlocklistMatchResult, TextAnalyzeSeverityResult, - Versions, +} from "./models/index.js"; +export { + ContentSafetyClientOptionalParams, AnalyzeTextOptionalParams, AnalyzeImageOptionalParams, GetTextBlocklistOptionalParams, @@ -41,5 +40,5 @@ export { RemoveBlockItemsOptionalParams, GetTextBlocklistItemOptionalParams, ListTextBlocklistItemsOptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts index 5dde765c81..3d54f02cf1 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts @@ -20,17 +20,4 @@ export { AnalyzeTextResult, TextBlocklistMatchResult, TextAnalyzeSeverityResult, - Versions, } from "./models.js"; -export { - AnalyzeTextOptionalParams, - AnalyzeImageOptionalParams, - GetTextBlocklistOptionalParams, - CreateOrUpdateTextBlocklistOptionalParams, - DeleteTextBlocklistOptionalParams, - ListTextBlocklistsOptionalParams, - AddOrUpdateBlockItemsOptionalParams, - RemoveBlockItemsOptionalParams, - GetTextBlocklistItemOptionalParams, - ListTextBlocklistItemsOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/models.ts index a5f8bd0883..7630c3732f 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/models.ts @@ -11,9 +11,14 @@ export interface TextBlocklist { description?: string; } -export function textBlocklistSerializer( - item: TextBlocklist, -): Record { +export function textBlocklistSerializer(item: TextBlocklist): any { + return { + blocklistName: item["blocklistName"], + description: item["description"], + }; +} + +export function textBlocklistDeserializer(item: any): TextBlocklist { return { blocklistName: item["blocklistName"], description: item["description"], @@ -28,10 +33,8 @@ export interface AddOrUpdateBlockItemsOptions { export function addOrUpdateBlockItemsOptionsSerializer( item: AddOrUpdateBlockItemsOptions, -): Record { - return { - blockItems: item["blockItems"].map(textBlockItemInfoSerializer), - }; +): any { + return { blockItems: textBlockItemInfoArraySerializer(item["blockItems"]) }; } /** Block item info in text blocklist. */ @@ -42,13 +45,16 @@ export interface TextBlockItemInfo { text: string; } -export function textBlockItemInfoSerializer( - item: TextBlockItemInfo, -): Record { - return { - description: item["description"], - text: item["text"], - }; +export function textBlockItemInfoSerializer(item: TextBlockItemInfo): any { + return { description: item["description"], text: item["text"] }; +} + +export function textBlockItemInfoArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return textBlockItemInfoSerializer(item); + }); } /** The response of adding blockItems to text blocklist. */ @@ -57,6 +63,16 @@ export interface AddOrUpdateBlockItemsResult { value?: TextBlockItem[]; } +export function addOrUpdateBlockItemsResultDeserializer( + item: any, +): AddOrUpdateBlockItemsResult { + return { + value: !item["value"] + ? item["value"] + : textBlockItemArrayDeserializer(item["value"]), + }; +} + /** Item in TextBlocklist. */ export interface TextBlockItem { /** Block Item Id. It will be uuid. */ @@ -67,6 +83,22 @@ export interface TextBlockItem { text: string; } +export function textBlockItemDeserializer(item: any): TextBlockItem { + return { + blockItemId: item["blockItemId"], + description: item["description"], + text: item["text"], + }; +} + +export function textBlockItemArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return textBlockItemDeserializer(item); + }); +} + /** The request of removing blockItems from text blocklist. */ export interface RemoveBlockItemsOptions { /** Array of blockItemIds to remove. */ @@ -75,9 +107,11 @@ export interface RemoveBlockItemsOptions { export function removeBlockItemsOptionsSerializer( item: RemoveBlockItemsOptions, -): Record { +): any { return { - blockItemIds: item["blockItemIds"], + blockItemIds: item["blockItemIds"].map((p: any) => { + return p; + }), }; } @@ -91,12 +125,14 @@ export interface AnalyzeImageOptions { outputType?: AnalyzeImageOutputType; } -export function analyzeImageOptionsSerializer( - item: AnalyzeImageOptions, -): Record { +export function analyzeImageOptionsSerializer(item: AnalyzeImageOptions): any { return { - image: imageDataSerializer(item.image), - categories: item["categories"], + image: imageDataSerializer(item["image"]), + categories: !item["categories"] + ? item["categories"] + : item["categories"].map((p: any) => { + return p; + }), outputType: item["outputType"], }; } @@ -109,12 +145,11 @@ export interface ImageData { blobUrl?: string; } -export function imageDataSerializer(item: ImageData): Record { +export function imageDataSerializer(item: ImageData): any { return { - content: - item["content"] !== undefined - ? uint8ArrayToString(item["content"], "base64") - : undefined, + content: !item["content"] + ? item["content"] + : uint8ArrayToString(item["content"], "base64"), blobUrl: item["blobUrl"], }; } @@ -130,6 +165,14 @@ export interface AnalyzeImageResult { analyzeResults: ImageAnalyzeSeverityResult[]; } +export function analyzeImageResultDeserializer(item: any): AnalyzeImageResult { + return { + analyzeResults: imageAnalyzeSeverityResultArrayDeserializer( + item["analyzeResults"], + ), + }; +} + /** Image analysis result. */ export interface ImageAnalyzeSeverityResult { /** The image category. */ @@ -138,6 +181,23 @@ export interface ImageAnalyzeSeverityResult { severity?: number; } +export function imageAnalyzeSeverityResultDeserializer( + item: any, +): ImageAnalyzeSeverityResult { + return { + category: item["category"], + severity: item["severity"], + }; +} + +export function imageAnalyzeSeverityResultArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return imageAnalyzeSeverityResultDeserializer(item); + }); +} + /** The analysis request of the text. */ export interface AnalyzeTextOptions { /** The text needs to be scanned. We support at most 10k Unicode characters (unicode code points) in text of one request. */ @@ -152,13 +212,19 @@ export interface AnalyzeTextOptions { outputType?: AnalyzeTextOutputType; } -export function analyzeTextOptionsSerializer( - item: AnalyzeTextOptions, -): Record { +export function analyzeTextOptionsSerializer(item: AnalyzeTextOptions): any { return { text: item["text"], - categories: item["categories"], - blocklistNames: item["blocklistNames"], + categories: !item["categories"] + ? item["categories"] + : item["categories"].map((p: any) => { + return p; + }), + blocklistNames: !item["blocklistNames"] + ? item["blocklistNames"] + : item["blocklistNames"].map((p: any) => { + return p; + }), breakByBlocklists: item["breakByBlocklists"], outputType: item["outputType"], }; @@ -177,6 +243,19 @@ export interface AnalyzeTextResult { analyzeResults: TextAnalyzeSeverityResult[]; } +export function analyzeTextResultDeserializer(item: any): AnalyzeTextResult { + return { + blocklistsMatchResults: !item["blocklistsMatchResults"] + ? item["blocklistsMatchResults"] + : textBlocklistMatchResultArrayDeserializer( + item["blocklistsMatchResults"], + ), + analyzeResults: textAnalyzeSeverityResultArrayDeserializer( + item["analyzeResults"], + ), + }; +} + /** The result of blocklist match. */ export interface TextBlocklistMatchResult { /** The name of matched blocklist. */ @@ -187,6 +266,24 @@ export interface TextBlocklistMatchResult { blockItemText: string; } +export function textBlocklistMatchResultDeserializer( + item: any, +): TextBlocklistMatchResult { + return { + blocklistName: item["blocklistName"], + blockItemId: item["blockItemId"], + blockItemText: item["blockItemText"], + }; +} + +export function textBlocklistMatchResultArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return textBlocklistMatchResultDeserializer(item); + }); +} + /** Text analysis result. */ export interface TextAnalyzeSeverityResult { /** The text category. */ @@ -195,8 +292,22 @@ export interface TextAnalyzeSeverityResult { severity?: number; } -/** Type of Versions */ -export type Versions = "2023-10-01"; +export function textAnalyzeSeverityResultDeserializer( + item: any, +): TextAnalyzeSeverityResult { + return { + category: item["category"], + severity: item["severity"], + }; +} + +export function textAnalyzeSeverityResultArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return textAnalyzeSeverityResultDeserializer(item); + }); +} /** Paged collection of TextBlocklist items */ export interface _PagedTextBlocklist { @@ -206,6 +317,31 @@ export interface _PagedTextBlocklist { nextLink?: string; } +export function _pagedTextBlocklistDeserializer( + item: any, +): _PagedTextBlocklist { + return { + value: textBlocklistArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function textBlocklistArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return textBlocklistSerializer(item); + }); +} + +export function textBlocklistArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return textBlocklistDeserializer(item); + }); +} + /** Paged collection of TextBlockItem items */ export interface _PagedTextBlockItem { /** The TextBlockItem items on this page */ @@ -213,3 +349,12 @@ export interface _PagedTextBlockItem { /** The link to the next page of items */ nextLink?: string; } + +export function _pagedTextBlockItemDeserializer( + item: any, +): _PagedTextBlockItem { + return { + value: textBlockItemArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md index 8850d5d786..550d5ddce3 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md @@ -34,7 +34,7 @@ export interface BrokerProperties { // @public export interface CloudEvent { data?: any; - dataBase64?: Uint8Array; + data_base64?: Uint8Array; datacontenttype?: string; dataschema?: string; id: string; @@ -134,9 +134,6 @@ export interface ReleaseResult { succeededLockTokens: string[]; } -// @public -export type ServiceApiVersions = "2023-06-01-preview"; - // (No @packageDocumentation comment for this package) ``` diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts index 7939389ec4..efd351a77a 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { KeyCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { KeyCredential } from "@azure/core-auth"; +/** Azure Messaging EventGrid Client */ export interface EventGridContext extends Client {} /** Optional parameters for the client. */ diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/index.ts index 33683f6411..8a029ed362 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/index.ts @@ -14,3 +14,11 @@ export { releaseCloudEvents, rejectCloudEvents, } from "./operations.js"; +export { + PublishCloudEventOptionalParams, + PublishCloudEventsOptionalParams, + ReceiveCloudEventsOptionalParams, + AcknowledgeCloudEventsOptionalParams, + ReleaseCloudEventsOptionalParams, + RejectCloudEventsOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts index 1fd17cf0e5..8900f8484c 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts @@ -2,33 +2,41 @@ // Licensed under the MIT License. import { - cloudEventSerializer, + AcknowledgeCloudEventsOptionalParams, + EventGridContext as Client, + PublishCloudEventOptionalParams, + PublishCloudEventsOptionalParams, + ReceiveCloudEventsOptionalParams, + RejectCloudEventsOptionalParams, + ReleaseCloudEventsOptionalParams, +} from "./index.js"; +import { + _publishCloudEventRequestSerializer, CloudEvent, PublishResult, + publishResultDeserializer, ReceiveResult, + receiveResultDeserializer, AcknowledgeOptions, + acknowledgeOptionsSerializer, AcknowledgeResult, + acknowledgeResultDeserializer, ReleaseOptions, + releaseOptionsSerializer, ReleaseResult, + releaseResultDeserializer, RejectOptions, + rejectOptionsSerializer, RejectResult, + rejectResultDeserializer, + cloudEventArraySerializer, } from "../models/models.js"; -import { EventGridContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; -import { - PublishCloudEventOptionalParams, - PublishCloudEventsOptionalParams, - ReceiveCloudEventsOptionalParams, - AcknowledgeCloudEventsOptionalParams, - ReleaseCloudEventsOptionalParams, - RejectCloudEventsOptionalParams, -} from "../models/options.js"; export function _publishCloudEventSend( context: Client, @@ -43,7 +51,7 @@ export function _publishCloudEventSend( contentType: (options.contentType as any) ?? "application/cloudevents+json; charset=utf-8", - body: { event: cloudEventSerializer(event.event) }, + body: _publishCloudEventRequestSerializer(event), }); } @@ -55,7 +63,7 @@ export async function _publishCloudEventDeserialize( throw createRestError(result); } - return result.body; + return publishResultDeserializer(result.body); } /** Publish Single Cloud Event to namespace topic. In case of success, the server responds with an HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return various error codes. For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for internal server error. */ @@ -80,29 +88,15 @@ export function _publishCloudEventsSend( events: CloudEvent[], options: PublishCloudEventsOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/topics/{topicName}:publish", topicName).post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/cloudevents-batch+json; charset=utf-8", - body: (events ?? []).map((p) => { - return { - id: p["id"], - source: p["source"], - data: p["data"], - data_base64: - p["dataBase64"] !== undefined - ? uint8ArrayToString(p["dataBase64"], "base64") - : undefined, - type: p["type"], - time: p["time"]?.toISOString(), - specversion: p["specversion"], - dataschema: p["dataschema"], - datacontenttype: p["datacontenttype"], - subject: p["subject"], - }; - }), - }); + return context + .path("/topics/{topicName}:publish", topicName) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/cloudevents-batch+json; charset=utf-8", + body: cloudEventArraySerializer(events), + }); } export async function _publishCloudEventsDeserialize( @@ -113,7 +107,7 @@ export async function _publishCloudEventsDeserialize( throw createRestError(result); } - return result.body; + return publishResultDeserializer(result.body); } /** Publish Batch Cloud Event to namespace topic. In case of success, the server responds with an HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return various error codes. For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for internal server error. */ @@ -161,34 +155,7 @@ export async function _receiveCloudEventsDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - brokerProperties: { - lockToken: p.brokerProperties["lockToken"], - deliveryCount: p.brokerProperties["deliveryCount"], - }, - event: { - id: p.event["id"], - source: p.event["source"], - data: p.event["data"], - dataBase64: - typeof p.event["data_base64"] === "string" - ? stringToUint8Array(p.event["data_base64"], "base64") - : p.event["data_base64"], - type: p.event["type"], - time: - p.event["time"] !== undefined - ? new Date(p.event["time"]) - : undefined, - specversion: p.event["specversion"], - dataschema: p.event["dataschema"], - datacontenttype: p.event["datacontenttype"], - subject: p.event["subject"], - }, - }; - }), - }; + return receiveResultDeserializer(result.body); } /** Receive Batch of Cloud Events from the Event Subscription. */ @@ -224,7 +191,7 @@ export function _acknowledgeCloudEventsSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/json; charset=utf-8", - body: { lockTokens: lockTokens["lockTokens"] }, + body: acknowledgeOptionsSerializer(lockTokens), }); } @@ -236,16 +203,7 @@ export async function _acknowledgeCloudEventsDeserialize( throw createRestError(result); } - return { - failedLockTokens: result.body["failedLockTokens"].map((p: any) => { - return { - lockToken: p["lockToken"], - errorCode: p["errorCode"], - errorDescription: p["errorDescription"], - }; - }), - succeededLockTokens: result.body["succeededLockTokens"], - }; + return acknowledgeResultDeserializer(result.body); } /** Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if at least one event is successfully acknowledged. The response body will include the set of successfully acknowledged lockTokens, along with other failed lockTokens with their corresponding error information. Successfully acknowledged events will no longer be available to any consumer. */ @@ -283,7 +241,7 @@ export function _releaseCloudEventsSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/json; charset=utf-8", - body: { lockTokens: lockTokens["lockTokens"] }, + body: releaseOptionsSerializer(lockTokens), }); } @@ -295,16 +253,7 @@ export async function _releaseCloudEventsDeserialize( throw createRestError(result); } - return { - failedLockTokens: result.body["failedLockTokens"].map((p: any) => { - return { - lockToken: p["lockToken"], - errorCode: p["errorCode"], - errorDescription: p["errorDescription"], - }; - }), - succeededLockTokens: result.body["succeededLockTokens"], - }; + return releaseResultDeserializer(result.body); } /** Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one event is successfully released. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. */ @@ -342,7 +291,7 @@ export function _rejectCloudEventsSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/json; charset=utf-8", - body: { lockTokens: lockTokens["lockTokens"] }, + body: rejectOptionsSerializer(lockTokens), }); } @@ -354,16 +303,7 @@ export async function _rejectCloudEventsDeserialize( throw createRestError(result); } - return { - failedLockTokens: result.body["failedLockTokens"].map((p: any) => { - return { - lockToken: p["lockToken"], - errorCode: p["errorCode"], - errorDescription: p["errorDescription"], - }; - }), - succeededLockTokens: result.body["succeededLockTokens"], - }; + return rejectResultDeserializer(result.body); } /** Reject batch of Cloud Events. */ diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/eventGridClient.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/eventGridClient.ts index 13ef8419b3..7d592898d0 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/eventGridClient.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/eventGridClient.ts @@ -1,27 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { KeyCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; -import { - CloudEvent, - PublishResult, - ReceiveResult, - AcknowledgeOptions, - AcknowledgeResult, - ReleaseOptions, - ReleaseResult, - RejectOptions, - RejectResult, -} from "./models/models.js"; -import { - PublishCloudEventOptionalParams, - PublishCloudEventsOptionalParams, - ReceiveCloudEventsOptionalParams, - AcknowledgeCloudEventsOptionalParams, - ReleaseCloudEventsOptionalParams, - RejectCloudEventsOptionalParams, -} from "./models/options.js"; import { createEventGrid, EventGridContext, @@ -32,7 +11,26 @@ import { acknowledgeCloudEvents, releaseCloudEvents, rejectCloudEvents, + PublishCloudEventOptionalParams, + PublishCloudEventsOptionalParams, + ReceiveCloudEventsOptionalParams, + AcknowledgeCloudEventsOptionalParams, + ReleaseCloudEventsOptionalParams, + RejectCloudEventsOptionalParams, } from "./api/index.js"; +import { + CloudEvent, + PublishResult, + ReceiveResult, + AcknowledgeOptions, + AcknowledgeResult, + ReleaseOptions, + ReleaseResult, + RejectOptions, + RejectResult, +} from "./models/models.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { KeyCredential } from "@azure/core-auth"; export { EventGridClientOptionalParams } from "./api/eventGridContext.js"; diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/index.ts index 4cfc608ea5..dc45a8e0af 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/index.ts @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -export { - EventGridClient, - EventGridClientOptionalParams, -} from "./eventGridClient.js"; +export { EventGridClient } from "./eventGridClient.js"; export { CloudEvent, PublishResult, @@ -18,11 +15,13 @@ export { ReleaseResult, RejectOptions, RejectResult, - ServiceApiVersions, +} from "./models/index.js"; +export { + EventGridClientOptionalParams, PublishCloudEventOptionalParams, PublishCloudEventsOptionalParams, ReceiveCloudEventsOptionalParams, AcknowledgeCloudEventsOptionalParams, ReleaseCloudEventsOptionalParams, RejectCloudEventsOptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/index.ts index 884ecab0b4..d0b50697f9 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/index.ts @@ -14,13 +14,4 @@ export { ReleaseResult, RejectOptions, RejectResult, - ServiceApiVersions, } from "./models.js"; -export { - PublishCloudEventOptionalParams, - PublishCloudEventsOptionalParams, - ReceiveCloudEventsOptionalParams, - AcknowledgeCloudEventsOptionalParams, - ReleaseCloudEventsOptionalParams, - RejectCloudEventsOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts index 6ef94f2ca9..9fe0d417f7 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts @@ -1,7 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { uint8ArrayToString } from "@azure/core-util"; +import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; + +/** model interface _PublishCloudEventRequest */ +export interface _PublishCloudEventRequest { + event: CloudEvent; +} + +export function _publishCloudEventRequestSerializer( + item: _PublishCloudEventRequest, +): any { + return { event: cloudEventSerializer(item["event"]) }; +} /** Properties of an event published to an Azure Messaging EventGrid Namespace topic using the CloudEvent 1.0 Schema. */ export interface CloudEvent { @@ -12,7 +23,7 @@ export interface CloudEvent { /** Event data specific to the event type. */ data?: any; /** Event data specific to the event type, encoded as a base64 string. */ - dataBase64?: Uint8Array; + data_base64?: Uint8Array; /** Type of event related to the originating occurrence. */ type: string; /** The time (in UTC) the event was generated, in RFC3339 format. */ @@ -27,17 +38,14 @@ export interface CloudEvent { subject?: string; } -export function cloudEventSerializer( - item: CloudEvent, -): Record { +export function cloudEventSerializer(item: CloudEvent): any { return { id: item["id"], source: item["source"], data: item["data"], - data_base64: - item["dataBase64"] !== undefined - ? uint8ArrayToString(item["dataBase64"], "base64") - : undefined, + data_base64: !item["data_base64"] + ? item["data_base64"] + : uint8ArrayToString(item["data_base64"], "base64"), type: item["type"], time: item["time"]?.toISOString(), specversion: item["specversion"], @@ -47,15 +55,44 @@ export function cloudEventSerializer( }; } +export function cloudEventDeserializer(item: any): CloudEvent { + return { + id: item["id"], + source: item["source"], + data: item["data"], + data_base64: !item["data_base64"] + ? item["data_base64"] + : typeof item["data_base64"] === "string" + ? stringToUint8Array(item["data_base64"], "base64") + : item["data_base64"], + type: item["type"], + time: !item["time"] ? item["time"] : new Date(item["time"]), + specversion: item["specversion"], + dataschema: item["dataschema"], + datacontenttype: item["datacontenttype"], + subject: item["subject"], + }; +} + /** The result of the Publish operation. */ export interface PublishResult {} +export function publishResultDeserializer(item: any): PublishResult { + return item as any; +} + /** Details of the Receive operation response. */ export interface ReceiveResult { /** Array of receive responses, one per cloud event. */ value: ReceiveDetails[]; } +export function receiveResultDeserializer(item: any): ReceiveResult { + return { + value: receiveDetailsArrayDeserializer(item["value"]), + }; +} + /** Receive operation details per Cloud Event. */ export interface ReceiveDetails { /** The Event Broker details. */ @@ -64,6 +101,13 @@ export interface ReceiveDetails { event: CloudEvent; } +export function receiveDetailsDeserializer(item: any): ReceiveDetails { + return { + brokerProperties: brokerPropertiesDeserializer(item["brokerProperties"]), + event: cloudEventDeserializer(item["event"]), + }; +} + /** Properties of the Event Broker operation. */ export interface BrokerProperties { /** The token used to lock the event. */ @@ -72,17 +116,32 @@ export interface BrokerProperties { deliveryCount: number; } +export function brokerPropertiesDeserializer(item: any): BrokerProperties { + return { + lockToken: item["lockToken"], + deliveryCount: item["deliveryCount"], + }; +} + +export function receiveDetailsArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return receiveDetailsDeserializer(item); + }); +} + /** Array of lock token strings for the corresponding received Cloud Events to be acknowledged. */ export interface AcknowledgeOptions { /** String array of lock tokens. */ lockTokens: string[]; } -export function acknowledgeOptionsSerializer( - item: AcknowledgeOptions, -): Record { +export function acknowledgeOptionsSerializer(item: AcknowledgeOptions): any { return { - lockTokens: item["lockTokens"], + lockTokens: item["lockTokens"].map((p: any) => { + return p; + }), }; } @@ -94,6 +153,17 @@ export interface AcknowledgeResult { succeededLockTokens: string[]; } +export function acknowledgeResultDeserializer(item: any): AcknowledgeResult { + return { + failedLockTokens: failedLockTokenArrayDeserializer( + item["failedLockTokens"], + ), + succeededLockTokens: item["succeededLockTokens"].map((p: any) => { + return p; + }), + }; +} + /** Failed LockToken information. */ export interface FailedLockToken { /** LockToken value */ @@ -104,17 +174,33 @@ export interface FailedLockToken { errorDescription: string; } +export function failedLockTokenDeserializer(item: any): FailedLockToken { + return { + lockToken: item["lockToken"], + errorCode: item["errorCode"], + errorDescription: item["errorDescription"], + }; +} + +export function failedLockTokenArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return failedLockTokenDeserializer(item); + }); +} + /** Array of lock token strings for the corresponding received Cloud Events to be released. */ export interface ReleaseOptions { /** String array of lock tokens. */ lockTokens: string[]; } -export function releaseOptionsSerializer( - item: ReleaseOptions, -): Record { +export function releaseOptionsSerializer(item: ReleaseOptions): any { return { - lockTokens: item["lockTokens"], + lockTokens: item["lockTokens"].map((p: any) => { + return p; + }), }; } @@ -126,17 +212,28 @@ export interface ReleaseResult { succeededLockTokens: string[]; } +export function releaseResultDeserializer(item: any): ReleaseResult { + return { + failedLockTokens: failedLockTokenArrayDeserializer( + item["failedLockTokens"], + ), + succeededLockTokens: item["succeededLockTokens"].map((p: any) => { + return p; + }), + }; +} + /** Array of lock token strings for the corresponding received Cloud Events to be rejected. */ export interface RejectOptions { /** String array of lock tokens. */ lockTokens: string[]; } -export function rejectOptionsSerializer( - item: RejectOptions, -): Record { +export function rejectOptionsSerializer(item: RejectOptions): any { return { - lockTokens: item["lockTokens"], + lockTokens: item["lockTokens"].map((p: any) => { + return p; + }), }; } @@ -148,5 +245,25 @@ export interface RejectResult { succeededLockTokens: string[]; } -/** Type of ServiceApiVersions */ -export type ServiceApiVersions = "2023-06-01-preview"; +export function rejectResultDeserializer(item: any): RejectResult { + return { + failedLockTokens: failedLockTokenArrayDeserializer( + item["failedLockTokens"], + ), + succeededLockTokens: item["succeededLockTokens"].map((p: any) => { + return p; + }), + }; +} + +export function cloudEventArraySerializer(result: Array): any[] { + return result.map((item) => { + return cloudEventSerializer(item); + }); +} + +export function cloudEventArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return cloudEventDeserializer(item); + }); +} diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/review/hierarchy-generic.api.md b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/review/hierarchy-generic.api.md index 06ebb0931f..3f86be7cf8 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/review/hierarchy-generic.api.md +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/review/hierarchy-generic.api.md @@ -8,14 +8,14 @@ import { ClientOptions } from '@azure-rest/core-client'; import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; -// @public (undocumented) +// @public export interface A { // (undocumented) prop1: string; } -// @public (undocumented) -export interface BA { +// @public +export interface Ba { // (undocumented) prop2: string; } @@ -27,11 +27,11 @@ export interface BCOp1OptionalParams extends OperationOptions { // @public export interface BCOperations { // (undocumented) - op1: (body: BA, options?: BCOp1OptionalParams) => Promise; + op1: (body: Ba, options?: BCOp1OptionalParams) => Promise; } -// @public (undocumented) -export interface BEA { +// @public +export interface Bea { // (undocumented) prop3: string; } @@ -43,7 +43,7 @@ export interface BECOp1OptionalParams extends OperationOptions { // @public export interface BECOperations { // (undocumented) - op1: (body: BEA, options?: BECOp1OptionalParams) => Promise; + op1: (body: Bea, options?: BECOp1OptionalParams) => Promise; } // @public @@ -63,7 +63,7 @@ export interface BOperations { // (undocumented) e: BEOperations; // (undocumented) - op1: (body: BA, options?: BOp1OptionalParams) => Promise; + op1: (body: Ba, options?: BOp1OptionalParams) => Promise; } // @public @@ -78,7 +78,7 @@ export interface DOperations { // @public (undocumented) export class FooClient { - constructor(endpoint: string, options?: FooClientOptionalParams); + constructor(endpointParam: string, options?: FooClientOptionalParams); readonly b: BOperations; readonly d: DOperations; // (undocumented) diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/c/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/c/index.ts index 11bccd9524..ed37ae2eb6 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/c/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/c/index.ts @@ -1,26 +1,25 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { BA } from "../../../models/models.js"; -import { FooContext as Client } from "../../index.js"; +import { BCOp1OptionalParams, FooContext as Client } from "../../index.js"; +import { Ba, baSerializer } from "../../../models/models.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { BCOp1OptionalParams } from "../../../models/options.js"; export function _op1Send( context: Client, - body: BA, + body: Ba, options: BCOp1OptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/b/c") .post({ ...operationOptionsToRequestParameters(options), - body: { prop2: body["prop2"] }, + body: baSerializer(body), }); } @@ -37,7 +36,7 @@ export async function _op1Deserialize( export async function op1( context: Client, - body: BA, + body: Ba, options: BCOp1OptionalParams = { requestOptions: {} }, ): Promise { const result = await _op1Send(context, body, options); diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/e/c/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/e/c/index.ts index ccb5986300..5ce947d93f 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/e/c/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/e/c/index.ts @@ -1,26 +1,25 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { BEA } from "../../../../models/models.js"; -import { FooContext as Client } from "../../../index.js"; +import { BECOp1OptionalParams, FooContext as Client } from "../../../index.js"; +import { Bea, beaSerializer } from "../../../../models/models.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { BECOp1OptionalParams } from "../../../../models/options.js"; export function _op1Send( context: Client, - body: BEA, + body: Bea, options: BECOp1OptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/b/e") .post({ ...operationOptionsToRequestParameters(options), - body: { prop3: body["prop3"] }, + body: beaSerializer(body), }); } @@ -37,7 +36,7 @@ export async function _op1Deserialize( export async function op1( context: Client, - body: BEA, + body: Bea, options: BECOp1OptionalParams = { requestOptions: {} }, ): Promise { const result = await _op1Send(context, body, options); diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/index.ts index 424e29f195..2a52876fa2 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/index.ts @@ -1,26 +1,25 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { BA } from "../../models/models.js"; -import { FooContext as Client } from "../index.js"; +import { BOp1OptionalParams, FooContext as Client } from "../index.js"; +import { Ba, baSerializer } from "../../models/models.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { BOp1OptionalParams } from "../../models/options.js"; export function _op1Send( context: Client, - body: BA, + body: Ba, options: BOp1OptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/b") .post({ ...operationOptionsToRequestParameters(options), - body: { prop2: body["prop2"] }, + body: baSerializer(body), }); } @@ -37,7 +36,7 @@ export async function _op1Deserialize( export async function op1( context: Client, - body: BA, + body: Ba, options: BOp1OptionalParams = { requestOptions: {} }, ): Promise { const result = await _op1Send(context, body, options); diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/d/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/d/index.ts index db0448c804..88a9c3c693 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/d/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/d/index.ts @@ -1,15 +1,14 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { A } from "../../models/models.js"; -import { FooContext as Client } from "../index.js"; +import { FooContext as Client, DOp1OptionalParams } from "../index.js"; +import { A, aSerializer } from "../../models/models.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { DOp1OptionalParams } from "../../models/options.js"; export function _op1Send( context: Client, @@ -20,7 +19,7 @@ export function _op1Send( .path("/d") .post({ ...operationOptionsToRequestParameters(options), - body: { prop1: body["prop1"] }, + body: aSerializer(body), }); } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts index af40f3b415..4c1e9ad738 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts @@ -1,8 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; export interface FooContext extends Client {} @@ -10,7 +10,7 @@ export interface FooContext extends Client {} export interface FooClientOptionalParams extends ClientOptions {} export function createFoo( - endpoint: string, + endpointParam: string, options: FooClientOptionalParams = {}, ): FooContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; @@ -23,7 +23,7 @@ export function createFoo( loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, }; const clientContext = getClient( - options.endpoint ?? options.baseUrl ?? endpoint, + options.endpoint ?? options.baseUrl ?? String(endpointParam), undefined, updatedOptions, ); diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/index.ts index e7070405bd..f65f356c47 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/index.ts @@ -7,3 +7,10 @@ export { FooClientOptionalParams, } from "./fooContext.js"; export { op1 } from "./operations.js"; +export { + Op1OptionalParams, + BOp1OptionalParams, + BECOp1OptionalParams, + BCOp1OptionalParams, + DOp1OptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/operations.ts index 2f533ce147..158936ffaa 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/operations.ts @@ -1,15 +1,14 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { A } from "../models/models.js"; -import { FooContext as Client } from "./index.js"; +import { FooContext as Client, Op1OptionalParams } from "./index.js"; +import { A, aSerializer } from "../models/models.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { Op1OptionalParams } from "../models/options.js"; export function _op1Send( context: Client, @@ -20,7 +19,7 @@ export function _op1Send( .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { prop1: body["prop1"] }, + body: aSerializer(body), }); } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/c/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/c/index.ts index 1bc96ac420..282ab4aac9 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/c/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/c/index.ts @@ -2,18 +2,18 @@ // Licensed under the MIT License. import { FooContext } from "../../../api/fooContext.js"; -import { BA } from "../../../models/models.js"; import { op1 } from "../../../api/b/c/index.js"; -import { BCOp1OptionalParams } from "../../../models/options.js"; +import { BCOp1OptionalParams } from "../../../api/options.js"; +import { Ba } from "../../../models/models.js"; /** Interface representing a BC operations. */ export interface BCOperations { - op1: (body: BA, options?: BCOp1OptionalParams) => Promise; + op1: (body: Ba, options?: BCOp1OptionalParams) => Promise; } export function getBC(context: FooContext) { return { - op1: (body: BA, options?: BCOp1OptionalParams) => + op1: (body: Ba, options?: BCOp1OptionalParams) => op1(context, body, options), }; } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/c/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/c/index.ts index 3ef8b76f45..2cafaaef56 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/c/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/c/index.ts @@ -2,18 +2,18 @@ // Licensed under the MIT License. import { FooContext } from "../../../../api/fooContext.js"; -import { BEA } from "../../../../models/models.js"; import { op1 } from "../../../../api/b/e/c/index.js"; -import { BECOp1OptionalParams } from "../../../../models/options.js"; +import { BECOp1OptionalParams } from "../../../../api/options.js"; +import { Bea } from "../../../../models/models.js"; /** Interface representing a BEC operations. */ export interface BECOperations { - op1: (body: BEA, options?: BECOp1OptionalParams) => Promise; + op1: (body: Bea, options?: BECOp1OptionalParams) => Promise; } export function getBEC(context: FooContext) { return { - op1: (body: BEA, options?: BECOp1OptionalParams) => + op1: (body: Bea, options?: BECOp1OptionalParams) => op1(context, body, options), }; } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts index a55bbcd711..4ed48d6010 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts @@ -2,22 +2,22 @@ // Licensed under the MIT License. import { FooContext } from "../../api/fooContext.js"; -import { BA } from "../../models/models.js"; import { op1 } from "../../api/b/index.js"; -import { BOp1OptionalParams } from "../../models/options.js"; +import { BOp1OptionalParams } from "../../api/options.js"; +import { Ba } from "../../models/models.js"; import { BCOperations, getBCOperations } from "./c/index.js"; import { BEOperations, getBEOperations } from "./e/index.js"; /** Interface representing a B operations. */ export interface BOperations { - op1: (body: BA, options?: BOp1OptionalParams) => Promise; + op1: (body: Ba, options?: BOp1OptionalParams) => Promise; e: BEOperations; c: BCOperations; } export function getB(context: FooContext) { return { - op1: (body: BA, options?: BOp1OptionalParams) => + op1: (body: Ba, options?: BOp1OptionalParams) => op1(context, body, options), }; } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/d/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/d/index.ts index 8456e2c39b..cd686d16b8 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/d/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/d/index.ts @@ -2,9 +2,9 @@ // Licensed under the MIT License. import { FooContext } from "../../api/fooContext.js"; -import { A } from "../../models/models.js"; import { op1 } from "../../api/d/index.js"; -import { DOp1OptionalParams } from "../../models/options.js"; +import { DOp1OptionalParams } from "../../api/options.js"; +import { A } from "../../models/models.js"; /** Interface representing a D operations. */ export interface DOperations { diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/fooClient.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/fooClient.ts index 365dee6566..e742f17afe 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/fooClient.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/fooClient.ts @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { Pipeline } from "@azure/core-rest-pipeline"; -import { A } from "./models/models.js"; -import { Op1OptionalParams } from "./models/options.js"; import { getBOperations, BOperations } from "./classic/b/index.js"; import { getDOperations, DOperations } from "./classic/d/index.js"; import { @@ -11,7 +8,10 @@ import { FooContext, FooClientOptionalParams, op1, + Op1OptionalParams, } from "./api/index.js"; +import { A } from "./models/models.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; export { FooClientOptionalParams } from "./api/fooContext.js"; @@ -20,12 +20,12 @@ export class FooClient { /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; - constructor(endpoint: string, options: FooClientOptionalParams = {}) { + constructor(endpointParam: string, options: FooClientOptionalParams = {}) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-client` : "azsdk-js-client"; - this._client = createFoo(endpoint, { + this._client = createFoo(endpointParam, { ...options, userAgentOptions: { userAgentPrefix }, }); diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/index.ts index fecc20e53d..f07da1513d 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/index.ts @@ -1,17 +1,16 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -export { FooClient, FooClientOptionalParams } from "./fooClient.js"; +export { FooClient } from "./fooClient.js"; +export { A, Ba, Bea } from "./models/index.js"; export { - A, - BA, - BEA, + FooClientOptionalParams, Op1OptionalParams, BOp1OptionalParams, BECOp1OptionalParams, BCOp1OptionalParams, DOp1OptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; export { BOperations, DOperations, diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/index.ts index fc2269f93b..8e00d409af 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/index.ts @@ -1,11 +1,4 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -export { A, BA, BEA } from "./models.js"; -export { - Op1OptionalParams, - BOp1OptionalParams, - BECOp1OptionalParams, - BCOp1OptionalParams, - DOp1OptionalParams, -} from "./options.js"; +export { A, Ba, Bea } from "./models.js"; diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/models.ts index 81bb471575..6ea4c3b715 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/models.ts @@ -1,32 +1,29 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +/** model interface A */ export interface A { prop1: string; } -export function aSerializer(item: A): Record { - return { - prop1: item["prop1"], - }; +export function aSerializer(item: A): any { + return { prop1: item["prop1"] }; } -export interface BA { +/** model interface Ba */ +export interface Ba { prop2: string; } -export function bASerializer(item: BA): Record { - return { - prop2: item["prop2"], - }; +export function baSerializer(item: Ba): any { + return { prop2: item["prop2"] }; } -export interface BEA { +/** model interface Bea */ +export interface Bea { prop3: string; } -export function bEASerializer(item: BEA): Record { - return { - prop3: item["prop3"], - }; +export function beaSerializer(item: Bea): any { + return { prop3: item["prop3"] }; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md index bb1a08decf..299398a678 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md @@ -12,9 +12,6 @@ import { TokenCredential } from '@azure/core-auth'; // @public export type AggregationType = string; -// @public -export type APIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; - // @public export interface AppComponent { displayName?: string; @@ -356,7 +353,7 @@ export interface ListMetricDefinitionsOptionalParams extends OperationOptions { // @public export interface ListMetricDimensionValuesOptionalParams extends OperationOptions { - interval?: LoadTestRunClientTimeGrain; + interval?: TimeGrain; } // @public @@ -366,7 +363,7 @@ export interface ListMetricNamespacesOptionalParams extends OperationOptions { // @public export interface ListMetricsOptionalParams extends OperationOptions { aggregation?: string; - interval?: LoadTestRunClientTimeGrain; + interval?: TimeGrain; } // @public @@ -451,63 +448,23 @@ export interface LoadTestConfiguration { // @public (undocumented) export class LoadTestRunClient { constructor(endpointParam: string, credential: TokenCredential, options?: LoadTestRunClientOptionalParams); - createOrUpdateAppComponents(testRunId: string, body: LoadTestRunClientTestRunAppComponents, options?: LoadTestRunClientCreateOrUpdateAppComponentsOptionalParams): Promise; - createOrUpdateServerMetricsConfig(testRunId: string, body: LoadTestRunClientTestRunServerMetricConfig, options?: LoadTestRunClientCreateOrUpdateServerMetricsConfigOptionalParams): Promise; - createOrUpdateTestRun(testRunId: string, body: LoadTestRunClientTestRun, options?: CreateOrUpdateTestRunOptionalParams): Promise; + createOrUpdateAppComponents(testRunId: string, body: TestRunAppComponents, options?: LoadTestRunClientCreateOrUpdateAppComponentsOptionalParams): Promise; + createOrUpdateServerMetricsConfig(testRunId: string, body: TestRunServerMetricConfig, options?: LoadTestRunClientCreateOrUpdateServerMetricsConfigOptionalParams): Promise; + createOrUpdateTestRun(testRunId: string, body: TestRun, options?: CreateOrUpdateTestRunOptionalParams): Promise; deleteTestRun(testRunId: string, options?: DeleteTestRunOptionalParams): Promise; - getAppComponents(testRunId: string, options?: LoadTestRunClientGetAppComponentsOptionalParams): Promise; - getServerMetricsConfig(testRunId: string, options?: LoadTestRunClientGetServerMetricsConfigOptionalParams): Promise; - getTestRun(testRunId: string, options?: GetTestRunOptionalParams): Promise; - getTestRunFile(testRunId: string, fileName: string, options?: GetTestRunFileOptionalParams): Promise; - listMetricDefinitions(testRunId: string, metricNamespace: string, options?: ListMetricDefinitionsOptionalParams): Promise; - listMetricDimensionValues(testRunId: string, name: string, metricname: string, metricNamespace: string, timespan: string, options?: ListMetricDimensionValuesOptionalParams): Promise; - listMetricNamespaces(testRunId: string, options?: ListMetricNamespacesOptionalParams): Promise; - listMetrics(testRunId: string, metricname: string, metricNamespace: string, timespan: string, body?: LoadTestRunClientMetricRequestPayload, options?: ListMetricsOptionalParams): PagedAsyncIterableIterator; - listTestRuns(options?: ListTestRunsOptionalParams): PagedAsyncIterableIterator; + getAppComponents(testRunId: string, options?: LoadTestRunClientGetAppComponentsOptionalParams): Promise; + getServerMetricsConfig(testRunId: string, options?: LoadTestRunClientGetServerMetricsConfigOptionalParams): Promise; + getTestRun(testRunId: string, options?: GetTestRunOptionalParams): Promise; + getTestRunFile(testRunId: string, fileName: string, options?: GetTestRunFileOptionalParams): Promise; + listMetricDefinitions(testRunId: string, metricNamespace: string, options?: ListMetricDefinitionsOptionalParams): Promise; + listMetricDimensionValues(testRunId: string, name: string, metricname: string, metricNamespace: string, timespan: string, options?: ListMetricDimensionValuesOptionalParams): Promise; + listMetricNamespaces(testRunId: string, options?: ListMetricNamespacesOptionalParams): Promise; + listMetrics(testRunId: string, metricname: string, metricNamespace: string, timespan: string, body?: MetricRequestPayload, options?: ListMetricsOptionalParams): PagedAsyncIterableIterator; + listTestRuns(options?: ListTestRunsOptionalParams): PagedAsyncIterableIterator; readonly pipeline: Pipeline; - stopTestRun(testRunId: string, options?: StopTestRunOptionalParams): Promise; -} - -// @public -export type LoadTestRunClientAggregationType = string; - -// @public -export type LoadTestRunClientAPIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; - -// @public -export interface LoadTestRunClientAppComponent { - displayName?: string; - kind?: string; - readonly resourceGroup?: string; - readonly resourceId: string; - resourceName: string; - resourceType: string; - readonly subscriptionId?: string; -} - -// @public -export interface LoadTestRunClientArtifactsContainerInfo { - expireDateTime?: Date; - url?: string; -} - -// @public -export interface LoadTestRunClientAutoStopCriteria { - autoStopDisabled?: boolean; - errorRate?: number; - errorRateTimeWindowInSeconds?: number; -} - -// @public -export interface LoadTestRunClientCertificateMetadata { - name?: string; - type?: LoadTestRunClientCertificateType; - value?: string; + stopTestRun(testRunId: string, options?: StopTestRunOptionalParams): Promise; } -// @public -export type LoadTestRunClientCertificateType = string; - // @public export interface LoadTestRunClientCreateOrUpdateAppComponentsOptionalParams extends OperationOptions { contentType?: string; @@ -519,1982 +476,207 @@ export interface LoadTestRunClientCreateOrUpdateServerMetricsConfigOptionalParam } // @public -export interface LoadTestRunClientDimensionFilter { - name?: string; - values?: string[]; +export interface LoadTestRunClientGetAppComponentsOptionalParams extends OperationOptions { } // @public -export interface LoadTestRunClientDimensionValue { - name?: string; - value?: string; +export interface LoadTestRunClientGetServerMetricsConfigOptionalParams extends OperationOptions { } // @public -export interface LoadTestRunClientDimensionValueList { - readonly name?: string; - nextLink?: string; - value?: string[]; +export interface LoadTestRunClientOptionalParams extends ClientOptions { + apiVersion?: string; } // @public -export interface LoadTestRunClientErrorDetails { - readonly message?: string; +export interface MetricAvailability { + timeGrain?: TimeGrain; } // @public -export type LoadTestRunClientFileStatus = string; - -// @public -export type LoadTestRunClientFileType = string; - -// @public -export interface LoadTestRunClientFunctionFlexConsumptionResourceConfiguration { - httpConcurrency: number; - instanceMemoryMB: number; +export interface MetricDefinition { + description?: string; + dimensions?: NameAndDesc[]; + metricAvailabilities?: MetricAvailability[]; + name?: string; + namespace?: string; + primaryAggregationType?: AggregationType; + supportedAggregationTypes?: string[]; + unit?: MetricUnit; } // @public -export interface LoadTestRunClientFunctionFlexConsumptionTargetResourceConfigurations extends LoadTestRunClientTargetResourceConfigurations { - configurations?: Record; - kind: "FunctionsFlexConsumption"; +export interface MetricDefinitionCollection { + value: MetricDefinition[]; } // @public -export interface LoadTestRunClientGetAppComponentsOptionalParams extends OperationOptions { +export interface MetricNamespace { + description?: string; + name?: string; } // @public -export interface LoadTestRunClientGetServerMetricsConfigOptionalParams extends OperationOptions { +export interface MetricNamespaceCollection { + value: MetricNamespace[]; } // @public -export enum LoadTestRunClientKnownAggregationType { - Average = "Average", - Count = "Count", - None = "None", - Percentile75 = "Percentile75", - Percentile90 = "Percentile90", - Percentile95 = "Percentile95", - Percentile96 = "Percentile96", - Percentile97 = "Percentile97", - Percentile98 = "Percentile98", - Percentile99 = "Percentile99", - Percentile999 = "Percentile999", - Percentile9999 = "Percentile9999", - Total = "Total" +export interface MetricRequestPayload { + filters?: DimensionFilter[]; } // @public -export enum LoadTestRunClientKnownCertificateType { - AKV_CERT_URI = "AKV_CERT_URI" -} +export type MetricUnit = string; // @public -export enum LoadTestRunClientKnownFileStatus { - NOT_VALIDATED = "NOT_VALIDATED", - VALIDATION_FAILURE = "VALIDATION_FAILURE", - VALIDATION_INITIATED = "VALIDATION_INITIATED", - VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", - VALIDATION_SUCCESS = "VALIDATION_SUCCESS" +export interface MetricValue { + timestamp?: Date; + value?: number; } // @public -export enum LoadTestRunClientKnownFileType { - ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", - JMX_FILE = "JMX_FILE", - TEST_SCRIPT = "TEST_SCRIPT", - URL_TEST_CONFIG = "URL_TEST_CONFIG", - USER_PROPERTIES = "USER_PROPERTIES", - ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS" +export interface NameAndDesc { + description?: string; + name?: string; } // @public -export enum LoadTestRunClientKnownMetricUnit { - Bytes = "Bytes", - BytesPerSecond = "BytesPerSecond", - Count = "Count", - CountPerSecond = "CountPerSecond", - Milliseconds = "Milliseconds", - NotSpecified = "NotSpecified", - Percent = "Percent", - Seconds = "Seconds" +export interface OptionalLoadTestConfig { + duration?: number; + endpointUrl?: string; + maxResponseTimeInMs?: number; + rampUpTime?: number; + requestsPerSecond?: number; + virtualUsers?: number; } // @public -export enum LoadTestRunClientKnownPFAction { - "continue" = "continue", - stop = "stop" +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; + next(): Promise>; } // @public -export enum LoadTestRunClientKnownPFAgFunc { - "p99.9" = "p99.9", - "p99.99" = "p99.99", - avg = "avg", - count = "count", - max = "max", - min = "min", - p50 = "p50", - p75 = "p75", - p90 = "p90", - p95 = "p95", - p96 = "p96", - p97 = "p97", - p98 = "p98", - p99 = "p99", - percentage = "percentage" +export interface PageSettings { + continuationToken?: string; } // @public -export enum LoadTestRunClientKnownPFMetrics { - error = "error", - latency = "latency", - requests = "requests", - requests_per_sec = "requests_per_sec", - response_time_ms = "response_time_ms" +export interface PassFailCriteria { + passFailMetrics?: Record; } // @public -export enum LoadTestRunClientKnownPFResult { - failed = "failed", - passed = "passed", - undetermined = "undetermined" +export interface PassFailMetric { + action?: PFAction; + readonly actualValue?: number; + aggregate?: PFAgFunc; + clientMetric?: PFMetrics; + condition?: string; + requestName?: string; + readonly result?: PFResult; + value?: number; } // @public -export enum LoadTestRunClientKnownPFTestResult { - FAILED = "FAILED", - NOT_APPLICABLE = "NOT_APPLICABLE", - PASSED = "PASSED" -} +export type PFAction = string; // @public -export enum LoadTestRunClientKnownRecommendationCategory { - CostOptimized = "CostOptimized", - ThroughputOptimized = "ThroughputOptimized" -} +export type PFAgFunc = string; // @public -export enum LoadTestRunClientKnownRequestDataLevel { - ERRORS = "ERRORS", - NONE = "NONE" -} +export type PFMetrics = string; // @public -export enum LoadTestRunClientKnownResourceKind { - FunctionsFlexConsumption = "FunctionsFlexConsumption" -} +export type PFResult = string; // @public -export enum LoadTestRunClientKnownSecretType { - AKV_SECRET_URI = "AKV_SECRET_URI", - SECRET_VALUE = "SECRET_VALUE" -} +export type PFTestResult = string; // @public -export enum LoadTestRunClientKnownStatus { - ACCEPTED = "ACCEPTED", - CANCELLED = "CANCELLED", - CANCELLING = "CANCELLING", - CONFIGURED = "CONFIGURED", - CONFIGURING = "CONFIGURING", - DEPROVISIONED = "DEPROVISIONED", - DEPROVISIONING = "DEPROVISIONING", - DONE = "DONE", - EXECUTED = "EXECUTED", - EXECUTING = "EXECUTING", - FAILED = "FAILED", - NOTSTARTED = "NOTSTARTED", - PROVISIONED = "PROVISIONED", - PROVISIONING = "PROVISIONING", - VALIDATION_FAILURE = "VALIDATION_FAILURE", - VALIDATION_SUCCESS = "VALIDATION_SUCCESS" -} +export type RecommendationCategory = string; // @public -export enum LoadTestRunClientKnownTestKind { - JMX = "JMX", - Locust = "Locust", - URL = "URL" +export interface RegionalConfiguration { + engineInstances: number; + region: string; } // @public -export enum LoadTestRunClientKnownTestProfileRunStatus { - ACCEPTED = "ACCEPTED", - CANCELLED = "CANCELLED", - CANCELLING = "CANCELLING", - DONE = "DONE", - EXECUTING = "EXECUTING", - FAILED = "FAILED", - NOTSTARTED = "NOTSTARTED" -} +export type RequestDataLevel = string; // @public -export enum LoadTestRunClientKnownTimeGrain { - PT10S = "PT10S", - PT1H = "PT1H", - PT1M = "PT1M", - PT5M = "PT5M", - PT5S = "PT5S" -} +export type ResourceKind = string; // @public -export interface LoadTestRunClientLoadTestConfiguration { - engineInstances?: number; - optionalLoadTestConfig?: LoadTestRunClientOptionalLoadTestConfig; - quickStartTest?: boolean; - regionalLoadTestConfig?: LoadTestRunClientRegionalConfiguration[]; - splitAllCSVs?: boolean; +export interface ResourceMetric { + aggregation: string; + displayDescription?: string; + readonly id?: string; + metricNamespace: string; + name: string; + resourceId: string; + resourceType: string; + unit?: string; } // @public -export interface LoadTestRunClientMetricAvailability { - timeGrain?: LoadTestRunClientTimeGrain; +export interface Secret { + type?: SecretType; + value?: string; } // @public -export interface LoadTestRunClientMetricDefinition { - description?: string; - dimensions?: LoadTestRunClientNameAndDesc[]; - metricAvailabilities?: LoadTestRunClientMetricAvailability[]; - name?: string; - namespace?: string; - primaryAggregationType?: LoadTestRunClientAggregationType; - supportedAggregationTypes?: string[]; - unit?: LoadTestRunClientMetricUnit; -} +export type SecretType = string; // @public -export interface LoadTestRunClientMetricDefinitionCollection { - value: LoadTestRunClientMetricDefinition[]; -} +export type Status = string; // @public -export interface LoadTestRunClientMetricNamespace { - description?: string; - name?: string; +export interface StopTestProfileRunOptionalParams extends OperationOptions { } // @public -export interface LoadTestRunClientMetricNamespaceCollection { - value: LoadTestRunClientMetricNamespace[]; +export interface StopTestRunOptionalParams extends OperationOptions { } // @public -export interface LoadTestRunClientMetricRequestPayload { - filters?: LoadTestRunClientDimensionFilter[]; +export interface TargetResourceConfigurations { + kind: ResourceKind; } // @public -export type LoadTestRunClientMetricUnit = string; +export type TargetResourceConfigurationsUnion = FunctionFlexConsumptionTargetResourceConfigurations | TargetResourceConfigurations; // @public -export interface LoadTestRunClientMetricValue { - timestamp?: Date; - value?: number; -} - -// @public -export interface LoadTestRunClientNameAndDesc { - description?: string; - name?: string; -} - -// @public -export interface LoadTestRunClientOptionalLoadTestConfig { - duration?: number; - endpointUrl?: string; - maxResponseTimeInMs?: number; - rampUpTime?: number; - requestsPerSecond?: number; - virtualUsers?: number; -} - -// @public -export interface LoadTestRunClientOptionalParams extends ClientOptions { - apiVersion?: string; -} - -// @public -export interface LoadTestRunClientPassFailCriteria { - passFailMetrics?: Record; -} - -// @public -export interface LoadTestRunClientPassFailMetric { - action?: LoadTestRunClientPFAction; - readonly actualValue?: number; - aggregate?: LoadTestRunClientPFAgFunc; - clientMetric?: LoadTestRunClientPFMetrics; - condition?: string; - requestName?: string; - readonly result?: LoadTestRunClientPFResult; - value?: number; -} - -// @public -export type LoadTestRunClientPFAction = string; - -// @public -export type LoadTestRunClientPFAgFunc = string; - -// @public -export type LoadTestRunClientPFMetrics = string; - -// @public -export type LoadTestRunClientPFResult = string; - -// @public -export type LoadTestRunClientPFTestResult = string; - -// @public -export type LoadTestRunClientRecommendationCategory = string; - -// @public -export interface LoadTestRunClientRegionalConfiguration { - engineInstances: number; - region: string; -} - -// @public -export type LoadTestRunClientRequestDataLevel = string; - -// @public -export type LoadTestRunClientResourceKind = string; - -// @public -export interface LoadTestRunClientResourceMetric { - aggregation: string; - displayDescription?: string; - readonly id?: string; - metricNamespace: string; - name: string; - resourceId: string; - resourceType: string; - unit?: string; -} - -// @public -export interface LoadTestRunClientSecret { - type?: LoadTestRunClientSecretType; - value?: string; -} - -// @public -export type LoadTestRunClientSecretType = string; - -// @public -export type LoadTestRunClientStatus = string; - -// @public -export interface LoadTestRunClientTargetResourceConfigurations { - kind: LoadTestRunClientResourceKind; -} - -// @public -export type LoadTestRunClientTargetResourceConfigurationsUnion = LoadTestRunClientFunctionFlexConsumptionTargetResourceConfigurations | LoadTestRunClientTargetResourceConfigurations; - -// @public -export interface LoadTestRunClientTest { - autoStopCriteria?: LoadTestRunClientAutoStopCriteria; - baselineTestRunId?: string; - certificate?: LoadTestRunClientCertificateMetadata; - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - environmentVariables?: Record; - readonly inputArtifacts?: LoadTestRunClientTestInputArtifacts; - keyvaultReferenceIdentityId?: string; - keyvaultReferenceIdentityType?: string; - kind?: LoadTestRunClientTestKind; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; - passFailCriteria?: LoadTestRunClientPassFailCriteria; - publicIPDisabled?: boolean; - secrets?: Record; - subnetId?: string; - readonly testId: string; -} - -// @public -export interface LoadTestRunClientTestAppComponents { - components: Record; - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - readonly testId?: string; -} - -// @public -export interface LoadTestRunClientTestFileInfo { - readonly expireDateTime?: Date; - fileName: string; - readonly fileType?: LoadTestRunClientFileType; - readonly url?: string; - readonly validationFailureDetails?: string; - readonly validationStatus?: LoadTestRunClientFileStatus; -} - -// @public -export interface LoadTestRunClientTestInputArtifacts { - readonly additionalFileInfo?: LoadTestRunClientTestFileInfo[]; - configFileInfo?: LoadTestRunClientTestFileInfo; - inputArtifactsZipFileInfo?: LoadTestRunClientTestFileInfo; - testScriptFileInfo?: LoadTestRunClientTestFileInfo; - urlTestConfigFileInfo?: LoadTestRunClientTestFileInfo; - userPropFileInfo?: LoadTestRunClientTestFileInfo; -} - -// @public -export type LoadTestRunClientTestKind = string; - -// @public -export interface LoadTestRunClientTestProfile { - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - targetResourceConfigurations?: LoadTestRunClientTargetResourceConfigurationsUnion; - targetResourceId?: string; - testId?: string; - readonly testProfileId: string; -} - -// @public -export interface LoadTestRunClientTestProfileRun { - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - readonly durationInSeconds?: number; - readonly endDateTime?: Date; - readonly errorDetails?: LoadTestRunClientErrorDetails[]; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - readonly recommendations?: LoadTestRunClientTestProfileRunRecommendation[]; - readonly startDateTime?: Date; - readonly status?: LoadTestRunClientTestProfileRunStatus; - readonly targetResourceConfigurations?: LoadTestRunClientTargetResourceConfigurationsUnion; - readonly targetResourceId?: string; - testProfileId?: string; - readonly testProfileRunId: string; - readonly testRunDetails?: Record; -} - -// @public -export interface LoadTestRunClientTestProfileRunRecommendation { - category: LoadTestRunClientRecommendationCategory; - configurations?: string[]; -} - -// @public -export type LoadTestRunClientTestProfileRunStatus = string; - -// @public -export interface LoadTestRunClientTestRun { - autoStopCriteria?: LoadTestRunClientAutoStopCriteria; - certificate?: LoadTestRunClientCertificateMetadata; - readonly createdBy?: string; - readonly createdDateTime?: Date; - debugLogsEnabled?: boolean; - description?: string; - displayName?: string; - readonly duration?: number; - readonly endDateTime?: Date; - environmentVariables?: Record; - readonly errorDetails?: LoadTestRunClientErrorDetails[]; - readonly executedDateTime?: Date; - readonly kind?: LoadTestRunClientTestKind; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; - passFailCriteria?: LoadTestRunClientPassFailCriteria; - readonly portalUrl?: string; - readonly publicIPDisabled?: boolean; - readonly regionalStatistics?: Record; - requestDataLevel?: LoadTestRunClientRequestDataLevel; - secrets?: Record; - readonly startDateTime?: Date; - readonly status?: LoadTestRunClientStatus; - readonly subnetId?: string; - readonly testArtifacts?: LoadTestRunClientTestRunArtifacts; - testId?: string; - readonly testResult?: LoadTestRunClientPFTestResult; - readonly testRunId: string; - readonly testRunStatistics?: Record; - readonly virtualUsers?: number; -} - -// @public -export interface LoadTestRunClientTestRunAppComponents { - components: Record; - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - readonly testRunId?: string; -} - -// @public -export interface LoadTestRunClientTestRunArtifacts { - readonly inputArtifacts?: LoadTestRunClientTestRunInputArtifacts; - outputArtifacts?: LoadTestRunClientTestRunOutputArtifacts; -} - -// @public -export interface LoadTestRunClientTestRunDetail { - configurationId: string; - properties: Record; - status: LoadTestRunClientStatus; -} - -// @public -export interface LoadTestRunClientTestRunFileInfo { - readonly expireDateTime?: Date; - fileName: string; - readonly fileType?: LoadTestRunClientFileType; - readonly url?: string; - readonly validationFailureDetails?: string; - readonly validationStatus?: LoadTestRunClientFileStatus; -} - -// @public -export interface LoadTestRunClientTestRunInputArtifacts { - readonly additionalFileInfo?: LoadTestRunClientTestRunFileInfo[]; - configFileInfo?: LoadTestRunClientTestRunFileInfo; - inputArtifactsZipFileInfo?: LoadTestRunClientTestRunFileInfo; - testScriptFileInfo?: LoadTestRunClientTestRunFileInfo; - urlTestConfigFileInfo?: LoadTestRunClientTestRunFileInfo; - userPropFileInfo?: LoadTestRunClientTestRunFileInfo; -} - -// @public -export interface LoadTestRunClientTestRunOutputArtifacts { - artifactsContainerInfo?: LoadTestRunClientArtifactsContainerInfo; - logsFileInfo?: LoadTestRunClientTestRunFileInfo; - reportFileInfo?: LoadTestRunClientTestRunFileInfo; - resultFileInfo?: LoadTestRunClientTestRunFileInfo; -} - -// @public -export interface LoadTestRunClientTestRunServerMetricConfig { - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - metrics?: Record; - readonly testRunId?: string; -} - -// @public -export interface LoadTestRunClientTestRunStatistics { - readonly errorCount?: number; - readonly errorPct?: number; - readonly maxResTime?: number; - readonly meanResTime?: number; - readonly medianResTime?: number; - readonly minResTime?: number; - readonly pct1ResTime?: number; - readonly pct2ResTime?: number; - readonly pct3ResTime?: number; - readonly pct75ResTime?: number; - readonly pct96ResTime?: number; - readonly pct97ResTime?: number; - readonly pct98ResTime?: number; - readonly pct9999ResTime?: number; - readonly pct999ResTime?: number; - readonly receivedKBytesPerSec?: number; - readonly sampleCount?: number; - readonly sentKBytesPerSec?: number; - readonly throughput?: number; - readonly transaction?: string; -} - -// @public -export interface LoadTestRunClientTestServerMetricConfig { - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - metrics: Record; - readonly testId?: string; -} - -// @public -export type LoadTestRunClientTimeGrain = string; - -// @public -export interface LoadTestRunClientTimeSeriesElement { - data?: LoadTestRunClientMetricValue[]; - dimensionValues?: LoadTestRunClientDimensionValue[]; -} - -// @public -export interface MetricAvailability { - timeGrain?: TimeGrain; -} - -// @public -export interface MetricDefinition { - description?: string; - dimensions?: NameAndDesc[]; - metricAvailabilities?: MetricAvailability[]; - name?: string; - namespace?: string; - primaryAggregationType?: AggregationType; - supportedAggregationTypes?: string[]; - unit?: MetricUnit; -} - -// @public -export interface MetricDefinitionCollection { - value: MetricDefinition[]; -} - -// @public -export interface MetricNamespace { - description?: string; - name?: string; -} - -// @public -export interface MetricNamespaceCollection { - value: MetricNamespace[]; -} - -// @public -export interface MetricRequestPayload { - filters?: DimensionFilter[]; -} - -// @public -export type MetricUnit = string; - -// @public -export interface MetricValue { - timestamp?: Date; - value?: number; -} - -// @public -export interface NameAndDesc { - description?: string; - name?: string; -} - -// @public -export interface OptionalLoadTestConfig { - duration?: number; - endpointUrl?: string; - maxResponseTimeInMs?: number; - rampUpTime?: number; - requestsPerSecond?: number; - virtualUsers?: number; -} - -// @public -export interface PagedAsyncIterableIterator { - [Symbol.asyncIterator](): PagedAsyncIterableIterator; - byPage: (settings?: TPageSettings) => AsyncIterableIterator>; - next(): Promise>; -} - -// @public -export interface PageSettings { - continuationToken?: string; -} - -// @public -export interface PassFailCriteria { - passFailMetrics?: Record; -} - -// @public -export interface PassFailMetric { - action?: PFAction; - readonly actualValue?: number; - aggregate?: PFAgFunc; - clientMetric?: PFMetrics; - condition?: string; - requestName?: string; - readonly result?: PFResult; - value?: number; -} - -// @public -export type PFAction = string; - -// @public -export type PFAgFunc = string; - -// @public -export type PFMetrics = string; - -// @public -export type PFResult = string; - -// @public -export type PFTestResult = string; - -// @public -export type RecommendationCategory = string; - -// @public -export interface RegionalConfiguration { - engineInstances: number; - region: string; -} - -// @public -export type RequestDataLevel = string; - -// @public -export type ResourceKind = string; - -// @public -export interface ResourceMetric { - aggregation: string; - displayDescription?: string; - readonly id?: string; - metricNamespace: string; - name: string; - resourceId: string; - resourceType: string; - unit?: string; -} - -// @public -export interface Secret { - type?: SecretType; - value?: string; -} - -// @public -export type SecretType = string; - -// @public -export type Status = string; - -// @public -export interface StopTestProfileRunOptionalParams extends OperationOptions { -} - -// @public -export interface StopTestRunOptionalParams extends OperationOptions { -} - -// @public -export interface TargetResourceConfigurations { - kind: ResourceKind; -} - -// @public -export type TargetResourceConfigurationsUnion = FunctionFlexConsumptionTargetResourceConfigurations | TargetResourceConfigurations; - -// @public -export interface Test { - autoStopCriteria?: AutoStopCriteria; - baselineTestRunId?: string; - certificate?: CertificateMetadata; - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - environmentVariables?: Record; - readonly inputArtifacts?: TestInputArtifacts; - keyvaultReferenceIdentityId?: string; - keyvaultReferenceIdentityType?: string; - kind?: TestKind; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - loadTestConfiguration?: LoadTestConfiguration; - passFailCriteria?: PassFailCriteria; - publicIPDisabled?: boolean; - secrets?: Record; - subnetId?: string; - readonly testId: string; -} - -// @public -export interface TestAppComponents { - components: Record; - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - readonly testId?: string; -} - -// @public -export interface TestFileInfo { - readonly expireDateTime?: Date; - fileName: string; - readonly fileType?: FileType; - readonly url?: string; - readonly validationFailureDetails?: string; - readonly validationStatus?: FileStatus; -} - -// @public -export interface TestInputArtifacts { - readonly additionalFileInfo?: TestFileInfo[]; - configFileInfo?: TestFileInfo; - inputArtifactsZipFileInfo?: TestFileInfo; - testScriptFileInfo?: TestFileInfo; - urlTestConfigFileInfo?: TestFileInfo; - userPropFileInfo?: TestFileInfo; -} - -// @public -export type TestKind = string; - -// @public -export interface TestProfile { - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - targetResourceConfigurations?: TargetResourceConfigurationsUnion; - targetResourceId?: string; - testId?: string; - readonly testProfileId: string; -} - -// @public (undocumented) -export class TestProfileAdministrationClient { - constructor(endpointParam: string, credential: TokenCredential, options?: TestProfileAdministrationClientOptionalParams); - createOrUpdateTestProfile(testProfileId: string, body: TestProfileAdministrationClientTestProfile, options?: CreateOrUpdateTestProfileOptionalParams): Promise; - deleteTestProfile(testProfileId: string, options?: DeleteTestProfileOptionalParams): Promise; - getTestProfile(testProfileId: string, options?: GetTestProfileOptionalParams): Promise; - listTestProfiles(options?: ListTestProfilesOptionalParams): PagedAsyncIterableIterator; - readonly pipeline: Pipeline; -} - -// @public -export type TestProfileAdministrationClientAggregationType = string; - -// @public -export type TestProfileAdministrationClientAPIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; - -// @public -export interface TestProfileAdministrationClientAppComponent { - displayName?: string; - kind?: string; - readonly resourceGroup?: string; - readonly resourceId: string; - resourceName: string; - resourceType: string; - readonly subscriptionId?: string; -} - -// @public -export interface TestProfileAdministrationClientArtifactsContainerInfo { - expireDateTime?: Date; - url?: string; -} - -// @public -export interface TestProfileAdministrationClientAutoStopCriteria { - autoStopDisabled?: boolean; - errorRate?: number; - errorRateTimeWindowInSeconds?: number; -} - -// @public -export interface TestProfileAdministrationClientCertificateMetadata { - name?: string; - type?: TestProfileAdministrationClientCertificateType; - value?: string; -} - -// @public -export type TestProfileAdministrationClientCertificateType = string; - -// @public -export interface TestProfileAdministrationClientDimensionFilter { - name?: string; - values?: string[]; -} - -// @public -export interface TestProfileAdministrationClientDimensionValue { - name?: string; - value?: string; -} - -// @public -export interface TestProfileAdministrationClientDimensionValueList { - readonly name?: string; - nextLink?: string; - value?: string[]; -} - -// @public -export interface TestProfileAdministrationClientErrorDetails { - readonly message?: string; -} - -// @public -export type TestProfileAdministrationClientFileStatus = string; - -// @public -export type TestProfileAdministrationClientFileType = string; - -// @public -export interface TestProfileAdministrationClientFunctionFlexConsumptionResourceConfiguration { - httpConcurrency: number; - instanceMemoryMB: number; -} - -// @public -export interface TestProfileAdministrationClientFunctionFlexConsumptionTargetResourceConfigurations extends TestProfileAdministrationClientTargetResourceConfigurations { - configurations?: Record; - kind: "FunctionsFlexConsumption"; -} - -// @public -export enum TestProfileAdministrationClientKnownAggregationType { - Average = "Average", - Count = "Count", - None = "None", - Percentile75 = "Percentile75", - Percentile90 = "Percentile90", - Percentile95 = "Percentile95", - Percentile96 = "Percentile96", - Percentile97 = "Percentile97", - Percentile98 = "Percentile98", - Percentile99 = "Percentile99", - Percentile999 = "Percentile999", - Percentile9999 = "Percentile9999", - Total = "Total" -} - -// @public -export enum TestProfileAdministrationClientKnownCertificateType { - AKV_CERT_URI = "AKV_CERT_URI" -} - -// @public -export enum TestProfileAdministrationClientKnownFileStatus { - NOT_VALIDATED = "NOT_VALIDATED", - VALIDATION_FAILURE = "VALIDATION_FAILURE", - VALIDATION_INITIATED = "VALIDATION_INITIATED", - VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", - VALIDATION_SUCCESS = "VALIDATION_SUCCESS" -} - -// @public -export enum TestProfileAdministrationClientKnownFileType { - ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", - JMX_FILE = "JMX_FILE", - TEST_SCRIPT = "TEST_SCRIPT", - URL_TEST_CONFIG = "URL_TEST_CONFIG", - USER_PROPERTIES = "USER_PROPERTIES", - ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS" -} - -// @public -export enum TestProfileAdministrationClientKnownMetricUnit { - Bytes = "Bytes", - BytesPerSecond = "BytesPerSecond", - Count = "Count", - CountPerSecond = "CountPerSecond", - Milliseconds = "Milliseconds", - NotSpecified = "NotSpecified", - Percent = "Percent", - Seconds = "Seconds" -} - -// @public -export enum TestProfileAdministrationClientKnownPFAction { - "continue" = "continue", - stop = "stop" -} - -// @public -export enum TestProfileAdministrationClientKnownPFAgFunc { - "p99.9" = "p99.9", - "p99.99" = "p99.99", - avg = "avg", - count = "count", - max = "max", - min = "min", - p50 = "p50", - p75 = "p75", - p90 = "p90", - p95 = "p95", - p96 = "p96", - p97 = "p97", - p98 = "p98", - p99 = "p99", - percentage = "percentage" -} - -// @public -export enum TestProfileAdministrationClientKnownPFMetrics { - error = "error", - latency = "latency", - requests = "requests", - requests_per_sec = "requests_per_sec", - response_time_ms = "response_time_ms" -} - -// @public -export enum TestProfileAdministrationClientKnownPFResult { - failed = "failed", - passed = "passed", - undetermined = "undetermined" -} - -// @public -export enum TestProfileAdministrationClientKnownPFTestResult { - FAILED = "FAILED", - NOT_APPLICABLE = "NOT_APPLICABLE", - PASSED = "PASSED" -} - -// @public -export enum TestProfileAdministrationClientKnownRecommendationCategory { - CostOptimized = "CostOptimized", - ThroughputOptimized = "ThroughputOptimized" -} - -// @public -export enum TestProfileAdministrationClientKnownRequestDataLevel { - ERRORS = "ERRORS", - NONE = "NONE" -} - -// @public -export enum TestProfileAdministrationClientKnownResourceKind { - FunctionsFlexConsumption = "FunctionsFlexConsumption" -} - -// @public -export enum TestProfileAdministrationClientKnownSecretType { - AKV_SECRET_URI = "AKV_SECRET_URI", - SECRET_VALUE = "SECRET_VALUE" -} - -// @public -export enum TestProfileAdministrationClientKnownStatus { - ACCEPTED = "ACCEPTED", - CANCELLED = "CANCELLED", - CANCELLING = "CANCELLING", - CONFIGURED = "CONFIGURED", - CONFIGURING = "CONFIGURING", - DEPROVISIONED = "DEPROVISIONED", - DEPROVISIONING = "DEPROVISIONING", - DONE = "DONE", - EXECUTED = "EXECUTED", - EXECUTING = "EXECUTING", - FAILED = "FAILED", - NOTSTARTED = "NOTSTARTED", - PROVISIONED = "PROVISIONED", - PROVISIONING = "PROVISIONING", - VALIDATION_FAILURE = "VALIDATION_FAILURE", - VALIDATION_SUCCESS = "VALIDATION_SUCCESS" -} - -// @public -export enum TestProfileAdministrationClientKnownTestKind { - JMX = "JMX", - Locust = "Locust", - URL = "URL" -} - -// @public -export enum TestProfileAdministrationClientKnownTestProfileRunStatus { - ACCEPTED = "ACCEPTED", - CANCELLED = "CANCELLED", - CANCELLING = "CANCELLING", - DONE = "DONE", - EXECUTING = "EXECUTING", - FAILED = "FAILED", - NOTSTARTED = "NOTSTARTED" -} - -// @public -export enum TestProfileAdministrationClientKnownTimeGrain { - PT10S = "PT10S", - PT1H = "PT1H", - PT1M = "PT1M", - PT5M = "PT5M", - PT5S = "PT5S" -} - -// @public -export interface TestProfileAdministrationClientLoadTestConfiguration { - engineInstances?: number; - optionalLoadTestConfig?: TestProfileAdministrationClientOptionalLoadTestConfig; - quickStartTest?: boolean; - regionalLoadTestConfig?: TestProfileAdministrationClientRegionalConfiguration[]; - splitAllCSVs?: boolean; -} - -// @public -export interface TestProfileAdministrationClientMetricAvailability { - timeGrain?: TestProfileAdministrationClientTimeGrain; -} - -// @public -export interface TestProfileAdministrationClientMetricDefinition { - description?: string; - dimensions?: TestProfileAdministrationClientNameAndDesc[]; - metricAvailabilities?: TestProfileAdministrationClientMetricAvailability[]; - name?: string; - namespace?: string; - primaryAggregationType?: TestProfileAdministrationClientAggregationType; - supportedAggregationTypes?: string[]; - unit?: TestProfileAdministrationClientMetricUnit; -} - -// @public -export interface TestProfileAdministrationClientMetricDefinitionCollection { - value: TestProfileAdministrationClientMetricDefinition[]; -} - -// @public -export interface TestProfileAdministrationClientMetricNamespace { - description?: string; - name?: string; -} - -// @public -export interface TestProfileAdministrationClientMetricNamespaceCollection { - value: TestProfileAdministrationClientMetricNamespace[]; -} - -// @public -export interface TestProfileAdministrationClientMetricRequestPayload { - filters?: TestProfileAdministrationClientDimensionFilter[]; -} - -// @public -export type TestProfileAdministrationClientMetricUnit = string; - -// @public -export interface TestProfileAdministrationClientMetricValue { - timestamp?: Date; - value?: number; -} - -// @public -export interface TestProfileAdministrationClientNameAndDesc { - description?: string; - name?: string; -} - -// @public -export interface TestProfileAdministrationClientOptionalLoadTestConfig { - duration?: number; - endpointUrl?: string; - maxResponseTimeInMs?: number; - rampUpTime?: number; - requestsPerSecond?: number; - virtualUsers?: number; -} - -// @public -export interface TestProfileAdministrationClientOptionalParams extends ClientOptions { - apiVersion?: string; -} - -// @public -export interface TestProfileAdministrationClientPassFailCriteria { - passFailMetrics?: Record; -} - -// @public -export interface TestProfileAdministrationClientPassFailMetric { - action?: TestProfileAdministrationClientPFAction; - readonly actualValue?: number; - aggregate?: TestProfileAdministrationClientPFAgFunc; - clientMetric?: TestProfileAdministrationClientPFMetrics; - condition?: string; - requestName?: string; - readonly result?: TestProfileAdministrationClientPFResult; - value?: number; -} - -// @public -export type TestProfileAdministrationClientPFAction = string; - -// @public -export type TestProfileAdministrationClientPFAgFunc = string; - -// @public -export type TestProfileAdministrationClientPFMetrics = string; - -// @public -export type TestProfileAdministrationClientPFResult = string; - -// @public -export type TestProfileAdministrationClientPFTestResult = string; - -// @public -export type TestProfileAdministrationClientRecommendationCategory = string; - -// @public -export interface TestProfileAdministrationClientRegionalConfiguration { - engineInstances: number; - region: string; -} - -// @public -export type TestProfileAdministrationClientRequestDataLevel = string; - -// @public -export type TestProfileAdministrationClientResourceKind = string; - -// @public -export interface TestProfileAdministrationClientResourceMetric { - aggregation: string; - displayDescription?: string; - readonly id?: string; - metricNamespace: string; - name: string; - resourceId: string; - resourceType: string; - unit?: string; -} - -// @public -export interface TestProfileAdministrationClientSecret { - type?: TestProfileAdministrationClientSecretType; - value?: string; -} - -// @public -export type TestProfileAdministrationClientSecretType = string; - -// @public -export type TestProfileAdministrationClientStatus = string; - -// @public -export interface TestProfileAdministrationClientTargetResourceConfigurations { - kind: TestProfileAdministrationClientResourceKind; -} - -// @public -export type TestProfileAdministrationClientTargetResourceConfigurationsUnion = TestProfileAdministrationClientFunctionFlexConsumptionTargetResourceConfigurations | TestProfileAdministrationClientTargetResourceConfigurations; - -// @public -export interface TestProfileAdministrationClientTest { - autoStopCriteria?: TestProfileAdministrationClientAutoStopCriteria; - baselineTestRunId?: string; - certificate?: TestProfileAdministrationClientCertificateMetadata; - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - environmentVariables?: Record; - readonly inputArtifacts?: TestProfileAdministrationClientTestInputArtifacts; - keyvaultReferenceIdentityId?: string; - keyvaultReferenceIdentityType?: string; - kind?: TestProfileAdministrationClientTestKind; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - loadTestConfiguration?: TestProfileAdministrationClientLoadTestConfiguration; - passFailCriteria?: TestProfileAdministrationClientPassFailCriteria; - publicIPDisabled?: boolean; - secrets?: Record; - subnetId?: string; - readonly testId: string; -} - -// @public -export interface TestProfileAdministrationClientTestAppComponents { - components: Record; - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - readonly testId?: string; -} - -// @public -export interface TestProfileAdministrationClientTestFileInfo { - readonly expireDateTime?: Date; - fileName: string; - readonly fileType?: TestProfileAdministrationClientFileType; - readonly url?: string; - readonly validationFailureDetails?: string; - readonly validationStatus?: TestProfileAdministrationClientFileStatus; -} - -// @public -export interface TestProfileAdministrationClientTestInputArtifacts { - readonly additionalFileInfo?: TestProfileAdministrationClientTestFileInfo[]; - configFileInfo?: TestProfileAdministrationClientTestFileInfo; - inputArtifactsZipFileInfo?: TestProfileAdministrationClientTestFileInfo; - testScriptFileInfo?: TestProfileAdministrationClientTestFileInfo; - urlTestConfigFileInfo?: TestProfileAdministrationClientTestFileInfo; - userPropFileInfo?: TestProfileAdministrationClientTestFileInfo; -} - -// @public -export type TestProfileAdministrationClientTestKind = string; - -// @public -export interface TestProfileAdministrationClientTestProfile { - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - targetResourceConfigurations?: TestProfileAdministrationClientTargetResourceConfigurationsUnion; - targetResourceId?: string; - testId?: string; - readonly testProfileId: string; -} - -// @public -export interface TestProfileAdministrationClientTestProfileRun { - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - readonly durationInSeconds?: number; - readonly endDateTime?: Date; - readonly errorDetails?: TestProfileAdministrationClientErrorDetails[]; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - readonly recommendations?: TestProfileAdministrationClientTestProfileRunRecommendation[]; - readonly startDateTime?: Date; - readonly status?: TestProfileAdministrationClientTestProfileRunStatus; - readonly targetResourceConfigurations?: TestProfileAdministrationClientTargetResourceConfigurationsUnion; - readonly targetResourceId?: string; - testProfileId?: string; - readonly testProfileRunId: string; - readonly testRunDetails?: Record; -} - -// @public -export interface TestProfileAdministrationClientTestProfileRunRecommendation { - category: TestProfileAdministrationClientRecommendationCategory; - configurations?: string[]; -} - -// @public -export type TestProfileAdministrationClientTestProfileRunStatus = string; - -// @public -export interface TestProfileAdministrationClientTestRun { - autoStopCriteria?: TestProfileAdministrationClientAutoStopCriteria; - certificate?: TestProfileAdministrationClientCertificateMetadata; - readonly createdBy?: string; - readonly createdDateTime?: Date; - debugLogsEnabled?: boolean; - description?: string; - displayName?: string; - readonly duration?: number; - readonly endDateTime?: Date; - environmentVariables?: Record; - readonly errorDetails?: TestProfileAdministrationClientErrorDetails[]; - readonly executedDateTime?: Date; - readonly kind?: TestProfileAdministrationClientTestKind; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - loadTestConfiguration?: TestProfileAdministrationClientLoadTestConfiguration; - passFailCriteria?: TestProfileAdministrationClientPassFailCriteria; - readonly portalUrl?: string; - readonly publicIPDisabled?: boolean; - readonly regionalStatistics?: Record; - requestDataLevel?: TestProfileAdministrationClientRequestDataLevel; - secrets?: Record; - readonly startDateTime?: Date; - readonly status?: TestProfileAdministrationClientStatus; - readonly subnetId?: string; - readonly testArtifacts?: TestProfileAdministrationClientTestRunArtifacts; - testId?: string; - readonly testResult?: TestProfileAdministrationClientPFTestResult; - readonly testRunId: string; - readonly testRunStatistics?: Record; - readonly virtualUsers?: number; -} - -// @public -export interface TestProfileAdministrationClientTestRunAppComponents { - components: Record; - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - readonly testRunId?: string; -} - -// @public -export interface TestProfileAdministrationClientTestRunArtifacts { - readonly inputArtifacts?: TestProfileAdministrationClientTestRunInputArtifacts; - outputArtifacts?: TestProfileAdministrationClientTestRunOutputArtifacts; -} - -// @public -export interface TestProfileAdministrationClientTestRunDetail { - configurationId: string; - properties: Record; - status: TestProfileAdministrationClientStatus; -} - -// @public -export interface TestProfileAdministrationClientTestRunFileInfo { - readonly expireDateTime?: Date; - fileName: string; - readonly fileType?: TestProfileAdministrationClientFileType; - readonly url?: string; - readonly validationFailureDetails?: string; - readonly validationStatus?: TestProfileAdministrationClientFileStatus; -} - -// @public -export interface TestProfileAdministrationClientTestRunInputArtifacts { - readonly additionalFileInfo?: TestProfileAdministrationClientTestRunFileInfo[]; - configFileInfo?: TestProfileAdministrationClientTestRunFileInfo; - inputArtifactsZipFileInfo?: TestProfileAdministrationClientTestRunFileInfo; - testScriptFileInfo?: TestProfileAdministrationClientTestRunFileInfo; - urlTestConfigFileInfo?: TestProfileAdministrationClientTestRunFileInfo; - userPropFileInfo?: TestProfileAdministrationClientTestRunFileInfo; -} - -// @public -export interface TestProfileAdministrationClientTestRunOutputArtifacts { - artifactsContainerInfo?: TestProfileAdministrationClientArtifactsContainerInfo; - logsFileInfo?: TestProfileAdministrationClientTestRunFileInfo; - reportFileInfo?: TestProfileAdministrationClientTestRunFileInfo; - resultFileInfo?: TestProfileAdministrationClientTestRunFileInfo; -} - -// @public -export interface TestProfileAdministrationClientTestRunServerMetricConfig { - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - metrics?: Record; - readonly testRunId?: string; -} - -// @public -export interface TestProfileAdministrationClientTestRunStatistics { - readonly errorCount?: number; - readonly errorPct?: number; - readonly maxResTime?: number; - readonly meanResTime?: number; - readonly medianResTime?: number; - readonly minResTime?: number; - readonly pct1ResTime?: number; - readonly pct2ResTime?: number; - readonly pct3ResTime?: number; - readonly pct75ResTime?: number; - readonly pct96ResTime?: number; - readonly pct97ResTime?: number; - readonly pct98ResTime?: number; - readonly pct9999ResTime?: number; - readonly pct999ResTime?: number; - readonly receivedKBytesPerSec?: number; - readonly sampleCount?: number; - readonly sentKBytesPerSec?: number; - readonly throughput?: number; - readonly transaction?: string; -} - -// @public -export interface TestProfileAdministrationClientTestServerMetricConfig { - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - metrics: Record; - readonly testId?: string; -} - -// @public -export type TestProfileAdministrationClientTimeGrain = string; - -// @public -export interface TestProfileAdministrationClientTimeSeriesElement { - data?: TestProfileAdministrationClientMetricValue[]; - dimensionValues?: TestProfileAdministrationClientDimensionValue[]; -} - -// @public -export interface TestProfileRun { - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - readonly durationInSeconds?: number; - readonly endDateTime?: Date; - readonly errorDetails?: ErrorDetails[]; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - readonly recommendations?: TestProfileRunRecommendation[]; - readonly startDateTime?: Date; - readonly status?: TestProfileRunStatus; - readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; - readonly targetResourceId?: string; - testProfileId?: string; - readonly testProfileRunId: string; - readonly testRunDetails?: Record; -} - -// @public (undocumented) -export class TestProfileRunClient { - constructor(endpointParam: string, credential: TokenCredential, options?: TestProfileRunClientOptionalParams); - createOrUpdateTestProfileRun(testProfileRunId: string, body: TestProfileRunClientTestProfileRun, options?: CreateOrUpdateTestProfileRunOptionalParams): Promise; - deleteTestProfileRun(testProfileRunId: string, options?: DeleteTestProfileRunOptionalParams): Promise; - getTestProfileRun(testProfileRunId: string, options?: GetTestProfileRunOptionalParams): Promise; - listTestProfileRuns(options?: ListTestProfileRunsOptionalParams): PagedAsyncIterableIterator; - readonly pipeline: Pipeline; - stopTestProfileRun(testProfileRunId: string, options?: StopTestProfileRunOptionalParams): Promise; -} - -// @public -export type TestProfileRunClientAggregationType = string; - -// @public -export type TestProfileRunClientAPIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; - -// @public -export interface TestProfileRunClientAppComponent { - displayName?: string; - kind?: string; - readonly resourceGroup?: string; - readonly resourceId: string; - resourceName: string; - resourceType: string; - readonly subscriptionId?: string; -} - -// @public -export interface TestProfileRunClientArtifactsContainerInfo { - expireDateTime?: Date; - url?: string; -} - -// @public -export interface TestProfileRunClientAutoStopCriteria { - autoStopDisabled?: boolean; - errorRate?: number; - errorRateTimeWindowInSeconds?: number; -} - -// @public -export interface TestProfileRunClientCertificateMetadata { - name?: string; - type?: TestProfileRunClientCertificateType; - value?: string; -} - -// @public -export type TestProfileRunClientCertificateType = string; - -// @public -export interface TestProfileRunClientDimensionFilter { - name?: string; - values?: string[]; -} - -// @public -export interface TestProfileRunClientDimensionValue { - name?: string; - value?: string; -} - -// @public -export interface TestProfileRunClientDimensionValueList { - readonly name?: string; - nextLink?: string; - value?: string[]; -} - -// @public -export interface TestProfileRunClientErrorDetails { - readonly message?: string; -} - -// @public -export type TestProfileRunClientFileStatus = string; - -// @public -export type TestProfileRunClientFileType = string; - -// @public -export interface TestProfileRunClientFunctionFlexConsumptionResourceConfiguration { - httpConcurrency: number; - instanceMemoryMB: number; -} - -// @public -export interface TestProfileRunClientFunctionFlexConsumptionTargetResourceConfigurations extends TestProfileRunClientTargetResourceConfigurations { - configurations?: Record; - kind: "FunctionsFlexConsumption"; -} - -// @public -export enum TestProfileRunClientKnownAggregationType { - Average = "Average", - Count = "Count", - None = "None", - Percentile75 = "Percentile75", - Percentile90 = "Percentile90", - Percentile95 = "Percentile95", - Percentile96 = "Percentile96", - Percentile97 = "Percentile97", - Percentile98 = "Percentile98", - Percentile99 = "Percentile99", - Percentile999 = "Percentile999", - Percentile9999 = "Percentile9999", - Total = "Total" -} - -// @public -export enum TestProfileRunClientKnownCertificateType { - AKV_CERT_URI = "AKV_CERT_URI" -} - -// @public -export enum TestProfileRunClientKnownFileStatus { - NOT_VALIDATED = "NOT_VALIDATED", - VALIDATION_FAILURE = "VALIDATION_FAILURE", - VALIDATION_INITIATED = "VALIDATION_INITIATED", - VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", - VALIDATION_SUCCESS = "VALIDATION_SUCCESS" -} - -// @public -export enum TestProfileRunClientKnownFileType { - ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", - JMX_FILE = "JMX_FILE", - TEST_SCRIPT = "TEST_SCRIPT", - URL_TEST_CONFIG = "URL_TEST_CONFIG", - USER_PROPERTIES = "USER_PROPERTIES", - ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS" -} - -// @public -export enum TestProfileRunClientKnownMetricUnit { - Bytes = "Bytes", - BytesPerSecond = "BytesPerSecond", - Count = "Count", - CountPerSecond = "CountPerSecond", - Milliseconds = "Milliseconds", - NotSpecified = "NotSpecified", - Percent = "Percent", - Seconds = "Seconds" -} - -// @public -export enum TestProfileRunClientKnownPFAction { - "continue" = "continue", - stop = "stop" -} - -// @public -export enum TestProfileRunClientKnownPFAgFunc { - "p99.9" = "p99.9", - "p99.99" = "p99.99", - avg = "avg", - count = "count", - max = "max", - min = "min", - p50 = "p50", - p75 = "p75", - p90 = "p90", - p95 = "p95", - p96 = "p96", - p97 = "p97", - p98 = "p98", - p99 = "p99", - percentage = "percentage" -} - -// @public -export enum TestProfileRunClientKnownPFMetrics { - error = "error", - latency = "latency", - requests = "requests", - requests_per_sec = "requests_per_sec", - response_time_ms = "response_time_ms" -} - -// @public -export enum TestProfileRunClientKnownPFResult { - failed = "failed", - passed = "passed", - undetermined = "undetermined" -} - -// @public -export enum TestProfileRunClientKnownPFTestResult { - FAILED = "FAILED", - NOT_APPLICABLE = "NOT_APPLICABLE", - PASSED = "PASSED" -} - -// @public -export enum TestProfileRunClientKnownRecommendationCategory { - CostOptimized = "CostOptimized", - ThroughputOptimized = "ThroughputOptimized" -} - -// @public -export enum TestProfileRunClientKnownRequestDataLevel { - ERRORS = "ERRORS", - NONE = "NONE" -} - -// @public -export enum TestProfileRunClientKnownResourceKind { - FunctionsFlexConsumption = "FunctionsFlexConsumption" -} - -// @public -export enum TestProfileRunClientKnownSecretType { - AKV_SECRET_URI = "AKV_SECRET_URI", - SECRET_VALUE = "SECRET_VALUE" -} - -// @public -export enum TestProfileRunClientKnownStatus { - ACCEPTED = "ACCEPTED", - CANCELLED = "CANCELLED", - CANCELLING = "CANCELLING", - CONFIGURED = "CONFIGURED", - CONFIGURING = "CONFIGURING", - DEPROVISIONED = "DEPROVISIONED", - DEPROVISIONING = "DEPROVISIONING", - DONE = "DONE", - EXECUTED = "EXECUTED", - EXECUTING = "EXECUTING", - FAILED = "FAILED", - NOTSTARTED = "NOTSTARTED", - PROVISIONED = "PROVISIONED", - PROVISIONING = "PROVISIONING", - VALIDATION_FAILURE = "VALIDATION_FAILURE", - VALIDATION_SUCCESS = "VALIDATION_SUCCESS" -} - -// @public -export enum TestProfileRunClientKnownTestKind { - JMX = "JMX", - Locust = "Locust", - URL = "URL" -} - -// @public -export enum TestProfileRunClientKnownTestProfileRunStatus { - ACCEPTED = "ACCEPTED", - CANCELLED = "CANCELLED", - CANCELLING = "CANCELLING", - DONE = "DONE", - EXECUTING = "EXECUTING", - FAILED = "FAILED", - NOTSTARTED = "NOTSTARTED" -} - -// @public -export enum TestProfileRunClientKnownTimeGrain { - PT10S = "PT10S", - PT1H = "PT1H", - PT1M = "PT1M", - PT5M = "PT5M", - PT5S = "PT5S" -} - -// @public -export interface TestProfileRunClientLoadTestConfiguration { - engineInstances?: number; - optionalLoadTestConfig?: TestProfileRunClientOptionalLoadTestConfig; - quickStartTest?: boolean; - regionalLoadTestConfig?: TestProfileRunClientRegionalConfiguration[]; - splitAllCSVs?: boolean; -} - -// @public -export interface TestProfileRunClientMetricAvailability { - timeGrain?: TestProfileRunClientTimeGrain; -} - -// @public -export interface TestProfileRunClientMetricDefinition { - description?: string; - dimensions?: TestProfileRunClientNameAndDesc[]; - metricAvailabilities?: TestProfileRunClientMetricAvailability[]; - name?: string; - namespace?: string; - primaryAggregationType?: TestProfileRunClientAggregationType; - supportedAggregationTypes?: string[]; - unit?: TestProfileRunClientMetricUnit; -} - -// @public -export interface TestProfileRunClientMetricDefinitionCollection { - value: TestProfileRunClientMetricDefinition[]; -} - -// @public -export interface TestProfileRunClientMetricNamespace { - description?: string; - name?: string; -} - -// @public -export interface TestProfileRunClientMetricNamespaceCollection { - value: TestProfileRunClientMetricNamespace[]; -} - -// @public -export interface TestProfileRunClientMetricRequestPayload { - filters?: TestProfileRunClientDimensionFilter[]; -} - -// @public -export type TestProfileRunClientMetricUnit = string; - -// @public -export interface TestProfileRunClientMetricValue { - timestamp?: Date; - value?: number; -} - -// @public -export interface TestProfileRunClientNameAndDesc { - description?: string; - name?: string; -} - -// @public -export interface TestProfileRunClientOptionalLoadTestConfig { - duration?: number; - endpointUrl?: string; - maxResponseTimeInMs?: number; - rampUpTime?: number; - requestsPerSecond?: number; - virtualUsers?: number; -} - -// @public -export interface TestProfileRunClientOptionalParams extends ClientOptions { - apiVersion?: string; -} - -// @public -export interface TestProfileRunClientPassFailCriteria { - passFailMetrics?: Record; -} - -// @public -export interface TestProfileRunClientPassFailMetric { - action?: TestProfileRunClientPFAction; - readonly actualValue?: number; - aggregate?: TestProfileRunClientPFAgFunc; - clientMetric?: TestProfileRunClientPFMetrics; - condition?: string; - requestName?: string; - readonly result?: TestProfileRunClientPFResult; - value?: number; -} - -// @public -export type TestProfileRunClientPFAction = string; - -// @public -export type TestProfileRunClientPFAgFunc = string; - -// @public -export type TestProfileRunClientPFMetrics = string; - -// @public -export type TestProfileRunClientPFResult = string; - -// @public -export type TestProfileRunClientPFTestResult = string; - -// @public -export type TestProfileRunClientRecommendationCategory = string; - -// @public -export interface TestProfileRunClientRegionalConfiguration { - engineInstances: number; - region: string; -} - -// @public -export type TestProfileRunClientRequestDataLevel = string; - -// @public -export type TestProfileRunClientResourceKind = string; - -// @public -export interface TestProfileRunClientResourceMetric { - aggregation: string; - displayDescription?: string; - readonly id?: string; - metricNamespace: string; - name: string; - resourceId: string; - resourceType: string; - unit?: string; -} - -// @public -export interface TestProfileRunClientSecret { - type?: TestProfileRunClientSecretType; - value?: string; -} - -// @public -export type TestProfileRunClientSecretType = string; - -// @public -export type TestProfileRunClientStatus = string; - -// @public -export interface TestProfileRunClientTargetResourceConfigurations { - kind: TestProfileRunClientResourceKind; -} - -// @public -export type TestProfileRunClientTargetResourceConfigurationsUnion = TestProfileRunClientFunctionFlexConsumptionTargetResourceConfigurations | TestProfileRunClientTargetResourceConfigurations; - -// @public -export interface TestProfileRunClientTest { - autoStopCriteria?: TestProfileRunClientAutoStopCriteria; +export interface Test { + autoStopCriteria?: AutoStopCriteria; baselineTestRunId?: string; - certificate?: TestProfileRunClientCertificateMetadata; + certificate?: CertificateMetadata; readonly createdBy?: string; readonly createdDateTime?: Date; description?: string; displayName?: string; environmentVariables?: Record; - readonly inputArtifacts?: TestProfileRunClientTestInputArtifacts; + readonly inputArtifacts?: TestInputArtifacts; keyvaultReferenceIdentityId?: string; keyvaultReferenceIdentityType?: string; - kind?: TestProfileRunClientTestKind; + kind?: TestKind; readonly lastModifiedBy?: string; readonly lastModifiedDateTime?: Date; - loadTestConfiguration?: TestProfileRunClientLoadTestConfiguration; - passFailCriteria?: TestProfileRunClientPassFailCriteria; + loadTestConfiguration?: LoadTestConfiguration; + passFailCriteria?: PassFailCriteria; publicIPDisabled?: boolean; - secrets?: Record; + secrets?: Record; subnetId?: string; readonly testId: string; } // @public -export interface TestProfileRunClientTestAppComponents { - components: Record; +export interface TestAppComponents { + components: Record; readonly createdBy?: string; readonly createdDateTime?: Date; readonly lastModifiedBy?: string; @@ -2503,209 +685,92 @@ export interface TestProfileRunClientTestAppComponents { } // @public -export interface TestProfileRunClientTestFileInfo { +export interface TestFileInfo { readonly expireDateTime?: Date; fileName: string; - readonly fileType?: TestProfileRunClientFileType; + readonly fileType?: FileType; readonly url?: string; readonly validationFailureDetails?: string; - readonly validationStatus?: TestProfileRunClientFileStatus; + readonly validationStatus?: FileStatus; } // @public -export interface TestProfileRunClientTestInputArtifacts { - readonly additionalFileInfo?: TestProfileRunClientTestFileInfo[]; - configFileInfo?: TestProfileRunClientTestFileInfo; - inputArtifactsZipFileInfo?: TestProfileRunClientTestFileInfo; - testScriptFileInfo?: TestProfileRunClientTestFileInfo; - urlTestConfigFileInfo?: TestProfileRunClientTestFileInfo; - userPropFileInfo?: TestProfileRunClientTestFileInfo; +export interface TestInputArtifacts { + readonly additionalFileInfo?: TestFileInfo[]; + configFileInfo?: TestFileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + testScriptFileInfo?: TestFileInfo; + urlTestConfigFileInfo?: TestFileInfo; + userPropFileInfo?: TestFileInfo; } // @public -export type TestProfileRunClientTestKind = string; +export type TestKind = string; // @public -export interface TestProfileRunClientTestProfile { +export interface TestProfile { readonly createdBy?: string; readonly createdDateTime?: Date; description?: string; displayName?: string; readonly lastModifiedBy?: string; readonly lastModifiedDateTime?: Date; - targetResourceConfigurations?: TestProfileRunClientTargetResourceConfigurationsUnion; + targetResourceConfigurations?: TargetResourceConfigurationsUnion; targetResourceId?: string; testId?: string; readonly testProfileId: string; } -// @public -export interface TestProfileRunClientTestProfileRun { - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - readonly durationInSeconds?: number; - readonly endDateTime?: Date; - readonly errorDetails?: TestProfileRunClientErrorDetails[]; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - readonly recommendations?: TestProfileRunClientTestProfileRunRecommendation[]; - readonly startDateTime?: Date; - readonly status?: TestProfileRunClientTestProfileRunStatus; - readonly targetResourceConfigurations?: TestProfileRunClientTargetResourceConfigurationsUnion; - readonly targetResourceId?: string; - testProfileId?: string; - readonly testProfileRunId: string; - readonly testRunDetails?: Record; +// @public (undocumented) +export class TestProfileAdministrationClient { + constructor(endpointParam: string, credential: TokenCredential, options?: TestProfileAdministrationClientOptionalParams); + createOrUpdateTestProfile(testProfileId: string, body: TestProfile, options?: CreateOrUpdateTestProfileOptionalParams): Promise; + deleteTestProfile(testProfileId: string, options?: DeleteTestProfileOptionalParams): Promise; + getTestProfile(testProfileId: string, options?: GetTestProfileOptionalParams): Promise; + listTestProfiles(options?: ListTestProfilesOptionalParams): PagedAsyncIterableIterator; + readonly pipeline: Pipeline; } // @public -export interface TestProfileRunClientTestProfileRunRecommendation { - category: TestProfileRunClientRecommendationCategory; - configurations?: string[]; +export interface TestProfileAdministrationClientOptionalParams extends ClientOptions { + apiVersion?: string; } // @public -export type TestProfileRunClientTestProfileRunStatus = string; - -// @public -export interface TestProfileRunClientTestRun { - autoStopCriteria?: TestProfileRunClientAutoStopCriteria; - certificate?: TestProfileRunClientCertificateMetadata; +export interface TestProfileRun { readonly createdBy?: string; readonly createdDateTime?: Date; - debugLogsEnabled?: boolean; description?: string; displayName?: string; - readonly duration?: number; + readonly durationInSeconds?: number; readonly endDateTime?: Date; - environmentVariables?: Record; - readonly errorDetails?: TestProfileRunClientErrorDetails[]; - readonly executedDateTime?: Date; - readonly kind?: TestProfileRunClientTestKind; + readonly errorDetails?: ErrorDetails[]; readonly lastModifiedBy?: string; readonly lastModifiedDateTime?: Date; - loadTestConfiguration?: TestProfileRunClientLoadTestConfiguration; - passFailCriteria?: TestProfileRunClientPassFailCriteria; - readonly portalUrl?: string; - readonly publicIPDisabled?: boolean; - readonly regionalStatistics?: Record; - requestDataLevel?: TestProfileRunClientRequestDataLevel; - secrets?: Record; + readonly recommendations?: TestProfileRunRecommendation[]; readonly startDateTime?: Date; - readonly status?: TestProfileRunClientStatus; - readonly subnetId?: string; - readonly testArtifacts?: TestProfileRunClientTestRunArtifacts; - testId?: string; - readonly testResult?: TestProfileRunClientPFTestResult; - readonly testRunId: string; - readonly testRunStatistics?: Record; - readonly virtualUsers?: number; -} - -// @public -export interface TestProfileRunClientTestRunAppComponents { - components: Record; - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - readonly testRunId?: string; -} - -// @public -export interface TestProfileRunClientTestRunArtifacts { - readonly inputArtifacts?: TestProfileRunClientTestRunInputArtifacts; - outputArtifacts?: TestProfileRunClientTestRunOutputArtifacts; -} - -// @public -export interface TestProfileRunClientTestRunDetail { - configurationId: string; - properties: Record; - status: TestProfileRunClientStatus; -} - -// @public -export interface TestProfileRunClientTestRunFileInfo { - readonly expireDateTime?: Date; - fileName: string; - readonly fileType?: TestProfileRunClientFileType; - readonly url?: string; - readonly validationFailureDetails?: string; - readonly validationStatus?: TestProfileRunClientFileStatus; -} - -// @public -export interface TestProfileRunClientTestRunInputArtifacts { - readonly additionalFileInfo?: TestProfileRunClientTestRunFileInfo[]; - configFileInfo?: TestProfileRunClientTestRunFileInfo; - inputArtifactsZipFileInfo?: TestProfileRunClientTestRunFileInfo; - testScriptFileInfo?: TestProfileRunClientTestRunFileInfo; - urlTestConfigFileInfo?: TestProfileRunClientTestRunFileInfo; - userPropFileInfo?: TestProfileRunClientTestRunFileInfo; -} - -// @public -export interface TestProfileRunClientTestRunOutputArtifacts { - artifactsContainerInfo?: TestProfileRunClientArtifactsContainerInfo; - logsFileInfo?: TestProfileRunClientTestRunFileInfo; - reportFileInfo?: TestProfileRunClientTestRunFileInfo; - resultFileInfo?: TestProfileRunClientTestRunFileInfo; -} - -// @public -export interface TestProfileRunClientTestRunServerMetricConfig { - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - metrics?: Record; - readonly testRunId?: string; -} - -// @public -export interface TestProfileRunClientTestRunStatistics { - readonly errorCount?: number; - readonly errorPct?: number; - readonly maxResTime?: number; - readonly meanResTime?: number; - readonly medianResTime?: number; - readonly minResTime?: number; - readonly pct1ResTime?: number; - readonly pct2ResTime?: number; - readonly pct3ResTime?: number; - readonly pct75ResTime?: number; - readonly pct96ResTime?: number; - readonly pct97ResTime?: number; - readonly pct98ResTime?: number; - readonly pct9999ResTime?: number; - readonly pct999ResTime?: number; - readonly receivedKBytesPerSec?: number; - readonly sampleCount?: number; - readonly sentKBytesPerSec?: number; - readonly throughput?: number; - readonly transaction?: string; + readonly status?: TestProfileRunStatus; + readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; + readonly targetResourceId?: string; + testProfileId?: string; + readonly testProfileRunId: string; + readonly testRunDetails?: Record; } -// @public -export interface TestProfileRunClientTestServerMetricConfig { - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - metrics: Record; - readonly testId?: string; +// @public (undocumented) +export class TestProfileRunClient { + constructor(endpointParam: string, credential: TokenCredential, options?: TestProfileRunClientOptionalParams); + createOrUpdateTestProfileRun(testProfileRunId: string, body: TestProfileRun, options?: CreateOrUpdateTestProfileRunOptionalParams): Promise; + deleteTestProfileRun(testProfileRunId: string, options?: DeleteTestProfileRunOptionalParams): Promise; + getTestProfileRun(testProfileRunId: string, options?: GetTestProfileRunOptionalParams): Promise; + listTestProfileRuns(options?: ListTestProfileRunsOptionalParams): PagedAsyncIterableIterator; + readonly pipeline: Pipeline; + stopTestProfileRun(testProfileRunId: string, options?: StopTestProfileRunOptionalParams): Promise; } // @public -export type TestProfileRunClientTimeGrain = string; - -// @public -export interface TestProfileRunClientTimeSeriesElement { - data?: TestProfileRunClientMetricValue[]; - dimensionValues?: TestProfileRunClientDimensionValue[]; +export interface TestProfileRunClientOptionalParams extends ClientOptions { + apiVersion?: string; } // @public diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts index 3b3ebc9a03..2879d059ec 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts @@ -7,10 +7,7 @@ import { PagedAsyncIterableIterator, } from "./static-helpers/pagingHelpers.js"; -export { - LoadTestAdministrationClient, - LoadTestAdministrationClientOptionalParams, -} from "./loadTestAdministration/loadTestAdministrationClient.js"; +export { LoadTestAdministrationClient } from "./loadTestAdministration/loadTestAdministrationClient.js"; export { Test, PassFailCriteria, @@ -45,7 +42,6 @@ export { AppComponent, TestServerMetricConfig, ResourceMetric, - APIVersions, TestRun, ErrorDetails, TestRunStatistics, @@ -62,8 +58,6 @@ export { RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -73,6 +67,8 @@ export { KnownMetricUnit, MetricUnit, MetricAvailability, + KnownTimeGrain, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -82,10 +78,11 @@ export { DimensionValue, TestProfile, TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, + TargetResourceConfigurationsUnion, KnownResourceKind, ResourceKind, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, TestProfileRun, KnownTestProfileRunStatus, TestProfileRunStatus, @@ -93,7 +90,9 @@ export { TestProfileRunRecommendation, KnownRecommendationCategory, RecommendationCategory, - TargetResourceConfigurationsUnion, +} from "./models/index.js"; +export { + LoadTestAdministrationClientOptionalParams, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, @@ -106,95 +105,11 @@ export { UploadTestFileOptionalParams, DeleteTestFileOptionalParams, DeleteTestOptionalParams, -} from "./loadTestAdministration/models/index.js"; +} from "./loadTestAdministration/api/index.js"; export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; +export { LoadTestRunClient } from "./loadTestRun/loadTestRunClient.js"; export { - LoadTestRunClient, LoadTestRunClientOptionalParams, -} from "./loadTestRun/loadTestRunClient.js"; -export { - Test as LoadTestRunClientTest, - PassFailCriteria as LoadTestRunClientPassFailCriteria, - PassFailMetric as LoadTestRunClientPassFailMetric, - KnownPFMetrics as LoadTestRunClientKnownPFMetrics, - PFMetrics as LoadTestRunClientPFMetrics, - KnownPFAgFunc as LoadTestRunClientKnownPFAgFunc, - PFAgFunc as LoadTestRunClientPFAgFunc, - KnownPFAction as LoadTestRunClientKnownPFAction, - PFAction as LoadTestRunClientPFAction, - KnownPFResult as LoadTestRunClientKnownPFResult, - PFResult as LoadTestRunClientPFResult, - AutoStopCriteria as LoadTestRunClientAutoStopCriteria, - Secret as LoadTestRunClientSecret, - KnownSecretType as LoadTestRunClientKnownSecretType, - SecretType as LoadTestRunClientSecretType, - CertificateMetadata as LoadTestRunClientCertificateMetadata, - KnownCertificateType as LoadTestRunClientKnownCertificateType, - CertificateType as LoadTestRunClientCertificateType, - LoadTestConfiguration as LoadTestRunClientLoadTestConfiguration, - OptionalLoadTestConfig as LoadTestRunClientOptionalLoadTestConfig, - RegionalConfiguration as LoadTestRunClientRegionalConfiguration, - TestInputArtifacts as LoadTestRunClientTestInputArtifacts, - TestFileInfo as LoadTestRunClientTestFileInfo, - KnownFileType as LoadTestRunClientKnownFileType, - FileType as LoadTestRunClientFileType, - KnownFileStatus as LoadTestRunClientKnownFileStatus, - FileStatus as LoadTestRunClientFileStatus, - KnownTestKind as LoadTestRunClientKnownTestKind, - TestKind as LoadTestRunClientTestKind, - TestAppComponents as LoadTestRunClientTestAppComponents, - AppComponent as LoadTestRunClientAppComponent, - TestServerMetricConfig as LoadTestRunClientTestServerMetricConfig, - ResourceMetric as LoadTestRunClientResourceMetric, - APIVersions as LoadTestRunClientAPIVersions, - TestRun as LoadTestRunClientTestRun, - ErrorDetails as LoadTestRunClientErrorDetails, - TestRunStatistics as LoadTestRunClientTestRunStatistics, - TestRunArtifacts as LoadTestRunClientTestRunArtifacts, - TestRunInputArtifacts as LoadTestRunClientTestRunInputArtifacts, - TestRunFileInfo as LoadTestRunClientTestRunFileInfo, - TestRunOutputArtifacts as LoadTestRunClientTestRunOutputArtifacts, - ArtifactsContainerInfo as LoadTestRunClientArtifactsContainerInfo, - KnownPFTestResult as LoadTestRunClientKnownPFTestResult, - PFTestResult as LoadTestRunClientPFTestResult, - KnownStatus as LoadTestRunClientKnownStatus, - Status as LoadTestRunClientStatus, - KnownRequestDataLevel as LoadTestRunClientKnownRequestDataLevel, - RequestDataLevel as LoadTestRunClientRequestDataLevel, - TestRunAppComponents as LoadTestRunClientTestRunAppComponents, - TestRunServerMetricConfig as LoadTestRunClientTestRunServerMetricConfig, - KnownTimeGrain as LoadTestRunClientKnownTimeGrain, - TimeGrain as LoadTestRunClientTimeGrain, - DimensionValueList as LoadTestRunClientDimensionValueList, - MetricDefinitionCollection as LoadTestRunClientMetricDefinitionCollection, - MetricDefinition as LoadTestRunClientMetricDefinition, - NameAndDesc as LoadTestRunClientNameAndDesc, - KnownAggregationType as LoadTestRunClientKnownAggregationType, - AggregationType as LoadTestRunClientAggregationType, - KnownMetricUnit as LoadTestRunClientKnownMetricUnit, - MetricUnit as LoadTestRunClientMetricUnit, - MetricAvailability as LoadTestRunClientMetricAvailability, - MetricNamespaceCollection as LoadTestRunClientMetricNamespaceCollection, - MetricNamespace as LoadTestRunClientMetricNamespace, - MetricRequestPayload as LoadTestRunClientMetricRequestPayload, - DimensionFilter as LoadTestRunClientDimensionFilter, - TimeSeriesElement as LoadTestRunClientTimeSeriesElement, - MetricValue as LoadTestRunClientMetricValue, - DimensionValue as LoadTestRunClientDimensionValue, - TestProfile as LoadTestRunClientTestProfile, - TargetResourceConfigurations as LoadTestRunClientTargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations as LoadTestRunClientFunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration as LoadTestRunClientFunctionFlexConsumptionResourceConfiguration, - KnownResourceKind as LoadTestRunClientKnownResourceKind, - ResourceKind as LoadTestRunClientResourceKind, - TestProfileRun as LoadTestRunClientTestProfileRun, - KnownTestProfileRunStatus as LoadTestRunClientKnownTestProfileRunStatus, - TestProfileRunStatus as LoadTestRunClientTestProfileRunStatus, - TestRunDetail as LoadTestRunClientTestRunDetail, - TestProfileRunRecommendation as LoadTestRunClientTestProfileRunRecommendation, - KnownRecommendationCategory as LoadTestRunClientKnownRecommendationCategory, - RecommendationCategory as LoadTestRunClientRecommendationCategory, - TargetResourceConfigurationsUnion as LoadTestRunClientTargetResourceConfigurationsUnion, CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams as LoadTestRunClientCreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams as LoadTestRunClientCreateOrUpdateServerMetricsConfigOptionalParams, @@ -209,189 +124,21 @@ export { ListMetricsOptionalParams, ListTestRunsOptionalParams, StopTestRunOptionalParams, -} from "./loadTestRun/models/index.js"; -export { - TestProfileAdministrationClient, - TestProfileAdministrationClientOptionalParams, -} from "./testProfileAdministration/testProfileAdministrationClient.js"; +} from "./loadTestRun/api/index.js"; +export { TestProfileAdministrationClient } from "./testProfileAdministration/testProfileAdministrationClient.js"; export { - Test as TestProfileAdministrationClientTest, - PassFailCriteria as TestProfileAdministrationClientPassFailCriteria, - PassFailMetric as TestProfileAdministrationClientPassFailMetric, - KnownPFMetrics as TestProfileAdministrationClientKnownPFMetrics, - PFMetrics as TestProfileAdministrationClientPFMetrics, - KnownPFAgFunc as TestProfileAdministrationClientKnownPFAgFunc, - PFAgFunc as TestProfileAdministrationClientPFAgFunc, - KnownPFAction as TestProfileAdministrationClientKnownPFAction, - PFAction as TestProfileAdministrationClientPFAction, - KnownPFResult as TestProfileAdministrationClientKnownPFResult, - PFResult as TestProfileAdministrationClientPFResult, - AutoStopCriteria as TestProfileAdministrationClientAutoStopCriteria, - Secret as TestProfileAdministrationClientSecret, - KnownSecretType as TestProfileAdministrationClientKnownSecretType, - SecretType as TestProfileAdministrationClientSecretType, - CertificateMetadata as TestProfileAdministrationClientCertificateMetadata, - KnownCertificateType as TestProfileAdministrationClientKnownCertificateType, - CertificateType as TestProfileAdministrationClientCertificateType, - LoadTestConfiguration as TestProfileAdministrationClientLoadTestConfiguration, - OptionalLoadTestConfig as TestProfileAdministrationClientOptionalLoadTestConfig, - RegionalConfiguration as TestProfileAdministrationClientRegionalConfiguration, - TestInputArtifacts as TestProfileAdministrationClientTestInputArtifacts, - TestFileInfo as TestProfileAdministrationClientTestFileInfo, - KnownFileType as TestProfileAdministrationClientKnownFileType, - FileType as TestProfileAdministrationClientFileType, - KnownFileStatus as TestProfileAdministrationClientKnownFileStatus, - FileStatus as TestProfileAdministrationClientFileStatus, - KnownTestKind as TestProfileAdministrationClientKnownTestKind, - TestKind as TestProfileAdministrationClientTestKind, - TestAppComponents as TestProfileAdministrationClientTestAppComponents, - AppComponent as TestProfileAdministrationClientAppComponent, - TestServerMetricConfig as TestProfileAdministrationClientTestServerMetricConfig, - ResourceMetric as TestProfileAdministrationClientResourceMetric, - APIVersions as TestProfileAdministrationClientAPIVersions, - TestRun as TestProfileAdministrationClientTestRun, - ErrorDetails as TestProfileAdministrationClientErrorDetails, - TestRunStatistics as TestProfileAdministrationClientTestRunStatistics, - TestRunArtifacts as TestProfileAdministrationClientTestRunArtifacts, - TestRunInputArtifacts as TestProfileAdministrationClientTestRunInputArtifacts, - TestRunFileInfo as TestProfileAdministrationClientTestRunFileInfo, - TestRunOutputArtifacts as TestProfileAdministrationClientTestRunOutputArtifacts, - ArtifactsContainerInfo as TestProfileAdministrationClientArtifactsContainerInfo, - KnownPFTestResult as TestProfileAdministrationClientKnownPFTestResult, - PFTestResult as TestProfileAdministrationClientPFTestResult, - KnownStatus as TestProfileAdministrationClientKnownStatus, - Status as TestProfileAdministrationClientStatus, - KnownRequestDataLevel as TestProfileAdministrationClientKnownRequestDataLevel, - RequestDataLevel as TestProfileAdministrationClientRequestDataLevel, - TestRunAppComponents as TestProfileAdministrationClientTestRunAppComponents, - TestRunServerMetricConfig as TestProfileAdministrationClientTestRunServerMetricConfig, - KnownTimeGrain as TestProfileAdministrationClientKnownTimeGrain, - TimeGrain as TestProfileAdministrationClientTimeGrain, - DimensionValueList as TestProfileAdministrationClientDimensionValueList, - MetricDefinitionCollection as TestProfileAdministrationClientMetricDefinitionCollection, - MetricDefinition as TestProfileAdministrationClientMetricDefinition, - NameAndDesc as TestProfileAdministrationClientNameAndDesc, - KnownAggregationType as TestProfileAdministrationClientKnownAggregationType, - AggregationType as TestProfileAdministrationClientAggregationType, - KnownMetricUnit as TestProfileAdministrationClientKnownMetricUnit, - MetricUnit as TestProfileAdministrationClientMetricUnit, - MetricAvailability as TestProfileAdministrationClientMetricAvailability, - MetricNamespaceCollection as TestProfileAdministrationClientMetricNamespaceCollection, - MetricNamespace as TestProfileAdministrationClientMetricNamespace, - MetricRequestPayload as TestProfileAdministrationClientMetricRequestPayload, - DimensionFilter as TestProfileAdministrationClientDimensionFilter, - TimeSeriesElement as TestProfileAdministrationClientTimeSeriesElement, - MetricValue as TestProfileAdministrationClientMetricValue, - DimensionValue as TestProfileAdministrationClientDimensionValue, - TestProfile as TestProfileAdministrationClientTestProfile, - TargetResourceConfigurations as TestProfileAdministrationClientTargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations as TestProfileAdministrationClientFunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration as TestProfileAdministrationClientFunctionFlexConsumptionResourceConfiguration, - KnownResourceKind as TestProfileAdministrationClientKnownResourceKind, - ResourceKind as TestProfileAdministrationClientResourceKind, - TestProfileRun as TestProfileAdministrationClientTestProfileRun, - KnownTestProfileRunStatus as TestProfileAdministrationClientKnownTestProfileRunStatus, - TestProfileRunStatus as TestProfileAdministrationClientTestProfileRunStatus, - TestRunDetail as TestProfileAdministrationClientTestRunDetail, - TestProfileRunRecommendation as TestProfileAdministrationClientTestProfileRunRecommendation, - KnownRecommendationCategory as TestProfileAdministrationClientKnownRecommendationCategory, - RecommendationCategory as TestProfileAdministrationClientRecommendationCategory, - TargetResourceConfigurationsUnion as TestProfileAdministrationClientTargetResourceConfigurationsUnion, CreateOrUpdateTestProfileOptionalParams, DeleteTestProfileOptionalParams, GetTestProfileOptionalParams, ListTestProfilesOptionalParams, -} from "./testProfileAdministration/models/index.js"; -export { - TestProfileRunClient, - TestProfileRunClientOptionalParams, -} from "./testProfileRun/testProfileRunClient.js"; + TestProfileAdministrationClientOptionalParams, +} from "./testProfileAdministration/api/index.js"; +export { TestProfileRunClient } from "./testProfileRun/testProfileRunClient.js"; export { - Test as TestProfileRunClientTest, - PassFailCriteria as TestProfileRunClientPassFailCriteria, - PassFailMetric as TestProfileRunClientPassFailMetric, - KnownPFMetrics as TestProfileRunClientKnownPFMetrics, - PFMetrics as TestProfileRunClientPFMetrics, - KnownPFAgFunc as TestProfileRunClientKnownPFAgFunc, - PFAgFunc as TestProfileRunClientPFAgFunc, - KnownPFAction as TestProfileRunClientKnownPFAction, - PFAction as TestProfileRunClientPFAction, - KnownPFResult as TestProfileRunClientKnownPFResult, - PFResult as TestProfileRunClientPFResult, - AutoStopCriteria as TestProfileRunClientAutoStopCriteria, - Secret as TestProfileRunClientSecret, - KnownSecretType as TestProfileRunClientKnownSecretType, - SecretType as TestProfileRunClientSecretType, - CertificateMetadata as TestProfileRunClientCertificateMetadata, - KnownCertificateType as TestProfileRunClientKnownCertificateType, - CertificateType as TestProfileRunClientCertificateType, - LoadTestConfiguration as TestProfileRunClientLoadTestConfiguration, - OptionalLoadTestConfig as TestProfileRunClientOptionalLoadTestConfig, - RegionalConfiguration as TestProfileRunClientRegionalConfiguration, - TestInputArtifacts as TestProfileRunClientTestInputArtifacts, - TestFileInfo as TestProfileRunClientTestFileInfo, - KnownFileType as TestProfileRunClientKnownFileType, - FileType as TestProfileRunClientFileType, - KnownFileStatus as TestProfileRunClientKnownFileStatus, - FileStatus as TestProfileRunClientFileStatus, - KnownTestKind as TestProfileRunClientKnownTestKind, - TestKind as TestProfileRunClientTestKind, - TestAppComponents as TestProfileRunClientTestAppComponents, - AppComponent as TestProfileRunClientAppComponent, - TestServerMetricConfig as TestProfileRunClientTestServerMetricConfig, - ResourceMetric as TestProfileRunClientResourceMetric, - APIVersions as TestProfileRunClientAPIVersions, - TestRun as TestProfileRunClientTestRun, - ErrorDetails as TestProfileRunClientErrorDetails, - TestRunStatistics as TestProfileRunClientTestRunStatistics, - TestRunArtifacts as TestProfileRunClientTestRunArtifacts, - TestRunInputArtifacts as TestProfileRunClientTestRunInputArtifacts, - TestRunFileInfo as TestProfileRunClientTestRunFileInfo, - TestRunOutputArtifacts as TestProfileRunClientTestRunOutputArtifacts, - ArtifactsContainerInfo as TestProfileRunClientArtifactsContainerInfo, - KnownPFTestResult as TestProfileRunClientKnownPFTestResult, - PFTestResult as TestProfileRunClientPFTestResult, - KnownStatus as TestProfileRunClientKnownStatus, - Status as TestProfileRunClientStatus, - KnownRequestDataLevel as TestProfileRunClientKnownRequestDataLevel, - RequestDataLevel as TestProfileRunClientRequestDataLevel, - TestRunAppComponents as TestProfileRunClientTestRunAppComponents, - TestRunServerMetricConfig as TestProfileRunClientTestRunServerMetricConfig, - KnownTimeGrain as TestProfileRunClientKnownTimeGrain, - TimeGrain as TestProfileRunClientTimeGrain, - DimensionValueList as TestProfileRunClientDimensionValueList, - MetricDefinitionCollection as TestProfileRunClientMetricDefinitionCollection, - MetricDefinition as TestProfileRunClientMetricDefinition, - NameAndDesc as TestProfileRunClientNameAndDesc, - KnownAggregationType as TestProfileRunClientKnownAggregationType, - AggregationType as TestProfileRunClientAggregationType, - KnownMetricUnit as TestProfileRunClientKnownMetricUnit, - MetricUnit as TestProfileRunClientMetricUnit, - MetricAvailability as TestProfileRunClientMetricAvailability, - MetricNamespaceCollection as TestProfileRunClientMetricNamespaceCollection, - MetricNamespace as TestProfileRunClientMetricNamespace, - MetricRequestPayload as TestProfileRunClientMetricRequestPayload, - DimensionFilter as TestProfileRunClientDimensionFilter, - TimeSeriesElement as TestProfileRunClientTimeSeriesElement, - MetricValue as TestProfileRunClientMetricValue, - DimensionValue as TestProfileRunClientDimensionValue, - TestProfile as TestProfileRunClientTestProfile, - TargetResourceConfigurations as TestProfileRunClientTargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations as TestProfileRunClientFunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration as TestProfileRunClientFunctionFlexConsumptionResourceConfiguration, - KnownResourceKind as TestProfileRunClientKnownResourceKind, - ResourceKind as TestProfileRunClientResourceKind, - TestProfileRun as TestProfileRunClientTestProfileRun, - KnownTestProfileRunStatus as TestProfileRunClientKnownTestProfileRunStatus, - TestProfileRunStatus as TestProfileRunClientTestProfileRunStatus, - TestRunDetail as TestProfileRunClientTestRunDetail, - TestProfileRunRecommendation as TestProfileRunClientTestProfileRunRecommendation, - KnownRecommendationCategory as TestProfileRunClientKnownRecommendationCategory, - RecommendationCategory as TestProfileRunClientRecommendationCategory, - TargetResourceConfigurationsUnion as TestProfileRunClientTargetResourceConfigurationsUnion, CreateOrUpdateTestProfileRunOptionalParams, DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, StopTestProfileRunOptionalParams, -} from "./testProfileRun/models/index.js"; + TestProfileRunClientOptionalParams, +} from "./testProfileRun/api/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/index.ts index 707a79129e..44e82f5edd 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/index.ts @@ -3,7 +3,7 @@ export { createLoadTestAdministration, - LoadTestServiceContext, + LoadTestAdministrationContext, LoadTestAdministrationClientOptionalParams, } from "./loadTestAdministrationContext.js"; export { @@ -20,3 +20,17 @@ export { deleteTestFile, deleteTest, } from "./operations.js"; +export { + CreateOrUpdateTestOptionalParams, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + GetAppComponentsOptionalParams, + GetServerMetricsConfigOptionalParams, + GetTestOptionalParams, + GetTestFileOptionalParams, + ListTestFilesOptionalParams, + ListTestsOptionalParams, + UploadTestFileOptionalParams, + DeleteTestFileOptionalParams, + DeleteTestOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/loadTestAdministrationContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/loadTestAdministrationContext.ts index 6e1db5fc08..ed947ed8f5 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/loadTestAdministrationContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/loadTestAdministrationContext.ts @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { TokenCredential } from "@azure/core-auth"; -export interface LoadTestServiceContext extends Client {} +export interface LoadTestAdministrationContext extends Client {} /** Optional parameters for the client. */ export interface LoadTestAdministrationClientOptionalParams @@ -18,7 +18,7 @@ export function createLoadTestAdministration( endpointParam: string, credential: TokenCredential, options: LoadTestAdministrationClientOptionalParams = {}, -): LoadTestServiceContext { +): LoadTestAdministrationContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/operations.ts index bffc61c559..c5da4f8cf1 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/operations.ts @@ -2,46 +2,47 @@ // Licensed under the MIT License. import { - passFailCriteriaSerializer, - autoStopCriteriaSerializer, - secretSerializer, - certificateMetadataSerializer, - loadTestConfigurationSerializer, - appComponentSerializer, - resourceMetricSerializer, + LoadTestAdministrationContext as Client, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + CreateOrUpdateTestOptionalParams, + DeleteTestFileOptionalParams, + DeleteTestOptionalParams, + GetAppComponentsOptionalParams, + GetServerMetricsConfigOptionalParams, + GetTestFileOptionalParams, + GetTestOptionalParams, + ListTestFilesOptionalParams, + ListTestsOptionalParams, + UploadTestFileOptionalParams, +} from "./index.js"; +import { Test, + testSerializer, + testDeserializer, TestFileInfo, + testFileInfoDeserializer, TestAppComponents, + testAppComponentsSerializer, + testAppComponentsDeserializer, TestServerMetricConfig, - _PagedTest, + testServerMetricConfigSerializer, + testServerMetricConfigDeserializer, _PagedTestFileInfo, -} from "../models/models.js"; -import { LoadTestServiceContext as Client } from "./index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; -import { serializeRecord } from "../../helpers/serializerHelpers.js"; + _pagedTestFileInfoDeserializer, + _PagedTest, + _pagedTestDeserializer, +} from "../../models/models.js"; import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../../static-helpers/pagingHelpers.js"; import { - CreateOrUpdateTestOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestOptionalParams, - GetTestFileOptionalParams, - ListTestFilesOptionalParams, - ListTestsOptionalParams, - UploadTestFileOptionalParams, - DeleteTestFileOptionalParams, - DeleteTestOptionalParams, -} from "../models/options.js"; + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; export function _createOrUpdateTestSend( context: Client, @@ -55,34 +56,7 @@ export function _createOrUpdateTestSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { - passFailCriteria: !body.passFailCriteria - ? body.passFailCriteria - : passFailCriteriaSerializer(body.passFailCriteria), - autoStopCriteria: !body.autoStopCriteria - ? body.autoStopCriteria - : autoStopCriteriaSerializer(body.autoStopCriteria), - secrets: !body.secrets - ? body.secrets - : (serializeRecord(body.secrets as any, secretSerializer) as any), - certificate: !body.certificate - ? body.certificate - : certificateMetadataSerializer(body.certificate), - environmentVariables: !body.environmentVariables - ? body.environmentVariables - : (serializeRecord(body.environmentVariables as any) as any), - loadTestConfiguration: !body.loadTestConfiguration - ? body.loadTestConfiguration - : loadTestConfigurationSerializer(body.loadTestConfiguration), - baselineTestRunId: body["baselineTestRunId"], - description: body["description"], - displayName: body["displayName"], - subnetId: body["subnetId"], - kind: body["kind"], - publicIPDisabled: body["publicIPDisabled"], - keyvaultReferenceIdentityType: body["keyvaultReferenceIdentityType"], - keyvaultReferenceIdentityId: body["keyvaultReferenceIdentityId"], - }, + body: testSerializer(body), }); } @@ -94,265 +68,7 @@ export async function _createOrUpdateTestDeserialize( throw createRestError(result); } - return { - passFailCriteria: !result.body.passFailCriteria - ? undefined - : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, - secrets: result.body["secrets"], - certificate: !result.body.certificate - ? undefined - : { - value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"], - name: result.body.certificate?.["name"], - }, - environmentVariables: result.body["environmentVariables"], - loadTestConfiguration: !result.body.loadTestConfiguration - ? undefined - : { - engineInstances: - result.body.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: result.body.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: result.body.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !result.body.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], - virtualUsers: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, - regionalLoadTestConfig: - result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] - : result.body.loadTestConfiguration?.[ - "regionalLoadTestConfig" - ].map((p: any) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }), - }, - baselineTestRunId: result.body["baselineTestRunId"], - inputArtifacts: !result.body.inputArtifacts - ? undefined - : { - configFileInfo: !result.body.inputArtifacts?.configFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.configFileInfo?.["fileName"], - url: result.body.inputArtifacts?.configFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.configFileInfo?.["fileType"], - expireDateTime: - result.body.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.configFileInfo?.[ - "validationFailureDetails" - ], - }, - testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], - expireDateTime: - result.body.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.testScriptFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.testScriptFileInfo?.[ - "validationFailureDetails" - ], - }, - userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.userPropFileInfo?.["fileName"], - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.userPropFileInfo?.["fileType"], - expireDateTime: - result.body.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.userPropFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.userPropFileInfo?.[ - "validationFailureDetails" - ], - }, - inputArtifactsZipFileInfo: !result.body.inputArtifacts - ?.inputArtifactsZipFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "fileName" - ], - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], - fileType: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "fileType" - ], - expireDateTime: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationFailureDetails" - ], - }, - urlTestConfigFileInfo: !result.body.inputArtifacts - ?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileName" - ], - url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileType" - ], - expireDateTime: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, - additionalFileInfo: - result.body.inputArtifacts?.["additionalFileInfo"] === undefined - ? result.body.inputArtifacts?.["additionalFileInfo"] - : result.body.inputArtifacts?.["additionalFileInfo"].map( - (p: any) => { - return { - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"], - validationFailureDetails: p["validationFailureDetails"], - }; - }, - ), - }, - testId: result.body["testId"], - description: result.body["description"], - displayName: result.body["displayName"], - subnetId: result.body["subnetId"], - kind: result.body["kind"], - publicIPDisabled: result.body["publicIPDisabled"], - keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], - keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testDeserializer(result.body); } /** Create a new test or update an existing test by providing the test Id. */ @@ -378,12 +94,7 @@ export function _createOrUpdateAppComponentsSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { - components: serializeRecord( - body.components as any, - appComponentSerializer, - ) as any, - }, + body: testAppComponentsSerializer(body), }); } @@ -395,20 +106,7 @@ export async function _createOrUpdateAppComponentsDeserialize( throw createRestError(result); } - return { - components: result.body["components"], - testId: result.body["testId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testAppComponentsDeserializer(result.body); } /** Add an app component to a test by providing the resource Id, name and type. */ @@ -441,12 +139,7 @@ export function _createOrUpdateServerMetricsConfigSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { - metrics: serializeRecord( - body.metrics as any, - resourceMetricSerializer, - ) as any, - }, + body: testServerMetricConfigSerializer(body), }); } @@ -458,20 +151,7 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( throw createRestError(result); } - return { - testId: result.body["testId"], - metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testServerMetricConfigDeserializer(result.body); } /** Configure server metrics for a test */ @@ -510,20 +190,7 @@ export async function _getAppComponentsDeserialize( throw createRestError(result); } - return { - components: result.body["components"], - testId: result.body["testId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testAppComponentsDeserializer(result.body); } /** Get associated app component (collection of azure resources) for the given test. */ @@ -554,20 +221,7 @@ export async function _getServerMetricsConfigDeserialize( throw createRestError(result); } - return { - testId: result.body["testId"], - metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testServerMetricConfigDeserializer(result.body); } /** List server metrics configuration for the given test. */ @@ -598,265 +252,7 @@ export async function _getTestDeserialize( throw createRestError(result); } - return { - passFailCriteria: !result.body.passFailCriteria - ? undefined - : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, - secrets: result.body["secrets"], - certificate: !result.body.certificate - ? undefined - : { - value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"], - name: result.body.certificate?.["name"], - }, - environmentVariables: result.body["environmentVariables"], - loadTestConfiguration: !result.body.loadTestConfiguration - ? undefined - : { - engineInstances: - result.body.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: result.body.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: result.body.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !result.body.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], - virtualUsers: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, - regionalLoadTestConfig: - result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] - : result.body.loadTestConfiguration?.[ - "regionalLoadTestConfig" - ].map((p: any) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }), - }, - baselineTestRunId: result.body["baselineTestRunId"], - inputArtifacts: !result.body.inputArtifacts - ? undefined - : { - configFileInfo: !result.body.inputArtifacts?.configFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.configFileInfo?.["fileName"], - url: result.body.inputArtifacts?.configFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.configFileInfo?.["fileType"], - expireDateTime: - result.body.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.configFileInfo?.[ - "validationFailureDetails" - ], - }, - testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], - expireDateTime: - result.body.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.testScriptFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.testScriptFileInfo?.[ - "validationFailureDetails" - ], - }, - userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.userPropFileInfo?.["fileName"], - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.userPropFileInfo?.["fileType"], - expireDateTime: - result.body.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.userPropFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.userPropFileInfo?.[ - "validationFailureDetails" - ], - }, - inputArtifactsZipFileInfo: !result.body.inputArtifacts - ?.inputArtifactsZipFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "fileName" - ], - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], - fileType: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "fileType" - ], - expireDateTime: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationFailureDetails" - ], - }, - urlTestConfigFileInfo: !result.body.inputArtifacts - ?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileName" - ], - url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileType" - ], - expireDateTime: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, - additionalFileInfo: - result.body.inputArtifacts?.["additionalFileInfo"] === undefined - ? result.body.inputArtifacts?.["additionalFileInfo"] - : result.body.inputArtifacts?.["additionalFileInfo"].map( - (p: any) => { - return { - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"], - validationFailureDetails: p["validationFailureDetails"], - }; - }, - ), - }, - testId: result.body["testId"], - description: result.body["description"], - displayName: result.body["displayName"], - subnetId: result.body["subnetId"], - kind: result.body["kind"], - publicIPDisabled: result.body["publicIPDisabled"], - keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], - keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testDeserializer(result.body); } /** Get load test details by test Id */ @@ -888,17 +284,7 @@ export async function _getTestFileDeserialize( throw createRestError(result); } - return { - fileName: result.body["fileName"], - url: result.body["url"], - fileType: result.body["fileType"], - expireDateTime: - result.body["expireDateTime"] !== undefined - ? new Date(result.body["expireDateTime"]) - : undefined, - validationStatus: result.body["validationStatus"], - validationFailureDetails: result.body["validationFailureDetails"], - }; + return testFileInfoDeserializer(result.body); } /** Get all the files that are associated with a test. */ @@ -930,22 +316,7 @@ export async function _listTestFilesDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"], - validationFailureDetails: p["validationFailureDetails"], - }; - }), - nextLink: result.body["nextLink"], - }; + return _pagedTestFileInfoDeserializer(result.body); } /** Get all test files. */ @@ -989,246 +360,7 @@ export async function _listTestsDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - passFailCriteria: !p.passFailCriteria - ? undefined - : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !p.autoStopCriteria - ? undefined - : { - autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], - errorRate: p.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, - secrets: p["secrets"], - certificate: !p.certificate - ? undefined - : { - value: p.certificate?.["value"], - type: p.certificate?.["type"], - name: p.certificate?.["name"], - }, - environmentVariables: p["environmentVariables"], - loadTestConfiguration: !p.loadTestConfiguration - ? undefined - : { - engineInstances: p.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: p.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: p.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !p.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], - requestsPerSecond: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], - virtualUsers: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, - regionalLoadTestConfig: - p.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? p.loadTestConfiguration?.["regionalLoadTestConfig"] - : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( - (p: any) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }, - ), - }, - baselineTestRunId: p["baselineTestRunId"], - inputArtifacts: !p.inputArtifacts - ? undefined - : { - configFileInfo: !p.inputArtifacts?.configFileInfo - ? undefined - : { - fileName: p.inputArtifacts?.configFileInfo?.["fileName"], - url: p.inputArtifacts?.configFileInfo?.["url"], - fileType: p.inputArtifacts?.configFileInfo?.["fileType"], - expireDateTime: - p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - p.inputArtifacts?.configFileInfo?.["validationStatus"], - validationFailureDetails: - p.inputArtifacts?.configFileInfo?.[ - "validationFailureDetails" - ], - }, - testScriptFileInfo: !p.inputArtifacts?.testScriptFileInfo - ? undefined - : { - fileName: - p.inputArtifacts?.testScriptFileInfo?.["fileName"], - url: p.inputArtifacts?.testScriptFileInfo?.["url"], - fileType: - p.inputArtifacts?.testScriptFileInfo?.["fileType"], - expireDateTime: - p.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - p.inputArtifacts?.testScriptFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - p.inputArtifacts?.testScriptFileInfo?.[ - "validationFailureDetails" - ], - }, - userPropFileInfo: !p.inputArtifacts?.userPropFileInfo - ? undefined - : { - fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], - url: p.inputArtifacts?.userPropFileInfo?.["url"], - fileType: p.inputArtifacts?.userPropFileInfo?.["fileType"], - expireDateTime: - p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - p.inputArtifacts?.userPropFileInfo?.["validationStatus"], - validationFailureDetails: - p.inputArtifacts?.userPropFileInfo?.[ - "validationFailureDetails" - ], - }, - inputArtifactsZipFileInfo: !p.inputArtifacts - ?.inputArtifactsZipFileInfo - ? undefined - : { - fileName: - p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileName"], - url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], - fileType: - p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileType"], - expireDateTime: - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationFailureDetails" - ], - }, - urlTestConfigFileInfo: !p.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - p.inputArtifacts?.urlTestConfigFileInfo?.["fileName"], - url: p.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: - p.inputArtifacts?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, - additionalFileInfo: - p.inputArtifacts?.["additionalFileInfo"] === undefined - ? p.inputArtifacts?.["additionalFileInfo"] - : p.inputArtifacts?.["additionalFileInfo"].map((p: any) => { - return { - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"], - validationFailureDetails: p["validationFailureDetails"], - }; - }), - }, - testId: p["testId"], - description: p["description"], - displayName: p["displayName"], - subnetId: p["subnetId"], - kind: p["kind"], - publicIPDisabled: p["publicIPDisabled"], - keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], - keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, - createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: p["lastModifiedBy"], - }; - }), - nextLink: result.body["nextLink"], - }; + return _pagedTestDeserializer(result.body); } /** @@ -1273,17 +405,7 @@ export async function _uploadTestFileDeserialize( throw createRestError(result); } - return { - fileName: result.body["fileName"], - url: result.body["url"], - fileType: result.body["fileType"], - expireDateTime: - result.body["expireDateTime"] !== undefined - ? new Date(result.body["expireDateTime"]) - : undefined, - validationStatus: result.body["validationStatus"], - validationFailureDetails: result.body["validationFailureDetails"], - }; + return testFileInfoDeserializer(result.body); } /** diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/options.ts similarity index 97% rename from packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/options.ts rename to packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/options.ts index e4e6276f9e..5f76c93bb7 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/options.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { OperationOptions } from "@azure-rest/core-client"; -import { FileType } from "./models.js"; +import { FileType } from "../../models/models.js"; /** Optional parameters. */ export interface CreateOrUpdateTestOptionalParams extends OperationOptions { diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/index.ts index 67564508c5..8470bd3fad 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/index.ts @@ -1,93 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +export { LoadTestAdministrationClient } from "./loadTestAdministrationClient.js"; export { - LoadTestAdministrationClient, + LoadTestAdministrationContext, LoadTestAdministrationClientOptionalParams, -} from "./loadTestAdministrationClient.js"; -export { - Test, - PassFailCriteria, - PassFailMetric, - KnownPFMetrics, - PFMetrics, - KnownPFAgFunc, - PFAgFunc, - KnownPFAction, - PFAction, - KnownPFResult, - PFResult, - AutoStopCriteria, - Secret, - KnownSecretType, - SecretType, - CertificateMetadata, - KnownCertificateType, - CertificateType, - LoadTestConfiguration, - OptionalLoadTestConfig, - RegionalConfiguration, - TestInputArtifacts, - TestFileInfo, - KnownFileType, - FileType, - KnownFileStatus, - FileStatus, - KnownTestKind, - TestKind, - TestAppComponents, - AppComponent, - TestServerMetricConfig, - ResourceMetric, - APIVersions, - TestRun, - ErrorDetails, - TestRunStatistics, - TestRunArtifacts, - TestRunInputArtifacts, - TestRunFileInfo, - TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, - PFTestResult, - KnownStatus, - Status, - KnownRequestDataLevel, - RequestDataLevel, - TestRunAppComponents, - TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, - DimensionValueList, - MetricDefinitionCollection, - MetricDefinition, - NameAndDesc, - KnownAggregationType, - AggregationType, - KnownMetricUnit, - MetricUnit, - MetricAvailability, - MetricNamespaceCollection, - MetricNamespace, - MetricRequestPayload, - DimensionFilter, - TimeSeriesElement, - MetricValue, - DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, @@ -100,4 +17,4 @@ export { UploadTestFileOptionalParams, DeleteTestFileOptionalParams, DeleteTestOptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/loadTestAdministrationClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/loadTestAdministrationClient.ts index 83e3ad8874..26d29333d3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/loadTestAdministrationClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/loadTestAdministrationClient.ts @@ -1,31 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; -import { - Test, - TestFileInfo, - TestAppComponents, - TestServerMetricConfig, -} from "./models/models.js"; -import { - CreateOrUpdateTestOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestOptionalParams, - GetTestFileOptionalParams, - ListTestFilesOptionalParams, - ListTestsOptionalParams, - UploadTestFileOptionalParams, - DeleteTestFileOptionalParams, - DeleteTestOptionalParams, -} from "./models/options.js"; import { createLoadTestAdministration, - LoadTestServiceContext, + LoadTestAdministrationContext, LoadTestAdministrationClientOptionalParams, createOrUpdateTest, createOrUpdateAppComponents, @@ -39,13 +17,33 @@ import { uploadTestFile, deleteTestFile, deleteTest, + CreateOrUpdateTestOptionalParams, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + GetAppComponentsOptionalParams, + GetServerMetricsConfigOptionalParams, + GetTestOptionalParams, + GetTestFileOptionalParams, + ListTestFilesOptionalParams, + ListTestsOptionalParams, + UploadTestFileOptionalParams, + DeleteTestFileOptionalParams, + DeleteTestOptionalParams, } from "./api/index.js"; +import { + Test, + TestFileInfo, + TestAppComponents, + TestServerMetricConfig, +} from "../models/models.js"; import { PagedAsyncIterableIterator } from "../static-helpers/pagingHelpers.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TokenCredential } from "@azure/core-auth"; export { LoadTestAdministrationClientOptionalParams } from "./api/loadTestAdministrationContext.js"; export class LoadTestAdministrationClient { - private _client: LoadTestServiceContext; + private _client: LoadTestAdministrationContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/index.ts deleted file mode 100644 index 785238fbf7..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/index.ts +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -export { - Test, - PassFailCriteria, - PassFailMetric, - KnownPFMetrics, - PFMetrics, - KnownPFAgFunc, - PFAgFunc, - KnownPFAction, - PFAction, - KnownPFResult, - PFResult, - AutoStopCriteria, - Secret, - KnownSecretType, - SecretType, - CertificateMetadata, - KnownCertificateType, - CertificateType, - LoadTestConfiguration, - OptionalLoadTestConfig, - RegionalConfiguration, - TestInputArtifacts, - TestFileInfo, - KnownFileType, - FileType, - KnownFileStatus, - FileStatus, - KnownTestKind, - TestKind, - TestAppComponents, - AppComponent, - TestServerMetricConfig, - ResourceMetric, - APIVersions, - TestRun, - ErrorDetails, - TestRunStatistics, - TestRunArtifacts, - TestRunInputArtifacts, - TestRunFileInfo, - TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, - PFTestResult, - KnownStatus, - Status, - KnownRequestDataLevel, - RequestDataLevel, - TestRunAppComponents, - TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, - DimensionValueList, - MetricDefinitionCollection, - MetricDefinition, - NameAndDesc, - KnownAggregationType, - AggregationType, - KnownMetricUnit, - MetricUnit, - MetricAvailability, - MetricNamespaceCollection, - MetricNamespace, - MetricRequestPayload, - DimensionFilter, - TimeSeriesElement, - MetricValue, - DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, -} from "./models.js"; -export { - CreateOrUpdateTestOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestOptionalParams, - GetTestFileOptionalParams, - ListTestFilesOptionalParams, - ListTestsOptionalParams, - UploadTestFileOptionalParams, - DeleteTestFileOptionalParams, - DeleteTestOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/models.ts deleted file mode 100644 index 046c225d0a..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/models.ts +++ /dev/null @@ -1,1615 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { serializeRecord } from "../../helpers/serializerHelpers.js"; - -/** Load test model. */ -export interface Test { - /** Pass fail criteria for a test. */ - passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; - /** - * Secrets can be stored in an Azure Key Vault or any other secret store. If the - * secret is stored in an Azure Key Vault, the value should be the secret - * identifier and the type should be AKV_SECRET_URI. If the secret is stored - * elsewhere, the secret value should be provided directly and the type should be - * SECRET_VALUE. - */ - secrets?: Record; - /** Certificates metadata. */ - certificate?: CertificateMetadata; - /** Environment variables which are defined as a set of pairs. */ - environmentVariables?: Record; - /** The load test configuration. */ - loadTestConfiguration?: LoadTestConfiguration; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; - /** The input artifacts for the test. */ - readonly inputArtifacts?: TestInputArtifacts; - /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testId: string; - /** The test description. */ - description?: string; - /** Display name of a test. */ - displayName?: string; - /** Subnet ID on which the load test instances should run. */ - subnetId?: string; - /** Kind of test. */ - kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; - /** Type of the managed identity referencing the Key vault. */ - keyvaultReferenceIdentityType?: string; - /** Resource Id of the managed identity referencing the Key vault. */ - keyvaultReferenceIdentityId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testSerializer(item: Test): Record { - return { - passFailCriteria: !item.passFailCriteria - ? item.passFailCriteria - : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), - secrets: !item.secrets - ? item.secrets - : (serializeRecord(item.secrets as any, secretSerializer) as any), - certificate: !item.certificate - ? item.certificate - : certificateMetadataSerializer(item.certificate), - environmentVariables: !item.environmentVariables - ? item.environmentVariables - : (serializeRecord(item.environmentVariables as any) as any), - loadTestConfiguration: !item.loadTestConfiguration - ? item.loadTestConfiguration - : loadTestConfigurationSerializer(item.loadTestConfiguration), - baselineTestRunId: item["baselineTestRunId"], - description: item["description"], - displayName: item["displayName"], - subnetId: item["subnetId"], - kind: item["kind"], - publicIPDisabled: item["publicIPDisabled"], - keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], - keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], - }; -} - -/** Pass fail criteria for a test. */ -export interface PassFailCriteria { - /** Map of id and pass fail metrics { id : pass fail metrics }. */ - passFailMetrics?: Record; -} - -export function passFailCriteriaSerializer( - item: PassFailCriteria, -): Record { - return { - passFailMetrics: !item.passFailMetrics - ? item.passFailMetrics - : (serializeRecord( - item.passFailMetrics as any, - passFailMetricSerializer, - ) as any), - }; -} - -/** Pass fail metric */ -export interface PassFailMetric { - /** The client metric on which the criteria should be applied. */ - clientMetric?: PFMetrics; - /** - * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, - * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, - * ‘count’ - for requests - */ - aggregate?: PFAgFunc; - /** The comparison operator. Supported types ‘>’, ‘<’ */ - condition?: string; - /** Request name for which the Pass fail criteria has to be applied */ - requestName?: string; - /** - * The value to compare with the client metric. Allowed values - ‘error : [0.0 , - * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. - */ - value?: number; - /** Action taken after the threshold is met. Default is ‘continue’. */ - action?: PFAction; - /** The actual value of the client metric for the test run. */ - readonly actualValue?: number; - /** Outcome of the test run. */ - readonly result?: PFResult; -} - -export function passFailMetricSerializer( - item: PassFailMetric, -): Record { - return { - clientMetric: item["clientMetric"], - aggregate: item["aggregate"], - condition: item["condition"], - requestName: item["requestName"], - value: item["value"], - action: item["action"], - }; -} - -/** Known values of {@link PFMetrics} that the service accepts. */ -export enum KnownPFMetrics { - /** response_time_ms */ - response_time_ms = "response_time_ms", - /** latency */ - latency = "latency", - /** error */ - error = "error", - /** requests */ - requests = "requests", - /** requests_per_sec */ - requests_per_sec = "requests_per_sec", -} - -/** - * Metrics for pass/fail criteria. \ - * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **response_time_ms** \ - * **latency** \ - * **error** \ - * **requests** \ - * **requests_per_sec** - */ -export type PFMetrics = string; - -/** Known values of {@link PFAgFunc} that the service accepts. */ -export enum KnownPFAgFunc { - /** count */ - count = "count", - /** percentage */ - percentage = "percentage", - /** avg */ - avg = "avg", - /** p50 */ - p50 = "p50", - /** p75 */ - p75 = "p75", - /** p90 */ - p90 = "p90", - /** p95 */ - p95 = "p95", - /** p96 */ - p96 = "p96", - /** p97 */ - p97 = "p97", - /** p98 */ - p98 = "p98", - /** p99 */ - p99 = "p99", - /** p99.9 */ - "p99.9" = "p99.9", - /** p99.99 */ - "p99.99" = "p99.99", - /** min */ - min = "min", - /** max */ - max = "max", -} - -/** - * Aggregation functions for pass/fail criteria. \ - * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **count** \ - * **percentage** \ - * **avg** \ - * **p50** \ - * **p75** \ - * **p90** \ - * **p95** \ - * **p96** \ - * **p97** \ - * **p98** \ - * **p99** \ - * **p99.9** \ - * **p99.99** \ - * **min** \ - * **max** - */ -export type PFAgFunc = string; - -/** Known values of {@link PFAction} that the service accepts. */ -export enum KnownPFAction { - /** continue */ - "continue" = "continue", - /** stop */ - stop = "stop", -} - -/** - * Action to take on failure of pass/fail criteria. \ - * {@link KnownPFAction} can be used interchangeably with PFAction, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **continue** \ - * **stop** - */ -export type PFAction = string; - -/** Known values of {@link PFResult} that the service accepts. */ -export enum KnownPFResult { - /** passed */ - passed = "passed", - /** undetermined */ - undetermined = "undetermined", - /** failed */ - failed = "failed", -} - -/** - * Pass/fail criteria result. \ - * {@link KnownPFResult} can be used interchangeably with PFResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **passed** \ - * **undetermined** \ - * **failed** - */ -export type PFResult = string; - -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteria { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} - -export function autoStopCriteriaSerializer( - item: AutoStopCriteria, -): Record { - return { - autoStopDisabled: item["autoStopDisabled"], - errorRate: item["errorRate"], - errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], - }; -} - -/** Secret */ -export interface Secret { - /** The value of the secret for the respective type */ - value?: string; - /** Type of secret */ - type?: SecretType; -} - -export function secretSerializer(item: Secret): Record { - return { - value: item["value"], - type: item["type"], - }; -} - -/** Known values of {@link SecretType} that the service accepts. */ -export enum KnownSecretType { - /** AKV_SECRET_URI */ - AKV_SECRET_URI = "AKV_SECRET_URI", - /** SECRET_VALUE */ - SECRET_VALUE = "SECRET_VALUE", -} - -/** - * Types of secrets supported. \ - * {@link KnownSecretType} can be used interchangeably with SecretType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_SECRET_URI** \ - * **SECRET_VALUE** - */ -export type SecretType = string; - -/** Certificates metadata */ -export interface CertificateMetadata { - /** The value of the certificate for respective type */ - value?: string; - /** Type of certificate */ - type?: CertificateType; - /** Name of the certificate. */ - name?: string; -} - -export function certificateMetadataSerializer( - item: CertificateMetadata, -): Record { - return { - value: item["value"], - type: item["type"], - name: item["name"], - }; -} - -/** Known values of {@link CertificateType} that the service accepts. */ -export enum KnownCertificateType { - /** AKV_CERT_URI */ - AKV_CERT_URI = "AKV_CERT_URI", -} - -/** - * Types of certificates supported. \ - * {@link KnownCertificateType} can be used interchangeably with CertificateType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_CERT_URI** - */ -export type CertificateType = string; - -/** Configurations for the load test. */ -export interface LoadTestConfiguration { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ - engineInstances?: number; - /** - * If false, Azure Load Testing copies and processes your input files unmodified - * across all test engine instances. If true, Azure Load Testing splits the CSV - * input data evenly across all engine instances. If you provide multiple CSV - * files, each file will be split evenly. - */ - splitAllCSVs?: boolean; - /** - * If true, optionalLoadTestConfig is required and JMX script for the load test is - * not required to upload. - */ - quickStartTest?: boolean; - /** Configuration for quick load test */ - optionalLoadTestConfig?: OptionalLoadTestConfig; - /** Region distribution configuration for the load test. */ - regionalLoadTestConfig?: RegionalConfiguration[]; -} - -export function loadTestConfigurationSerializer( - item: LoadTestConfiguration, -): Record { - return { - engineInstances: item["engineInstances"], - splitAllCSVs: item["splitAllCSVs"], - quickStartTest: item["quickStartTest"], - optionalLoadTestConfig: !item.optionalLoadTestConfig - ? item.optionalLoadTestConfig - : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), - regionalLoadTestConfig: - item["regionalLoadTestConfig"] === undefined - ? item["regionalLoadTestConfig"] - : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), - }; -} - -/** Configuration for quick load test */ -export interface OptionalLoadTestConfig { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ - endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ - virtualUsers?: number; - /** Ramp up time in seconds. */ - rampUpTime?: number; - /** Test run duration in seconds. */ - duration?: number; -} - -export function optionalLoadTestConfigSerializer( - item: OptionalLoadTestConfig, -): Record { - return { - endpointUrl: item["endpointUrl"], - requestsPerSecond: item["requestsPerSecond"], - maxResponseTimeInMs: item["maxResponseTimeInMs"], - virtualUsers: item["virtualUsers"], - rampUpTime: item["rampUpTime"], - duration: item["duration"], - }; -} - -/** Region distribution configuration for the load test. */ -export interface RegionalConfiguration { - /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ - engineInstances: number; - /** - * Azure region name. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - region: string; -} - -export function regionalConfigurationSerializer( - item: RegionalConfiguration, -): Record { - return { - engineInstances: item["engineInstances"], - region: item["region"], - }; -} - -/** The input artifacts for the test. */ -export interface TestInputArtifacts { - /** File info */ - configFileInfo?: TestFileInfo; - /** File info */ - testScriptFileInfo?: TestFileInfo; - /** File info */ - userPropFileInfo?: TestFileInfo; - /** File info */ - inputArtifactsZipFileInfo?: TestFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfo; - /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestFileInfo[]; -} - -/** Test file info. */ -export interface TestFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; -} - -/** Known values of {@link FileType} that the service accepts. */ -export enum KnownFileType { - /** JMX_FILE */ - JMX_FILE = "JMX_FILE", - /** USER_PROPERTIES */ - USER_PROPERTIES = "USER_PROPERTIES", - /** ADDITIONAL_ARTIFACTS */ - ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", - /** ZIPPED_ARTIFACTS */ - ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", - /** URL_TEST_CONFIG */ - URL_TEST_CONFIG = "URL_TEST_CONFIG", - /** TEST_SCRIPT */ - TEST_SCRIPT = "TEST_SCRIPT", -} - -/** - * Types of file supported. \ - * {@link KnownFileType} can be used interchangeably with FileType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **JMX_FILE** \ - * **USER_PROPERTIES** \ - * **ADDITIONAL_ARTIFACTS** \ - * **ZIPPED_ARTIFACTS** \ - * **URL_TEST_CONFIG** \ - * **TEST_SCRIPT** - */ -export type FileType = string; - -/** Known values of {@link FileStatus} that the service accepts. */ -export enum KnownFileStatus { - /** NOT_VALIDATED */ - NOT_VALIDATED = "NOT_VALIDATED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", - /** VALIDATION_INITIATED */ - VALIDATION_INITIATED = "VALIDATION_INITIATED", - /** VALIDATION_NOT_REQUIRED */ - VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", -} - -/** - * File status. \ - * {@link KnownFileStatus} can be used interchangeably with FileStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NOT_VALIDATED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** \ - * **VALIDATION_INITIATED** \ - * **VALIDATION_NOT_REQUIRED** - */ -export type FileStatus = string; - -/** Known values of {@link TestKind} that the service accepts. */ -export enum KnownTestKind { - /** URL */ - URL = "URL", - /** JMX */ - JMX = "JMX", - /** Locust */ - Locust = "Locust", -} - -/** - * Test kind \ - * {@link KnownTestKind} can be used interchangeably with TestKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **URL** \ - * **JMX** \ - * **Locust** - */ -export type TestKind = string; - -/** Test app components */ -export interface TestAppComponents { - /** - * Azure resource collection { resource id (fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) - * : resource object } - */ - components: Record; - /** Test identifier */ - readonly testId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testAppComponentsSerializer( - item: TestAppComponents, -): Record { - return { - components: serializeRecord( - item.components as any, - appComponentSerializer, - ) as any, - }; -} - -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ -export interface AppComponent { - /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ - readonly resourceId: string; - /** Azure resource name, required while creating the app component. */ - resourceName: string; - /** Azure resource type, required while creating the app component. */ - resourceType: string; - /** Azure resource display name */ - displayName?: string; - /** Resource group name of the Azure resource */ - readonly resourceGroup?: string; - /** Subscription Id of the Azure resource */ - readonly subscriptionId?: string; - /** Kind of Azure resource type */ - kind?: string; -} - -export function appComponentSerializer( - item: AppComponent, -): Record { - return { - resourceName: item["resourceName"], - resourceType: item["resourceType"], - displayName: item["displayName"], - kind: item["kind"], - }; -} - -/** Test server metrics configuration */ -export interface TestServerMetricConfig { - /** Test identifier */ - readonly testId?: string; - /** - * Azure resource metrics collection {metric id : metrics object} (Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition - * for metric id). - */ - metrics: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testServerMetricConfigSerializer( - item: TestServerMetricConfig, -): Record { - return { - metrics: serializeRecord( - item.metrics as any, - resourceMetricSerializer, - ) as any, - }; -} - -/** - * Associated metric definition for particular metrics of the azure resource ( - * Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition). - */ -export interface ResourceMetric { - /** Unique name for metric. */ - readonly id?: string; - /** Azure resource id. */ - resourceId: string; - /** Metric name space. */ - metricNamespace: string; - /** Metric description. */ - displayDescription?: string; - /** The invariant value of metric name */ - name: string; - /** Metric aggregation. */ - aggregation: string; - /** Metric unit. */ - unit?: string; - /** Azure resource type. */ - resourceType: string; -} - -export function resourceMetricSerializer( - item: ResourceMetric, -): Record { - return { - resourceId: item["resourceId"], - metricNamespace: item["metricNamespace"], - displayDescription: item["displayDescription"], - name: item["name"], - aggregation: item["aggregation"], - unit: item["unit"], - resourceType: item["resourceType"], - }; -} - -/** Azure Load Testing API versions. */ -export type APIVersions = - | "2022-11-01" - | "2023-04-01-preview" - | "2024-03-01-preview" - | "2024-05-01-preview"; - -/** Load test run model */ -export interface TestRun { - /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testRunId: string; - /** Pass fail criteria for a test. */ - passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; - /** - * Secrets can be stored in an Azure Key Vault or any other secret store. If the - * secret is stored in an Azure Key Vault, the value should be the secret - * identifier and the type should be AKV_SECRET_URI. If the secret is stored - * elsewhere, the secret value should be provided directly and the type should be - * SECRET_VALUE. - */ - secrets?: Record; - /** Certificates metadata */ - certificate?: CertificateMetadata; - /** Environment variables which are defined as a set of pairs. */ - environmentVariables?: Record; - /** Error details if there is any failure in load test run */ - readonly errorDetails?: ErrorDetails[]; - /** - * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. - * The sampler name is the same as the name mentioned in the test script. - * Sampler name "Total" represents the aggregated statistics of all the samplers. - */ - readonly testRunStatistics?: Record; - /** - * Regional statistics. Key is the Azure region name and value is the test run statistics. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - readonly regionalStatistics?: Record; - /** The load test configuration. */ - loadTestConfiguration?: LoadTestConfiguration; - /** Collection of test run artifacts */ - readonly testArtifacts?: TestRunArtifacts; - /** Test result for pass/Fail criteria used during the test run. */ - readonly testResult?: PFTestResult; - /** Number of virtual users, for which test has been run. */ - readonly virtualUsers?: number; - /** Display name of a testRun. */ - displayName?: string; - /** Associated test Id. */ - testId?: string; - /** The test run description. */ - description?: string; - /** The test run status. */ - readonly status?: Status; - /** The test run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; - /** Test run initiated time. */ - readonly executedDateTime?: Date; - /** Portal url. */ - readonly portalUrl?: string; - /** Test run duration in milliseconds. */ - readonly duration?: number; - /** Subnet ID on which the load test instances should run. */ - readonly subnetId?: string; - /** Type of test. */ - readonly kind?: TestKind; - /** Request data collection level for test run */ - requestDataLevel?: RequestDataLevel; - /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ - debugLogsEnabled?: boolean; - /** Inject load test engines without deploying public IP for outbound access */ - readonly publicIPDisabled?: boolean; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunSerializer(item: TestRun): Record { - return { - passFailCriteria: !item.passFailCriteria - ? item.passFailCriteria - : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), - secrets: !item.secrets - ? item.secrets - : (serializeRecord(item.secrets as any, secretSerializer) as any), - certificate: !item.certificate - ? item.certificate - : certificateMetadataSerializer(item.certificate), - environmentVariables: !item.environmentVariables - ? item.environmentVariables - : (serializeRecord(item.environmentVariables as any) as any), - loadTestConfiguration: !item.loadTestConfiguration - ? item.loadTestConfiguration - : loadTestConfigurationSerializer(item.loadTestConfiguration), - displayName: item["displayName"], - testId: item["testId"], - description: item["description"], - requestDataLevel: item["requestDataLevel"], - debugLogsEnabled: item["debugLogsEnabled"], - }; -} - -/** Error details if there is any failure in load test run */ -export interface ErrorDetails { - /** Error details in case test run was not successfully run. */ - readonly message?: string; -} - -/** Test run statistics. */ -export interface TestRunStatistics { - /** Transaction name. */ - readonly transaction?: string; - /** Sampler count. */ - readonly sampleCount?: number; - /** Error count. */ - readonly errorCount?: number; - /** Error percentage. */ - readonly errorPct?: number; - /** Mean response time. */ - readonly meanResTime?: number; - /** Median response time. */ - readonly medianResTime?: number; - /** Max response time. */ - readonly maxResTime?: number; - /** Minimum response time. */ - readonly minResTime?: number; - /** 90 percentile response time. */ - readonly pct1ResTime?: number; - /** 95 percentile response time. */ - readonly pct2ResTime?: number; - /** 99 percentile response time. */ - readonly pct3ResTime?: number; - /** 75 percentile response time. */ - readonly pct75ResTime?: number; - /** 96 percentile response time. */ - readonly pct96ResTime?: number; - /** 97 percentile response time. */ - readonly pct97ResTime?: number; - /** 98 percentile response time. */ - readonly pct98ResTime?: number; - /** 99.9 percentile response time. */ - readonly pct999ResTime?: number; - /** 99.99 percentile response time. */ - readonly pct9999ResTime?: number; - /** Throughput. */ - readonly throughput?: number; - /** Received network bytes. */ - readonly receivedKBytesPerSec?: number; - /** Send network bytes. */ - readonly sentKBytesPerSec?: number; -} - -/** Collection of test run artifacts */ -export interface TestRunArtifacts { - /** The input artifacts for the test run. */ - readonly inputArtifacts?: TestRunInputArtifacts; - /** The output artifacts for the test run. */ - outputArtifacts?: TestRunOutputArtifacts; -} - -/** The input artifacts for the test run. */ -export interface TestRunInputArtifacts { - /** File info */ - configFileInfo?: TestRunFileInfo; - /** File info */ - testScriptFileInfo?: TestRunFileInfo; - /** File info */ - userPropFileInfo?: TestRunFileInfo; - /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfo; - /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestRunFileInfo[]; -} - -/** Test run file info. */ -export interface TestRunFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; -} - -/** The output artifacts for the test run. */ -export interface TestRunOutputArtifacts { - /** File info */ - resultFileInfo?: TestRunFileInfo; - /** File info */ - logsFileInfo?: TestRunFileInfo; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfo; - /** The report file for the test run. */ - reportFileInfo?: TestRunFileInfo; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfo { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: Date; -} - -/** Known values of {@link PFTestResult} that the service accepts. */ -export enum KnownPFTestResult { - /** PASSED */ - PASSED = "PASSED", - /** NOT_APPLICABLE */ - NOT_APPLICABLE = "NOT_APPLICABLE", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test result based on pass/fail criteria. \ - * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PASSED** \ - * **NOT_APPLICABLE** \ - * **FAILED** - */ -export type PFTestResult = string; - -/** Known values of {@link Status} that the service accepts. */ -export enum KnownStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** PROVISIONING */ - PROVISIONING = "PROVISIONING", - /** PROVISIONED */ - PROVISIONED = "PROVISIONED", - /** CONFIGURING */ - CONFIGURING = "CONFIGURING", - /** CONFIGURED */ - CONFIGURED = "CONFIGURED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** EXECUTED */ - EXECUTED = "EXECUTED", - /** DEPROVISIONING */ - DEPROVISIONING = "DEPROVISIONING", - /** DEPROVISIONED */ - DEPROVISIONED = "DEPROVISIONED", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", -} - -/** - * Test run status. \ - * {@link KnownStatus} can be used interchangeably with Status, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **PROVISIONING** \ - * **PROVISIONED** \ - * **CONFIGURING** \ - * **CONFIGURED** \ - * **EXECUTING** \ - * **EXECUTED** \ - * **DEPROVISIONING** \ - * **DEPROVISIONED** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** - */ -export type Status = string; - -/** Known values of {@link RequestDataLevel} that the service accepts. */ -export enum KnownRequestDataLevel { - /** NONE */ - NONE = "NONE", - /** ERRORS */ - ERRORS = "ERRORS", -} - -/** - * Request data collection level for test run \ - * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NONE** \ - * **ERRORS** - */ -export type RequestDataLevel = string; - -/** Test run app component */ -export interface TestRunAppComponents { - /** - * Azure resource collection { resource id (fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) - * : resource object } - */ - components: Record; - /** Test run identifier */ - readonly testRunId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunAppComponentsSerializer( - item: TestRunAppComponents, -): Record { - return { - components: serializeRecord( - item.components as any, - appComponentSerializer, - ) as any, - }; -} - -/** Test run server metrics configuration */ -export interface TestRunServerMetricConfig { - /** Test run identifier */ - readonly testRunId?: string; - /** - * Azure resource metrics collection {metric id : metrics object} (Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition - * for metric id). - */ - metrics?: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunServerMetricConfigSerializer( - item: TestRunServerMetricConfig, -): Record { - return { - metrics: !item.metrics - ? item.metrics - : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), - }; -} - -/** Known values of {@link TimeGrain} that the service accepts. */ -export enum KnownTimeGrain { - /** PT5S */ - PT5S = "PT5S", - /** PT10S */ - PT10S = "PT10S", - /** PT1M */ - PT1M = "PT1M", - /** PT5M */ - PT5M = "PT5M", - /** PT1H */ - PT1H = "PT1H", -} - -/** - * Time Grain \ - * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PT5S** \ - * **PT10S** \ - * **PT1M** \ - * **PT5M** \ - * **PT1H** - */ -export type TimeGrain = string; - -/** Metrics dimension values. */ -export interface DimensionValueList { - /** The dimension name */ - readonly name?: string; - /** The dimension value */ - value?: string[]; - /** Link for the next set of values in case of paginated results, if applicable. */ - nextLink?: string; -} - -/** Represents collection of metric definitions. */ -export interface MetricDefinitionCollection { - /** the values for the metric definitions. */ - value: MetricDefinition[]; -} - -/** Metric definition */ -export interface MetricDefinition { - /** List of dimensions */ - dimensions?: NameAndDesc[]; - /** The metric description */ - description?: string; - /** The metric name */ - name?: string; - /** The namespace the metric belongs to. */ - namespace?: string; - /** The primary aggregation type value defining how to use the values for display. */ - primaryAggregationType?: AggregationType; - /** The collection of what all aggregation types are supported. */ - supportedAggregationTypes?: string[]; - /** The unit of the metric. */ - unit?: MetricUnit; - /** - * Metric availability specifies the time grain (aggregation interval or - * frequency). - */ - metricAvailabilities?: MetricAvailability[]; -} - -/** The name and description */ -export interface NameAndDesc { - /** The description */ - description?: string; - /** The name */ - name?: string; -} - -/** Known values of {@link AggregationType} that the service accepts. */ -export enum KnownAggregationType { - /** Average */ - Average = "Average", - /** Count */ - Count = "Count", - /** None */ - None = "None", - /** Total */ - Total = "Total", - /** Percentile75 */ - Percentile75 = "Percentile75", - /** Percentile90 */ - Percentile90 = "Percentile90", - /** Percentile95 */ - Percentile95 = "Percentile95", - /** Percentile96 */ - Percentile96 = "Percentile96", - /** Percentile97 */ - Percentile97 = "Percentile97", - /** Percentile98 */ - Percentile98 = "Percentile98", - /** Percentile99 */ - Percentile99 = "Percentile99", - /** Percentile999 */ - Percentile999 = "Percentile999", - /** Percentile9999 */ - Percentile9999 = "Percentile9999", -} - -/** - * Aggregation type. \ - * {@link KnownAggregationType} can be used interchangeably with AggregationType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **Average** \ - * **Count** \ - * **None** \ - * **Total** \ - * **Percentile75** \ - * **Percentile90** \ - * **Percentile95** \ - * **Percentile96** \ - * **Percentile97** \ - * **Percentile98** \ - * **Percentile99** \ - * **Percentile999** \ - * **Percentile9999** - */ -export type AggregationType = string; - -/** Known values of {@link MetricUnit} that the service accepts. */ -export enum KnownMetricUnit { - /** NotSpecified */ - NotSpecified = "NotSpecified", - /** Percent */ - Percent = "Percent", - /** Count */ - Count = "Count", - /** Seconds */ - Seconds = "Seconds", - /** Milliseconds */ - Milliseconds = "Milliseconds", - /** Bytes */ - Bytes = "Bytes", - /** BytesPerSecond */ - BytesPerSecond = "BytesPerSecond", - /** CountPerSecond */ - CountPerSecond = "CountPerSecond", -} - -/** - * Metric unit. \ - * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NotSpecified** \ - * **Percent** \ - * **Count** \ - * **Seconds** \ - * **Milliseconds** \ - * **Bytes** \ - * **BytesPerSecond** \ - * **CountPerSecond** - */ -export type MetricUnit = string; - -/** Metric availability specifies the time grain (aggregation interval or frequency) */ -export interface MetricAvailability { - /** - * The time grain specifies the aggregation interval for the metric. Expressed as - * a duration 'PT1M', 'PT1H', etc. - */ - timeGrain?: TimeGrain; -} - -/** Represents collection of metric namespaces. */ -export interface MetricNamespaceCollection { - /** The values for the metric namespaces. */ - value: MetricNamespace[]; -} - -/** Metric namespace class specifies the metadata for a metric namespace. */ -export interface MetricNamespace { - /** The namespace description. */ - description?: string; - /** The metric namespace name. */ - name?: string; -} - -/** Filters to fetch the set of metric. */ -export interface MetricRequestPayload { - /** - * Get metrics for specific dimension values. Example: Metric contains dimension - * like SamplerName, Error. To retrieve all the time series data where SamplerName - * is equals to HTTPRequest1 or HTTPRequest2, the DimensionFilter value will be - * {"SamplerName", ["HTTPRequest1", "HTTPRequest2"} - */ - filters?: DimensionFilter[]; -} - -export function metricRequestPayloadSerializer( - item: MetricRequestPayload, -): Record { - return { - filters: - item["filters"] === undefined - ? item["filters"] - : item["filters"].map(dimensionFilterSerializer), - }; -} - -/** Dimension name and values to filter */ -export interface DimensionFilter { - /** The dimension name */ - name?: string; - /** The dimension values. Maximum values can be 20. */ - values?: string[]; -} - -export function dimensionFilterSerializer( - item: DimensionFilter, -): Record { - return { - name: item["name"], - values: item["values"], - }; -} - -/** The response to a metrics query. */ -export interface _Metrics { - /** The TimeSeriesElement items on this page */ - value: TimeSeriesElement[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** The time series returned when a data query is performed. */ -export interface TimeSeriesElement { - /** An array of data points representing the metric values. */ - data?: MetricValue[]; - /** The dimension values */ - dimensionValues?: DimensionValue[]; -} - -/** Represents a metric value. */ -export interface MetricValue { - /** The timestamp for the metric value in RFC 3339 format. */ - timestamp?: Date; - /** The metric value. */ - value?: number; -} - -/** Represents a metric dimension value. */ -export interface DimensionValue { - /** The name of the dimension. */ - name?: string; - /** The value of the dimension. */ - value?: string; -} - -/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ -export interface TestProfile { - /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileId: string; - /** Display name of the test profile. */ - displayName?: string; - /** Description for the test profile. */ - description?: string; - /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ - testId?: string; - /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ - targetResourceId?: string; - /** Configurations of the target resource on which testing would be done. */ - targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileSerializer( - item: TestProfile, -): Record { - return { - displayName: item["displayName"], - description: item["description"], - testId: item["testId"], - targetResourceId: item["targetResourceId"], - targetResourceConfigurations: !item.targetResourceConfigurations - ? item.targetResourceConfigurations - : targetResourceConfigurationsUnionSerializer( - item.targetResourceConfigurations, - ), - }; -} - -/** Configurations of a target resource. This varies with the kind of resource. */ -export interface TargetResourceConfigurations { - /** the discriminator possible values: FunctionsFlexConsumption */ - kind: ResourceKind; -} - -export function targetResourceConfigurationsUnionSerializer( - item: TargetResourceConfigurationsUnion, -) { - switch (item.kind) { - case "FunctionsFlexConsumption": - return functionFlexConsumptionTargetResourceConfigurationsSerializer( - item as FunctionFlexConsumptionTargetResourceConfigurations, - ); - - default: - return targetResourceConfigurationsSerializer(item); - } -} - -export function targetResourceConfigurationsSerializer( - item: TargetResourceConfigurationsUnion, -): Record { - return { - kind: item["kind"], - }; -} - -/** Configurations for a Function App using Flex Consumption Plan. */ -export interface FunctionFlexConsumptionTargetResourceConfigurations - extends TargetResourceConfigurations { - /** - * The kind value to use when providing configuration. - * This should typically be not changed from its value. - */ - kind: "FunctionsFlexConsumption"; - /** A map of configurations for a Function app using Flex Consumption Plan. */ - configurations?: Record; -} - -export function functionFlexConsumptionTargetResourceConfigurationsSerializer( - item: FunctionFlexConsumptionTargetResourceConfigurations, -): Record { - return { - kind: item["kind"], - configurations: !item.configurations - ? item.configurations - : (serializeRecord( - item.configurations as any, - functionFlexConsumptionResourceConfigurationSerializer, - ) as any), - }; -} - -/** Resource configuration instance for a Flex Consumption based Azure Function App. */ -export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 2048, 4096. */ - instanceMemoryMB: number; - /** HTTP Concurrency for the function app. */ - httpConcurrency: number; -} - -export function functionFlexConsumptionResourceConfigurationSerializer( - item: FunctionFlexConsumptionResourceConfiguration, -): Record { - return { - instanceMemoryMB: item["instanceMemoryMB"], - httpConcurrency: item["httpConcurrency"], - }; -} - -/** Known values of {@link ResourceKind} that the service accepts. */ -export enum KnownResourceKind { - /** FunctionsFlexConsumption */ - FunctionsFlexConsumption = "FunctionsFlexConsumption", -} - -/** - * Kind of the resource on which test profile is created. \ - * {@link KnownResourceKind} can be used interchangeably with ResourceKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **FunctionsFlexConsumption** - */ -export type ResourceKind = string; - -/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ -export interface TestProfileRun { - /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileRunId: string; - /** Display name for the test profile run. */ - displayName?: string; - /** The test profile run description */ - description?: string; - /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ - testProfileId?: string; - /** Target resource ID on which the test profile run is created */ - readonly targetResourceId?: string; - /** Configurations of the target resource on which the test profile ran. */ - readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The test profile run status. */ - readonly status?: TestProfileRunStatus; - /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ - readonly errorDetails?: ErrorDetails[]; - /** The test profile run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test profile run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; - /** Test profile run duration in seconds. */ - readonly durationInSeconds?: number; - /** - * Details of the test runs ran as part of the test profile run. - * Key is the testRunId of the corresponding testRun. - */ - readonly testRunDetails?: Record; - /** Recommendations provided based on a successful test profile run. */ - readonly recommendations?: TestProfileRunRecommendation[]; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileRunSerializer( - item: TestProfileRun, -): Record { - return { - displayName: item["displayName"], - description: item["description"], - testProfileId: item["testProfileId"], - }; -} - -/** Known values of {@link TestProfileRunStatus} that the service accepts. */ -export enum KnownTestProfileRunStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test profile run status. \ - * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **EXECUTING** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** - */ -export type TestProfileRunStatus = string; - -/** Details of a particular test run for a test profile run. */ -export interface TestRunDetail { - /** Status of the test run. */ - status: Status; - /** ID of the configuration on which the test ran. */ - configurationId: string; - /** Key value pair of extra properties associated with the test run. */ - properties: Record; -} - -/** A recommendation object that provides a list of configuration that optimizes its category. */ -export interface TestProfileRunRecommendation { - /** Category of the recommendation. */ - category: RecommendationCategory; - /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ - configurations?: string[]; -} - -/** Known values of {@link RecommendationCategory} that the service accepts. */ -export enum KnownRecommendationCategory { - /** ThroughputOptimized */ - ThroughputOptimized = "ThroughputOptimized", - /** CostOptimized */ - CostOptimized = "CostOptimized", -} - -/** - * Category of Recommendation. \ - * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ThroughputOptimized** \ - * **CostOptimized** - */ -export type RecommendationCategory = string; - -/** Paged collection of TestFileInfo items */ -export interface _PagedTestFileInfo { - /** The TestFileInfo items on this page */ - value: TestFileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of Test items */ -export interface _PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestRun items */ -export interface _PagedTestRun { - /** The TestRun items on this page */ - value: TestRun[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestProfile items */ -export interface _PagedTestProfile { - /** The TestProfile items on this page */ - value: TestProfile[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestProfileRun items */ -export interface _PagedTestProfileRun { - /** The TestProfileRun items on this page */ - value: TestProfileRun[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Alias for TargetResourceConfigurationsUnion */ -export type TargetResourceConfigurationsUnion = - | FunctionFlexConsumptionTargetResourceConfigurations - | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/index.ts index ab87456478..5180ae7e37 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/index.ts @@ -3,7 +3,7 @@ export { createLoadTestRun, - LoadTestServiceContext, + LoadTestRunContext, LoadTestRunClientOptionalParams, } from "./loadTestRunContext.js"; export { @@ -22,3 +22,19 @@ export { listTestRuns, stopTestRun, } from "./operations.js"; +export { + CreateOrUpdateTestRunOptionalParams, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + DeleteTestRunOptionalParams, + GetAppComponentsOptionalParams, + GetServerMetricsConfigOptionalParams, + GetTestRunOptionalParams, + GetTestRunFileOptionalParams, + ListMetricDimensionValuesOptionalParams, + ListMetricDefinitionsOptionalParams, + ListMetricNamespacesOptionalParams, + ListMetricsOptionalParams, + ListTestRunsOptionalParams, + StopTestRunOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/loadTestRunContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/loadTestRunContext.ts index 9532e65c8b..fd13aa2082 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/loadTestRunContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/loadTestRunContext.ts @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { TokenCredential } from "@azure/core-auth"; -export interface LoadTestServiceContext extends Client {} +export interface LoadTestRunContext extends Client {} /** Optional parameters for the client. */ export interface LoadTestRunClientOptionalParams extends ClientOptions { @@ -17,7 +17,7 @@ export function createLoadTestRun( endpointParam: string, credential: TokenCredential, options: LoadTestRunClientOptionalParams = {}, -): LoadTestServiceContext { +): LoadTestRunContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/operations.ts index 161bbf0e2f..d205a18237 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/operations.ts @@ -2,54 +2,58 @@ // Licensed under the MIT License. import { - passFailCriteriaSerializer, - autoStopCriteriaSerializer, - secretSerializer, - certificateMetadataSerializer, - loadTestConfigurationSerializer, - appComponentSerializer, - resourceMetricSerializer, - dimensionFilterSerializer, + LoadTestRunContext as Client, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + CreateOrUpdateTestRunOptionalParams, + DeleteTestRunOptionalParams, + GetAppComponentsOptionalParams, + GetServerMetricsConfigOptionalParams, + GetTestRunFileOptionalParams, + GetTestRunOptionalParams, + ListMetricDefinitionsOptionalParams, + ListMetricDimensionValuesOptionalParams, + ListMetricNamespacesOptionalParams, + ListMetricsOptionalParams, + ListTestRunsOptionalParams, + StopTestRunOptionalParams, +} from "./index.js"; +import { TestRun, + testRunSerializer, + testRunDeserializer, TestRunFileInfo, + testRunFileInfoDeserializer, TestRunAppComponents, + testRunAppComponentsSerializer, + testRunAppComponentsDeserializer, TestRunServerMetricConfig, + testRunServerMetricConfigSerializer, + testRunServerMetricConfigDeserializer, DimensionValueList, + dimensionValueListDeserializer, MetricDefinitionCollection, + metricDefinitionCollectionDeserializer, MetricNamespaceCollection, + metricNamespaceCollectionDeserializer, MetricRequestPayload, - TimeSeriesElement, + metricRequestPayloadSerializer, _Metrics, + _metricsDeserializer, + TimeSeriesElement, _PagedTestRun, -} from "../models/models.js"; -import { LoadTestServiceContext as Client } from "./index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; -import { serializeRecord } from "../../helpers/serializerHelpers.js"; + _pagedTestRunDeserializer, +} from "../../models/models.js"; import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../../static-helpers/pagingHelpers.js"; import { - CreateOrUpdateTestRunOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - DeleteTestRunOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestRunOptionalParams, - GetTestRunFileOptionalParams, - ListMetricDimensionValuesOptionalParams, - ListMetricDefinitionsOptionalParams, - ListMetricNamespacesOptionalParams, - ListMetricsOptionalParams, - ListTestRunsOptionalParams, - StopTestRunOptionalParams, -} from "../models/options.js"; + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; export function _createOrUpdateTestRunSend( context: Client, @@ -64,31 +68,7 @@ export function _createOrUpdateTestRunSend( contentType: (options.contentType as any) ?? "application/merge-patch+json", queryParameters: { oldTestRunId: options?.oldTestRunId }, - body: { - passFailCriteria: !body.passFailCriteria - ? body.passFailCriteria - : passFailCriteriaSerializer(body.passFailCriteria), - autoStopCriteria: !body.autoStopCriteria - ? body.autoStopCriteria - : autoStopCriteriaSerializer(body.autoStopCriteria), - secrets: !body.secrets - ? body.secrets - : (serializeRecord(body.secrets as any, secretSerializer) as any), - certificate: !body.certificate - ? body.certificate - : certificateMetadataSerializer(body.certificate), - environmentVariables: !body.environmentVariables - ? body.environmentVariables - : (serializeRecord(body.environmentVariables as any) as any), - loadTestConfiguration: !body.loadTestConfiguration - ? body.loadTestConfiguration - : loadTestConfigurationSerializer(body.loadTestConfiguration), - displayName: body["displayName"], - testId: body["testId"], - description: body["description"], - requestDataLevel: body["requestDataLevel"], - debugLogsEnabled: body["debugLogsEnabled"], - }, + body: testRunSerializer(body), }); } @@ -100,392 +80,7 @@ export async function _createOrUpdateTestRunDeserialize( throw createRestError(result); } - return { - testRunId: result.body["testRunId"], - passFailCriteria: !result.body.passFailCriteria - ? undefined - : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, - secrets: result.body["secrets"], - certificate: !result.body.certificate - ? undefined - : { - value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"], - name: result.body.certificate?.["name"], - }, - environmentVariables: result.body["environmentVariables"], - errorDetails: - result.body["errorDetails"] === undefined - ? result.body["errorDetails"] - : result.body["errorDetails"].map((p: any) => { - return { message: p["message"] }; - }), - testRunStatistics: result.body["testRunStatistics"], - regionalStatistics: result.body["regionalStatistics"], - loadTestConfiguration: !result.body.loadTestConfiguration - ? undefined - : { - engineInstances: - result.body.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: result.body.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: result.body.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !result.body.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], - virtualUsers: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, - regionalLoadTestConfig: - result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] - : result.body.loadTestConfiguration?.[ - "regionalLoadTestConfig" - ].map((p: any) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }), - }, - testArtifacts: !result.body.testArtifacts - ? undefined - : { - inputArtifacts: !result.body.testArtifacts?.inputArtifacts - ? undefined - : { - configFileInfo: !result.body.testArtifacts?.inputArtifacts - ?.configFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["validationFailureDetails"], - }, - testScriptFileInfo: !result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["validationFailureDetails"], - }, - userPropFileInfo: !result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["validationFailureDetails"], - }, - inputArtifactsZipFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.inputArtifactsZipFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "validationFailureDetails" - ], - }, - urlTestConfigFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationFailureDetails"], - }, - additionalFileInfo: - result.body.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ] === undefined - ? result.body.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ] - : result.body.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ].map((p: any) => { - return { - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"], - validationFailureDetails: - p["validationFailureDetails"], - }; - }), - }, - outputArtifacts: !result.body.testArtifacts?.outputArtifacts - ? undefined - : { - resultFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["validationFailureDetails"], - }, - logsFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationFailureDetails"], - }, - artifactsContainerInfo: !result.body.testArtifacts - ?.outputArtifacts?.artifactsContainerInfo - ? undefined - : { - url: result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"], - ) - : undefined, - }, - reportFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationFailureDetails"], - }, - }, - }, - testResult: result.body["testResult"], - virtualUsers: result.body["virtualUsers"], - displayName: result.body["displayName"], - testId: result.body["testId"], - description: result.body["description"], - status: result.body["status"], - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - executedDateTime: - result.body["executedDateTime"] !== undefined - ? new Date(result.body["executedDateTime"]) - : undefined, - portalUrl: result.body["portalUrl"], - duration: result.body["duration"], - subnetId: result.body["subnetId"], - kind: result.body["kind"], - requestDataLevel: result.body["requestDataLevel"], - debugLogsEnabled: result.body["debugLogsEnabled"], - publicIPDisabled: result.body["publicIPDisabled"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testRunDeserializer(result.body); } /** Create and start a new test run with the given test run Id. */ @@ -516,12 +111,7 @@ export function _createOrUpdateAppComponentsSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { - components: serializeRecord( - body.components as any, - appComponentSerializer, - ) as any, - }, + body: testRunAppComponentsSerializer(body), }); } @@ -533,20 +123,7 @@ export async function _createOrUpdateAppComponentsDeserialize( throw createRestError(result); } - return { - components: result.body["components"], - testRunId: result.body["testRunId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testRunAppComponentsDeserializer(result.body); } /** Add an app component to a test run by providing the resource Id, name and type. */ @@ -579,14 +156,7 @@ export function _createOrUpdateServerMetricsConfigSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { - metrics: !body.metrics - ? body.metrics - : (serializeRecord( - body.metrics as any, - resourceMetricSerializer, - ) as any), - }, + body: testRunServerMetricConfigSerializer(body), }); } @@ -598,20 +168,7 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( throw createRestError(result); } - return { - testRunId: result.body["testRunId"], - metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testRunServerMetricConfigDeserializer(result.body); } /** Configure server metrics for a test run */ @@ -681,20 +238,7 @@ export async function _getAppComponentsDeserialize( throw createRestError(result); } - return { - components: result.body["components"], - testRunId: result.body["testRunId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testRunAppComponentsDeserializer(result.body); } /** @@ -728,20 +272,7 @@ export async function _getServerMetricsConfigDeserialize( throw createRestError(result); } - return { - testRunId: result.body["testRunId"], - metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testRunServerMetricConfigDeserializer(result.body); } /** Get associated server metrics configuration for the given test run. */ @@ -772,392 +303,7 @@ export async function _getTestRunDeserialize( throw createRestError(result); } - return { - testRunId: result.body["testRunId"], - passFailCriteria: !result.body.passFailCriteria - ? undefined - : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, - secrets: result.body["secrets"], - certificate: !result.body.certificate - ? undefined - : { - value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"], - name: result.body.certificate?.["name"], - }, - environmentVariables: result.body["environmentVariables"], - errorDetails: - result.body["errorDetails"] === undefined - ? result.body["errorDetails"] - : result.body["errorDetails"].map((p: any) => { - return { message: p["message"] }; - }), - testRunStatistics: result.body["testRunStatistics"], - regionalStatistics: result.body["regionalStatistics"], - loadTestConfiguration: !result.body.loadTestConfiguration - ? undefined - : { - engineInstances: - result.body.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: result.body.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: result.body.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !result.body.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], - virtualUsers: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, - regionalLoadTestConfig: - result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] - : result.body.loadTestConfiguration?.[ - "regionalLoadTestConfig" - ].map((p: any) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }), - }, - testArtifacts: !result.body.testArtifacts - ? undefined - : { - inputArtifacts: !result.body.testArtifacts?.inputArtifacts - ? undefined - : { - configFileInfo: !result.body.testArtifacts?.inputArtifacts - ?.configFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["validationFailureDetails"], - }, - testScriptFileInfo: !result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["validationFailureDetails"], - }, - userPropFileInfo: !result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["validationFailureDetails"], - }, - inputArtifactsZipFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.inputArtifactsZipFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "validationFailureDetails" - ], - }, - urlTestConfigFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationFailureDetails"], - }, - additionalFileInfo: - result.body.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ] === undefined - ? result.body.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ] - : result.body.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ].map((p: any) => { - return { - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"], - validationFailureDetails: - p["validationFailureDetails"], - }; - }), - }, - outputArtifacts: !result.body.testArtifacts?.outputArtifacts - ? undefined - : { - resultFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["validationFailureDetails"], - }, - logsFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationFailureDetails"], - }, - artifactsContainerInfo: !result.body.testArtifacts - ?.outputArtifacts?.artifactsContainerInfo - ? undefined - : { - url: result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"], - ) - : undefined, - }, - reportFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationFailureDetails"], - }, - }, - }, - testResult: result.body["testResult"], - virtualUsers: result.body["virtualUsers"], - displayName: result.body["displayName"], - testId: result.body["testId"], - description: result.body["description"], - status: result.body["status"], - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - executedDateTime: - result.body["executedDateTime"] !== undefined - ? new Date(result.body["executedDateTime"]) - : undefined, - portalUrl: result.body["portalUrl"], - duration: result.body["duration"], - subnetId: result.body["subnetId"], - kind: result.body["kind"], - requestDataLevel: result.body["requestDataLevel"], - debugLogsEnabled: result.body["debugLogsEnabled"], - publicIPDisabled: result.body["publicIPDisabled"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testRunDeserializer(result.body); } /** Get test run details by test run Id. */ @@ -1189,17 +335,7 @@ export async function _getTestRunFileDeserialize( throw createRestError(result); } - return { - fileName: result.body["fileName"], - url: result.body["url"], - fileType: result.body["fileType"], - expireDateTime: - result.body["expireDateTime"] !== undefined - ? new Date(result.body["expireDateTime"]) - : undefined, - validationStatus: result.body["validationStatus"], - validationFailureDetails: result.body["validationFailureDetails"], - }; + return testRunFileInfoDeserializer(result.body); } /** Get test run file by file name. */ @@ -1252,11 +388,7 @@ export async function _listMetricDimensionValuesDeserialize( throw createRestError(result); } - return { - name: result.body["name"], - value: result.body["value"], - nextLink: result.body["nextLink"], - }; + return dimensionValueListDeserializer(result.body); } /** List the dimension values for the given metric dimension name. */ @@ -1303,30 +435,7 @@ export async function _listMetricDefinitionsDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - dimensions: - p["dimensions"] === undefined - ? p["dimensions"] - : p["dimensions"].map((p: any) => { - return { description: p["description"], name: p["name"] }; - }), - description: p["description"], - name: p["name"], - namespace: p["namespace"], - primaryAggregationType: p["primaryAggregationType"], - supportedAggregationTypes: p["supportedAggregationTypes"], - unit: p["unit"], - metricAvailabilities: - p["metricAvailabilities"] === undefined - ? p["metricAvailabilities"] - : p["metricAvailabilities"].map((p: any) => { - return { timeGrain: p["timeGrain"] }; - }), - }; - }), - }; + return metricDefinitionCollectionDeserializer(result.body); } /** List the metric definitions for a load test run. */ @@ -1363,11 +472,7 @@ export async function _listMetricNamespacesDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { description: p["description"], name: p["name"] }; - }), - }; + return metricNamespaceCollectionDeserializer(result.body); } /** List the metric namespaces for a load test run. */ @@ -1400,15 +505,7 @@ export function _listMetricsSend( metricNamespace: metricNamespace, timespan: timespan, }, - body: - body === undefined - ? body - : { - filters: - body["filters"] === undefined - ? body["filters"] - : body["filters"].map(dimensionFilterSerializer), - }, + body: !body ? body : metricRequestPayloadSerializer(body), }); } @@ -1420,31 +517,7 @@ export async function _listMetricsDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - data: - p["data"] === undefined - ? p["data"] - : p["data"].map((p: any) => { - return { - timestamp: - p["timestamp"] !== undefined - ? new Date(p["timestamp"]) - : undefined, - value: p["value"], - }; - }), - dimensionValues: - p["dimensionValues"] === undefined - ? p["dimensionValues"] - : p["dimensionValues"].map((p: any) => { - return { name: p["name"], value: p["value"] }; - }), - }; - }), - nextLink: result.body["nextLink"], - }; + return _metricsDeserializer(result.body); } /** List the metric values for a load test run. */ @@ -1503,432 +576,7 @@ export async function _listTestRunsDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - testRunId: p["testRunId"], - passFailCriteria: !p.passFailCriteria - ? undefined - : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !p.autoStopCriteria - ? undefined - : { - autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], - errorRate: p.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, - secrets: p["secrets"], - certificate: !p.certificate - ? undefined - : { - value: p.certificate?.["value"], - type: p.certificate?.["type"], - name: p.certificate?.["name"], - }, - environmentVariables: p["environmentVariables"], - errorDetails: - p["errorDetails"] === undefined - ? p["errorDetails"] - : p["errorDetails"].map((p: any) => { - return { message: p["message"] }; - }), - testRunStatistics: p["testRunStatistics"], - regionalStatistics: p["regionalStatistics"], - loadTestConfiguration: !p.loadTestConfiguration - ? undefined - : { - engineInstances: p.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: p.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: p.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !p.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], - requestsPerSecond: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], - virtualUsers: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, - regionalLoadTestConfig: - p.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? p.loadTestConfiguration?.["regionalLoadTestConfig"] - : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( - (p: any) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }, - ), - }, - testArtifacts: !p.testArtifacts - ? undefined - : { - inputArtifacts: !p.testArtifacts?.inputArtifacts - ? undefined - : { - configFileInfo: !p.testArtifacts?.inputArtifacts - ?.configFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], - fileType: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "fileType" - ], - expireDateTime: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "validationFailureDetails" - ], - }, - testScriptFileInfo: !p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileName"], - url: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], - fileType: - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"], - expireDateTime: - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["validationStatus"], - validationFailureDetails: - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.[ - "validationFailureDetails" - ], - }, - userPropFileInfo: !p.testArtifacts?.inputArtifacts - ?.userPropFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], - fileType: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "fileType" - ], - expireDateTime: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "validationFailureDetails" - ], - }, - inputArtifactsZipFileInfo: !p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileName"], - url: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], - fileType: - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"], - expireDateTime: - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["validationStatus"], - validationFailureDetails: - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "validationFailureDetails" - ], - }, - urlTestConfigFileInfo: !p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, - additionalFileInfo: - p.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ] === undefined - ? p.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ] - : p.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ].map((p: any) => { - return { - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"], - validationFailureDetails: - p["validationFailureDetails"], - }; - }), - }, - outputArtifacts: !p.testArtifacts?.outputArtifacts - ? undefined - : { - resultFileInfo: !p.testArtifacts?.outputArtifacts - ?.resultFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], - fileType: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "fileType" - ], - expireDateTime: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "validationFailureDetails" - ], - }, - logsFileInfo: !p.testArtifacts?.outputArtifacts - ?.logsFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "url" - ], - fileType: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "fileType" - ], - expireDateTime: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "validationFailureDetails" - ], - }, - artifactsContainerInfo: !p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo - ? undefined - : { - url: p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.[ - "expireDateTime" - ], - ) - : undefined, - }, - reportFileInfo: !p.testArtifacts?.outputArtifacts - ?.reportFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["url"], - fileType: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "fileType" - ], - expireDateTime: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "validationFailureDetails" - ], - }, - }, - }, - testResult: p["testResult"], - virtualUsers: p["virtualUsers"], - displayName: p["displayName"], - testId: p["testId"], - description: p["description"], - status: p["status"], - startDateTime: - p["startDateTime"] !== undefined - ? new Date(p["startDateTime"]) - : undefined, - endDateTime: - p["endDateTime"] !== undefined - ? new Date(p["endDateTime"]) - : undefined, - executedDateTime: - p["executedDateTime"] !== undefined - ? new Date(p["executedDateTime"]) - : undefined, - portalUrl: p["portalUrl"], - duration: p["duration"], - subnetId: p["subnetId"], - kind: p["kind"], - requestDataLevel: p["requestDataLevel"], - debugLogsEnabled: p["debugLogsEnabled"], - publicIPDisabled: p["publicIPDisabled"], - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, - createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: p["lastModifiedBy"], - }; - }), - nextLink: result.body["nextLink"], - }; + return _pagedTestRunDeserializer(result.body); } /** Get all test runs for the given filters. */ @@ -1963,392 +611,7 @@ export async function _stopTestRunDeserialize( throw createRestError(result); } - return { - testRunId: result.body["testRunId"], - passFailCriteria: !result.body.passFailCriteria - ? undefined - : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, - secrets: result.body["secrets"], - certificate: !result.body.certificate - ? undefined - : { - value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"], - name: result.body.certificate?.["name"], - }, - environmentVariables: result.body["environmentVariables"], - errorDetails: - result.body["errorDetails"] === undefined - ? result.body["errorDetails"] - : result.body["errorDetails"].map((p: any) => { - return { message: p["message"] }; - }), - testRunStatistics: result.body["testRunStatistics"], - regionalStatistics: result.body["regionalStatistics"], - loadTestConfiguration: !result.body.loadTestConfiguration - ? undefined - : { - engineInstances: - result.body.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: result.body.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: result.body.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !result.body.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], - virtualUsers: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, - regionalLoadTestConfig: - result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] - : result.body.loadTestConfiguration?.[ - "regionalLoadTestConfig" - ].map((p: any) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }), - }, - testArtifacts: !result.body.testArtifacts - ? undefined - : { - inputArtifacts: !result.body.testArtifacts?.inputArtifacts - ? undefined - : { - configFileInfo: !result.body.testArtifacts?.inputArtifacts - ?.configFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["validationFailureDetails"], - }, - testScriptFileInfo: !result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["validationFailureDetails"], - }, - userPropFileInfo: !result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["validationFailureDetails"], - }, - inputArtifactsZipFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.inputArtifactsZipFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "validationFailureDetails" - ], - }, - urlTestConfigFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationFailureDetails"], - }, - additionalFileInfo: - result.body.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ] === undefined - ? result.body.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ] - : result.body.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ].map((p: any) => { - return { - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"], - validationFailureDetails: - p["validationFailureDetails"], - }; - }), - }, - outputArtifacts: !result.body.testArtifacts?.outputArtifacts - ? undefined - : { - resultFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["validationFailureDetails"], - }, - logsFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationFailureDetails"], - }, - artifactsContainerInfo: !result.body.testArtifacts - ?.outputArtifacts?.artifactsContainerInfo - ? undefined - : { - url: result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"], - ) - : undefined, - }, - reportFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationFailureDetails"], - }, - }, - }, - testResult: result.body["testResult"], - virtualUsers: result.body["virtualUsers"], - displayName: result.body["displayName"], - testId: result.body["testId"], - description: result.body["description"], - status: result.body["status"], - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - executedDateTime: - result.body["executedDateTime"] !== undefined - ? new Date(result.body["executedDateTime"]) - : undefined, - portalUrl: result.body["portalUrl"], - duration: result.body["duration"], - subnetId: result.body["subnetId"], - kind: result.body["kind"], - requestDataLevel: result.body["requestDataLevel"], - debugLogsEnabled: result.body["debugLogsEnabled"], - publicIPDisabled: result.body["publicIPDisabled"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testRunDeserializer(result.body); } /** Stop test run by test run Id. */ diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/options.ts similarity index 98% rename from packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/options.ts rename to packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/options.ts index a9db996d62..6aa6653bbd 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/options.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { OperationOptions } from "@azure-rest/core-client"; -import { TimeGrain } from "./models.js"; +import { TimeGrain } from "../../models/models.js"; /** Optional parameters. */ export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/index.ts index 78cdac4d30..3cbd04210a 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/index.ts @@ -1,93 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +export { LoadTestRunClient } from "./loadTestRunClient.js"; export { - LoadTestRunClient, + LoadTestRunContext, LoadTestRunClientOptionalParams, -} from "./loadTestRunClient.js"; -export { - Test, - PassFailCriteria, - PassFailMetric, - KnownPFMetrics, - PFMetrics, - KnownPFAgFunc, - PFAgFunc, - KnownPFAction, - PFAction, - KnownPFResult, - PFResult, - AutoStopCriteria, - Secret, - KnownSecretType, - SecretType, - CertificateMetadata, - KnownCertificateType, - CertificateType, - LoadTestConfiguration, - OptionalLoadTestConfig, - RegionalConfiguration, - TestInputArtifacts, - TestFileInfo, - KnownFileType, - FileType, - KnownFileStatus, - FileStatus, - KnownTestKind, - TestKind, - TestAppComponents, - AppComponent, - TestServerMetricConfig, - ResourceMetric, - APIVersions, - TestRun, - ErrorDetails, - TestRunStatistics, - TestRunArtifacts, - TestRunInputArtifacts, - TestRunFileInfo, - TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, - PFTestResult, - KnownStatus, - Status, - KnownRequestDataLevel, - RequestDataLevel, - TestRunAppComponents, - TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, - DimensionValueList, - MetricDefinitionCollection, - MetricDefinition, - NameAndDesc, - KnownAggregationType, - AggregationType, - KnownMetricUnit, - MetricUnit, - MetricAvailability, - MetricNamespaceCollection, - MetricNamespace, - MetricRequestPayload, - DimensionFilter, - TimeSeriesElement, - MetricValue, - DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, @@ -102,4 +19,4 @@ export { ListMetricsOptionalParams, ListTestRunsOptionalParams, StopTestRunOptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/loadTestRunClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/loadTestRunClient.ts index 953b812322..295ad3931e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/loadTestRunClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/loadTestRunClient.ts @@ -1,38 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; -import { - TestRun, - TestRunFileInfo, - TestRunAppComponents, - TestRunServerMetricConfig, - DimensionValueList, - MetricDefinitionCollection, - MetricNamespaceCollection, - MetricRequestPayload, - TimeSeriesElement, -} from "./models/models.js"; -import { - CreateOrUpdateTestRunOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - DeleteTestRunOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestRunOptionalParams, - GetTestRunFileOptionalParams, - ListMetricDimensionValuesOptionalParams, - ListMetricDefinitionsOptionalParams, - ListMetricNamespacesOptionalParams, - ListMetricsOptionalParams, - ListTestRunsOptionalParams, - StopTestRunOptionalParams, -} from "./models/options.js"; import { createLoadTestRun, - LoadTestServiceContext, + LoadTestRunContext, LoadTestRunClientOptionalParams, createOrUpdateTestRun, createOrUpdateAppComponents, @@ -48,13 +19,40 @@ import { listMetrics, listTestRuns, stopTestRun, + CreateOrUpdateTestRunOptionalParams, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + DeleteTestRunOptionalParams, + GetAppComponentsOptionalParams, + GetServerMetricsConfigOptionalParams, + GetTestRunOptionalParams, + GetTestRunFileOptionalParams, + ListMetricDimensionValuesOptionalParams, + ListMetricDefinitionsOptionalParams, + ListMetricNamespacesOptionalParams, + ListMetricsOptionalParams, + ListTestRunsOptionalParams, + StopTestRunOptionalParams, } from "./api/index.js"; +import { + TestRun, + TestRunFileInfo, + TestRunAppComponents, + TestRunServerMetricConfig, + DimensionValueList, + MetricDefinitionCollection, + MetricNamespaceCollection, + MetricRequestPayload, + TimeSeriesElement, +} from "../models/models.js"; import { PagedAsyncIterableIterator } from "../static-helpers/pagingHelpers.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TokenCredential } from "@azure/core-auth"; export { LoadTestRunClientOptionalParams } from "./api/loadTestRunContext.js"; export class LoadTestRunClient { - private _client: LoadTestServiceContext; + private _client: LoadTestRunContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/index.ts deleted file mode 100644 index 85824e554b..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/index.ts +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -export { - Test, - PassFailCriteria, - PassFailMetric, - KnownPFMetrics, - PFMetrics, - KnownPFAgFunc, - PFAgFunc, - KnownPFAction, - PFAction, - KnownPFResult, - PFResult, - AutoStopCriteria, - Secret, - KnownSecretType, - SecretType, - CertificateMetadata, - KnownCertificateType, - CertificateType, - LoadTestConfiguration, - OptionalLoadTestConfig, - RegionalConfiguration, - TestInputArtifacts, - TestFileInfo, - KnownFileType, - FileType, - KnownFileStatus, - FileStatus, - KnownTestKind, - TestKind, - TestAppComponents, - AppComponent, - TestServerMetricConfig, - ResourceMetric, - APIVersions, - TestRun, - ErrorDetails, - TestRunStatistics, - TestRunArtifacts, - TestRunInputArtifacts, - TestRunFileInfo, - TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, - PFTestResult, - KnownStatus, - Status, - KnownRequestDataLevel, - RequestDataLevel, - TestRunAppComponents, - TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, - DimensionValueList, - MetricDefinitionCollection, - MetricDefinition, - NameAndDesc, - KnownAggregationType, - AggregationType, - KnownMetricUnit, - MetricUnit, - MetricAvailability, - MetricNamespaceCollection, - MetricNamespace, - MetricRequestPayload, - DimensionFilter, - TimeSeriesElement, - MetricValue, - DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, -} from "./models.js"; -export { - CreateOrUpdateTestRunOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - DeleteTestRunOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestRunOptionalParams, - GetTestRunFileOptionalParams, - ListMetricDimensionValuesOptionalParams, - ListMetricDefinitionsOptionalParams, - ListMetricNamespacesOptionalParams, - ListMetricsOptionalParams, - ListTestRunsOptionalParams, - StopTestRunOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/models.ts deleted file mode 100644 index 046c225d0a..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/models.ts +++ /dev/null @@ -1,1615 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { serializeRecord } from "../../helpers/serializerHelpers.js"; - -/** Load test model. */ -export interface Test { - /** Pass fail criteria for a test. */ - passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; - /** - * Secrets can be stored in an Azure Key Vault or any other secret store. If the - * secret is stored in an Azure Key Vault, the value should be the secret - * identifier and the type should be AKV_SECRET_URI. If the secret is stored - * elsewhere, the secret value should be provided directly and the type should be - * SECRET_VALUE. - */ - secrets?: Record; - /** Certificates metadata. */ - certificate?: CertificateMetadata; - /** Environment variables which are defined as a set of pairs. */ - environmentVariables?: Record; - /** The load test configuration. */ - loadTestConfiguration?: LoadTestConfiguration; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; - /** The input artifacts for the test. */ - readonly inputArtifacts?: TestInputArtifacts; - /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testId: string; - /** The test description. */ - description?: string; - /** Display name of a test. */ - displayName?: string; - /** Subnet ID on which the load test instances should run. */ - subnetId?: string; - /** Kind of test. */ - kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; - /** Type of the managed identity referencing the Key vault. */ - keyvaultReferenceIdentityType?: string; - /** Resource Id of the managed identity referencing the Key vault. */ - keyvaultReferenceIdentityId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testSerializer(item: Test): Record { - return { - passFailCriteria: !item.passFailCriteria - ? item.passFailCriteria - : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), - secrets: !item.secrets - ? item.secrets - : (serializeRecord(item.secrets as any, secretSerializer) as any), - certificate: !item.certificate - ? item.certificate - : certificateMetadataSerializer(item.certificate), - environmentVariables: !item.environmentVariables - ? item.environmentVariables - : (serializeRecord(item.environmentVariables as any) as any), - loadTestConfiguration: !item.loadTestConfiguration - ? item.loadTestConfiguration - : loadTestConfigurationSerializer(item.loadTestConfiguration), - baselineTestRunId: item["baselineTestRunId"], - description: item["description"], - displayName: item["displayName"], - subnetId: item["subnetId"], - kind: item["kind"], - publicIPDisabled: item["publicIPDisabled"], - keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], - keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], - }; -} - -/** Pass fail criteria for a test. */ -export interface PassFailCriteria { - /** Map of id and pass fail metrics { id : pass fail metrics }. */ - passFailMetrics?: Record; -} - -export function passFailCriteriaSerializer( - item: PassFailCriteria, -): Record { - return { - passFailMetrics: !item.passFailMetrics - ? item.passFailMetrics - : (serializeRecord( - item.passFailMetrics as any, - passFailMetricSerializer, - ) as any), - }; -} - -/** Pass fail metric */ -export interface PassFailMetric { - /** The client metric on which the criteria should be applied. */ - clientMetric?: PFMetrics; - /** - * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, - * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, - * ‘count’ - for requests - */ - aggregate?: PFAgFunc; - /** The comparison operator. Supported types ‘>’, ‘<’ */ - condition?: string; - /** Request name for which the Pass fail criteria has to be applied */ - requestName?: string; - /** - * The value to compare with the client metric. Allowed values - ‘error : [0.0 , - * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. - */ - value?: number; - /** Action taken after the threshold is met. Default is ‘continue’. */ - action?: PFAction; - /** The actual value of the client metric for the test run. */ - readonly actualValue?: number; - /** Outcome of the test run. */ - readonly result?: PFResult; -} - -export function passFailMetricSerializer( - item: PassFailMetric, -): Record { - return { - clientMetric: item["clientMetric"], - aggregate: item["aggregate"], - condition: item["condition"], - requestName: item["requestName"], - value: item["value"], - action: item["action"], - }; -} - -/** Known values of {@link PFMetrics} that the service accepts. */ -export enum KnownPFMetrics { - /** response_time_ms */ - response_time_ms = "response_time_ms", - /** latency */ - latency = "latency", - /** error */ - error = "error", - /** requests */ - requests = "requests", - /** requests_per_sec */ - requests_per_sec = "requests_per_sec", -} - -/** - * Metrics for pass/fail criteria. \ - * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **response_time_ms** \ - * **latency** \ - * **error** \ - * **requests** \ - * **requests_per_sec** - */ -export type PFMetrics = string; - -/** Known values of {@link PFAgFunc} that the service accepts. */ -export enum KnownPFAgFunc { - /** count */ - count = "count", - /** percentage */ - percentage = "percentage", - /** avg */ - avg = "avg", - /** p50 */ - p50 = "p50", - /** p75 */ - p75 = "p75", - /** p90 */ - p90 = "p90", - /** p95 */ - p95 = "p95", - /** p96 */ - p96 = "p96", - /** p97 */ - p97 = "p97", - /** p98 */ - p98 = "p98", - /** p99 */ - p99 = "p99", - /** p99.9 */ - "p99.9" = "p99.9", - /** p99.99 */ - "p99.99" = "p99.99", - /** min */ - min = "min", - /** max */ - max = "max", -} - -/** - * Aggregation functions for pass/fail criteria. \ - * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **count** \ - * **percentage** \ - * **avg** \ - * **p50** \ - * **p75** \ - * **p90** \ - * **p95** \ - * **p96** \ - * **p97** \ - * **p98** \ - * **p99** \ - * **p99.9** \ - * **p99.99** \ - * **min** \ - * **max** - */ -export type PFAgFunc = string; - -/** Known values of {@link PFAction} that the service accepts. */ -export enum KnownPFAction { - /** continue */ - "continue" = "continue", - /** stop */ - stop = "stop", -} - -/** - * Action to take on failure of pass/fail criteria. \ - * {@link KnownPFAction} can be used interchangeably with PFAction, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **continue** \ - * **stop** - */ -export type PFAction = string; - -/** Known values of {@link PFResult} that the service accepts. */ -export enum KnownPFResult { - /** passed */ - passed = "passed", - /** undetermined */ - undetermined = "undetermined", - /** failed */ - failed = "failed", -} - -/** - * Pass/fail criteria result. \ - * {@link KnownPFResult} can be used interchangeably with PFResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **passed** \ - * **undetermined** \ - * **failed** - */ -export type PFResult = string; - -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteria { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} - -export function autoStopCriteriaSerializer( - item: AutoStopCriteria, -): Record { - return { - autoStopDisabled: item["autoStopDisabled"], - errorRate: item["errorRate"], - errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], - }; -} - -/** Secret */ -export interface Secret { - /** The value of the secret for the respective type */ - value?: string; - /** Type of secret */ - type?: SecretType; -} - -export function secretSerializer(item: Secret): Record { - return { - value: item["value"], - type: item["type"], - }; -} - -/** Known values of {@link SecretType} that the service accepts. */ -export enum KnownSecretType { - /** AKV_SECRET_URI */ - AKV_SECRET_URI = "AKV_SECRET_URI", - /** SECRET_VALUE */ - SECRET_VALUE = "SECRET_VALUE", -} - -/** - * Types of secrets supported. \ - * {@link KnownSecretType} can be used interchangeably with SecretType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_SECRET_URI** \ - * **SECRET_VALUE** - */ -export type SecretType = string; - -/** Certificates metadata */ -export interface CertificateMetadata { - /** The value of the certificate for respective type */ - value?: string; - /** Type of certificate */ - type?: CertificateType; - /** Name of the certificate. */ - name?: string; -} - -export function certificateMetadataSerializer( - item: CertificateMetadata, -): Record { - return { - value: item["value"], - type: item["type"], - name: item["name"], - }; -} - -/** Known values of {@link CertificateType} that the service accepts. */ -export enum KnownCertificateType { - /** AKV_CERT_URI */ - AKV_CERT_URI = "AKV_CERT_URI", -} - -/** - * Types of certificates supported. \ - * {@link KnownCertificateType} can be used interchangeably with CertificateType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_CERT_URI** - */ -export type CertificateType = string; - -/** Configurations for the load test. */ -export interface LoadTestConfiguration { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ - engineInstances?: number; - /** - * If false, Azure Load Testing copies and processes your input files unmodified - * across all test engine instances. If true, Azure Load Testing splits the CSV - * input data evenly across all engine instances. If you provide multiple CSV - * files, each file will be split evenly. - */ - splitAllCSVs?: boolean; - /** - * If true, optionalLoadTestConfig is required and JMX script for the load test is - * not required to upload. - */ - quickStartTest?: boolean; - /** Configuration for quick load test */ - optionalLoadTestConfig?: OptionalLoadTestConfig; - /** Region distribution configuration for the load test. */ - regionalLoadTestConfig?: RegionalConfiguration[]; -} - -export function loadTestConfigurationSerializer( - item: LoadTestConfiguration, -): Record { - return { - engineInstances: item["engineInstances"], - splitAllCSVs: item["splitAllCSVs"], - quickStartTest: item["quickStartTest"], - optionalLoadTestConfig: !item.optionalLoadTestConfig - ? item.optionalLoadTestConfig - : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), - regionalLoadTestConfig: - item["regionalLoadTestConfig"] === undefined - ? item["regionalLoadTestConfig"] - : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), - }; -} - -/** Configuration for quick load test */ -export interface OptionalLoadTestConfig { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ - endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ - virtualUsers?: number; - /** Ramp up time in seconds. */ - rampUpTime?: number; - /** Test run duration in seconds. */ - duration?: number; -} - -export function optionalLoadTestConfigSerializer( - item: OptionalLoadTestConfig, -): Record { - return { - endpointUrl: item["endpointUrl"], - requestsPerSecond: item["requestsPerSecond"], - maxResponseTimeInMs: item["maxResponseTimeInMs"], - virtualUsers: item["virtualUsers"], - rampUpTime: item["rampUpTime"], - duration: item["duration"], - }; -} - -/** Region distribution configuration for the load test. */ -export interface RegionalConfiguration { - /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ - engineInstances: number; - /** - * Azure region name. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - region: string; -} - -export function regionalConfigurationSerializer( - item: RegionalConfiguration, -): Record { - return { - engineInstances: item["engineInstances"], - region: item["region"], - }; -} - -/** The input artifacts for the test. */ -export interface TestInputArtifacts { - /** File info */ - configFileInfo?: TestFileInfo; - /** File info */ - testScriptFileInfo?: TestFileInfo; - /** File info */ - userPropFileInfo?: TestFileInfo; - /** File info */ - inputArtifactsZipFileInfo?: TestFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfo; - /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestFileInfo[]; -} - -/** Test file info. */ -export interface TestFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; -} - -/** Known values of {@link FileType} that the service accepts. */ -export enum KnownFileType { - /** JMX_FILE */ - JMX_FILE = "JMX_FILE", - /** USER_PROPERTIES */ - USER_PROPERTIES = "USER_PROPERTIES", - /** ADDITIONAL_ARTIFACTS */ - ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", - /** ZIPPED_ARTIFACTS */ - ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", - /** URL_TEST_CONFIG */ - URL_TEST_CONFIG = "URL_TEST_CONFIG", - /** TEST_SCRIPT */ - TEST_SCRIPT = "TEST_SCRIPT", -} - -/** - * Types of file supported. \ - * {@link KnownFileType} can be used interchangeably with FileType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **JMX_FILE** \ - * **USER_PROPERTIES** \ - * **ADDITIONAL_ARTIFACTS** \ - * **ZIPPED_ARTIFACTS** \ - * **URL_TEST_CONFIG** \ - * **TEST_SCRIPT** - */ -export type FileType = string; - -/** Known values of {@link FileStatus} that the service accepts. */ -export enum KnownFileStatus { - /** NOT_VALIDATED */ - NOT_VALIDATED = "NOT_VALIDATED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", - /** VALIDATION_INITIATED */ - VALIDATION_INITIATED = "VALIDATION_INITIATED", - /** VALIDATION_NOT_REQUIRED */ - VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", -} - -/** - * File status. \ - * {@link KnownFileStatus} can be used interchangeably with FileStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NOT_VALIDATED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** \ - * **VALIDATION_INITIATED** \ - * **VALIDATION_NOT_REQUIRED** - */ -export type FileStatus = string; - -/** Known values of {@link TestKind} that the service accepts. */ -export enum KnownTestKind { - /** URL */ - URL = "URL", - /** JMX */ - JMX = "JMX", - /** Locust */ - Locust = "Locust", -} - -/** - * Test kind \ - * {@link KnownTestKind} can be used interchangeably with TestKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **URL** \ - * **JMX** \ - * **Locust** - */ -export type TestKind = string; - -/** Test app components */ -export interface TestAppComponents { - /** - * Azure resource collection { resource id (fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) - * : resource object } - */ - components: Record; - /** Test identifier */ - readonly testId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testAppComponentsSerializer( - item: TestAppComponents, -): Record { - return { - components: serializeRecord( - item.components as any, - appComponentSerializer, - ) as any, - }; -} - -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ -export interface AppComponent { - /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ - readonly resourceId: string; - /** Azure resource name, required while creating the app component. */ - resourceName: string; - /** Azure resource type, required while creating the app component. */ - resourceType: string; - /** Azure resource display name */ - displayName?: string; - /** Resource group name of the Azure resource */ - readonly resourceGroup?: string; - /** Subscription Id of the Azure resource */ - readonly subscriptionId?: string; - /** Kind of Azure resource type */ - kind?: string; -} - -export function appComponentSerializer( - item: AppComponent, -): Record { - return { - resourceName: item["resourceName"], - resourceType: item["resourceType"], - displayName: item["displayName"], - kind: item["kind"], - }; -} - -/** Test server metrics configuration */ -export interface TestServerMetricConfig { - /** Test identifier */ - readonly testId?: string; - /** - * Azure resource metrics collection {metric id : metrics object} (Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition - * for metric id). - */ - metrics: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testServerMetricConfigSerializer( - item: TestServerMetricConfig, -): Record { - return { - metrics: serializeRecord( - item.metrics as any, - resourceMetricSerializer, - ) as any, - }; -} - -/** - * Associated metric definition for particular metrics of the azure resource ( - * Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition). - */ -export interface ResourceMetric { - /** Unique name for metric. */ - readonly id?: string; - /** Azure resource id. */ - resourceId: string; - /** Metric name space. */ - metricNamespace: string; - /** Metric description. */ - displayDescription?: string; - /** The invariant value of metric name */ - name: string; - /** Metric aggregation. */ - aggregation: string; - /** Metric unit. */ - unit?: string; - /** Azure resource type. */ - resourceType: string; -} - -export function resourceMetricSerializer( - item: ResourceMetric, -): Record { - return { - resourceId: item["resourceId"], - metricNamespace: item["metricNamespace"], - displayDescription: item["displayDescription"], - name: item["name"], - aggregation: item["aggregation"], - unit: item["unit"], - resourceType: item["resourceType"], - }; -} - -/** Azure Load Testing API versions. */ -export type APIVersions = - | "2022-11-01" - | "2023-04-01-preview" - | "2024-03-01-preview" - | "2024-05-01-preview"; - -/** Load test run model */ -export interface TestRun { - /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testRunId: string; - /** Pass fail criteria for a test. */ - passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; - /** - * Secrets can be stored in an Azure Key Vault or any other secret store. If the - * secret is stored in an Azure Key Vault, the value should be the secret - * identifier and the type should be AKV_SECRET_URI. If the secret is stored - * elsewhere, the secret value should be provided directly and the type should be - * SECRET_VALUE. - */ - secrets?: Record; - /** Certificates metadata */ - certificate?: CertificateMetadata; - /** Environment variables which are defined as a set of pairs. */ - environmentVariables?: Record; - /** Error details if there is any failure in load test run */ - readonly errorDetails?: ErrorDetails[]; - /** - * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. - * The sampler name is the same as the name mentioned in the test script. - * Sampler name "Total" represents the aggregated statistics of all the samplers. - */ - readonly testRunStatistics?: Record; - /** - * Regional statistics. Key is the Azure region name and value is the test run statistics. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - readonly regionalStatistics?: Record; - /** The load test configuration. */ - loadTestConfiguration?: LoadTestConfiguration; - /** Collection of test run artifacts */ - readonly testArtifacts?: TestRunArtifacts; - /** Test result for pass/Fail criteria used during the test run. */ - readonly testResult?: PFTestResult; - /** Number of virtual users, for which test has been run. */ - readonly virtualUsers?: number; - /** Display name of a testRun. */ - displayName?: string; - /** Associated test Id. */ - testId?: string; - /** The test run description. */ - description?: string; - /** The test run status. */ - readonly status?: Status; - /** The test run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; - /** Test run initiated time. */ - readonly executedDateTime?: Date; - /** Portal url. */ - readonly portalUrl?: string; - /** Test run duration in milliseconds. */ - readonly duration?: number; - /** Subnet ID on which the load test instances should run. */ - readonly subnetId?: string; - /** Type of test. */ - readonly kind?: TestKind; - /** Request data collection level for test run */ - requestDataLevel?: RequestDataLevel; - /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ - debugLogsEnabled?: boolean; - /** Inject load test engines without deploying public IP for outbound access */ - readonly publicIPDisabled?: boolean; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunSerializer(item: TestRun): Record { - return { - passFailCriteria: !item.passFailCriteria - ? item.passFailCriteria - : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), - secrets: !item.secrets - ? item.secrets - : (serializeRecord(item.secrets as any, secretSerializer) as any), - certificate: !item.certificate - ? item.certificate - : certificateMetadataSerializer(item.certificate), - environmentVariables: !item.environmentVariables - ? item.environmentVariables - : (serializeRecord(item.environmentVariables as any) as any), - loadTestConfiguration: !item.loadTestConfiguration - ? item.loadTestConfiguration - : loadTestConfigurationSerializer(item.loadTestConfiguration), - displayName: item["displayName"], - testId: item["testId"], - description: item["description"], - requestDataLevel: item["requestDataLevel"], - debugLogsEnabled: item["debugLogsEnabled"], - }; -} - -/** Error details if there is any failure in load test run */ -export interface ErrorDetails { - /** Error details in case test run was not successfully run. */ - readonly message?: string; -} - -/** Test run statistics. */ -export interface TestRunStatistics { - /** Transaction name. */ - readonly transaction?: string; - /** Sampler count. */ - readonly sampleCount?: number; - /** Error count. */ - readonly errorCount?: number; - /** Error percentage. */ - readonly errorPct?: number; - /** Mean response time. */ - readonly meanResTime?: number; - /** Median response time. */ - readonly medianResTime?: number; - /** Max response time. */ - readonly maxResTime?: number; - /** Minimum response time. */ - readonly minResTime?: number; - /** 90 percentile response time. */ - readonly pct1ResTime?: number; - /** 95 percentile response time. */ - readonly pct2ResTime?: number; - /** 99 percentile response time. */ - readonly pct3ResTime?: number; - /** 75 percentile response time. */ - readonly pct75ResTime?: number; - /** 96 percentile response time. */ - readonly pct96ResTime?: number; - /** 97 percentile response time. */ - readonly pct97ResTime?: number; - /** 98 percentile response time. */ - readonly pct98ResTime?: number; - /** 99.9 percentile response time. */ - readonly pct999ResTime?: number; - /** 99.99 percentile response time. */ - readonly pct9999ResTime?: number; - /** Throughput. */ - readonly throughput?: number; - /** Received network bytes. */ - readonly receivedKBytesPerSec?: number; - /** Send network bytes. */ - readonly sentKBytesPerSec?: number; -} - -/** Collection of test run artifacts */ -export interface TestRunArtifacts { - /** The input artifacts for the test run. */ - readonly inputArtifacts?: TestRunInputArtifacts; - /** The output artifacts for the test run. */ - outputArtifacts?: TestRunOutputArtifacts; -} - -/** The input artifacts for the test run. */ -export interface TestRunInputArtifacts { - /** File info */ - configFileInfo?: TestRunFileInfo; - /** File info */ - testScriptFileInfo?: TestRunFileInfo; - /** File info */ - userPropFileInfo?: TestRunFileInfo; - /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfo; - /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestRunFileInfo[]; -} - -/** Test run file info. */ -export interface TestRunFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; -} - -/** The output artifacts for the test run. */ -export interface TestRunOutputArtifacts { - /** File info */ - resultFileInfo?: TestRunFileInfo; - /** File info */ - logsFileInfo?: TestRunFileInfo; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfo; - /** The report file for the test run. */ - reportFileInfo?: TestRunFileInfo; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfo { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: Date; -} - -/** Known values of {@link PFTestResult} that the service accepts. */ -export enum KnownPFTestResult { - /** PASSED */ - PASSED = "PASSED", - /** NOT_APPLICABLE */ - NOT_APPLICABLE = "NOT_APPLICABLE", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test result based on pass/fail criteria. \ - * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PASSED** \ - * **NOT_APPLICABLE** \ - * **FAILED** - */ -export type PFTestResult = string; - -/** Known values of {@link Status} that the service accepts. */ -export enum KnownStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** PROVISIONING */ - PROVISIONING = "PROVISIONING", - /** PROVISIONED */ - PROVISIONED = "PROVISIONED", - /** CONFIGURING */ - CONFIGURING = "CONFIGURING", - /** CONFIGURED */ - CONFIGURED = "CONFIGURED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** EXECUTED */ - EXECUTED = "EXECUTED", - /** DEPROVISIONING */ - DEPROVISIONING = "DEPROVISIONING", - /** DEPROVISIONED */ - DEPROVISIONED = "DEPROVISIONED", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", -} - -/** - * Test run status. \ - * {@link KnownStatus} can be used interchangeably with Status, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **PROVISIONING** \ - * **PROVISIONED** \ - * **CONFIGURING** \ - * **CONFIGURED** \ - * **EXECUTING** \ - * **EXECUTED** \ - * **DEPROVISIONING** \ - * **DEPROVISIONED** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** - */ -export type Status = string; - -/** Known values of {@link RequestDataLevel} that the service accepts. */ -export enum KnownRequestDataLevel { - /** NONE */ - NONE = "NONE", - /** ERRORS */ - ERRORS = "ERRORS", -} - -/** - * Request data collection level for test run \ - * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NONE** \ - * **ERRORS** - */ -export type RequestDataLevel = string; - -/** Test run app component */ -export interface TestRunAppComponents { - /** - * Azure resource collection { resource id (fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) - * : resource object } - */ - components: Record; - /** Test run identifier */ - readonly testRunId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunAppComponentsSerializer( - item: TestRunAppComponents, -): Record { - return { - components: serializeRecord( - item.components as any, - appComponentSerializer, - ) as any, - }; -} - -/** Test run server metrics configuration */ -export interface TestRunServerMetricConfig { - /** Test run identifier */ - readonly testRunId?: string; - /** - * Azure resource metrics collection {metric id : metrics object} (Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition - * for metric id). - */ - metrics?: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunServerMetricConfigSerializer( - item: TestRunServerMetricConfig, -): Record { - return { - metrics: !item.metrics - ? item.metrics - : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), - }; -} - -/** Known values of {@link TimeGrain} that the service accepts. */ -export enum KnownTimeGrain { - /** PT5S */ - PT5S = "PT5S", - /** PT10S */ - PT10S = "PT10S", - /** PT1M */ - PT1M = "PT1M", - /** PT5M */ - PT5M = "PT5M", - /** PT1H */ - PT1H = "PT1H", -} - -/** - * Time Grain \ - * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PT5S** \ - * **PT10S** \ - * **PT1M** \ - * **PT5M** \ - * **PT1H** - */ -export type TimeGrain = string; - -/** Metrics dimension values. */ -export interface DimensionValueList { - /** The dimension name */ - readonly name?: string; - /** The dimension value */ - value?: string[]; - /** Link for the next set of values in case of paginated results, if applicable. */ - nextLink?: string; -} - -/** Represents collection of metric definitions. */ -export interface MetricDefinitionCollection { - /** the values for the metric definitions. */ - value: MetricDefinition[]; -} - -/** Metric definition */ -export interface MetricDefinition { - /** List of dimensions */ - dimensions?: NameAndDesc[]; - /** The metric description */ - description?: string; - /** The metric name */ - name?: string; - /** The namespace the metric belongs to. */ - namespace?: string; - /** The primary aggregation type value defining how to use the values for display. */ - primaryAggregationType?: AggregationType; - /** The collection of what all aggregation types are supported. */ - supportedAggregationTypes?: string[]; - /** The unit of the metric. */ - unit?: MetricUnit; - /** - * Metric availability specifies the time grain (aggregation interval or - * frequency). - */ - metricAvailabilities?: MetricAvailability[]; -} - -/** The name and description */ -export interface NameAndDesc { - /** The description */ - description?: string; - /** The name */ - name?: string; -} - -/** Known values of {@link AggregationType} that the service accepts. */ -export enum KnownAggregationType { - /** Average */ - Average = "Average", - /** Count */ - Count = "Count", - /** None */ - None = "None", - /** Total */ - Total = "Total", - /** Percentile75 */ - Percentile75 = "Percentile75", - /** Percentile90 */ - Percentile90 = "Percentile90", - /** Percentile95 */ - Percentile95 = "Percentile95", - /** Percentile96 */ - Percentile96 = "Percentile96", - /** Percentile97 */ - Percentile97 = "Percentile97", - /** Percentile98 */ - Percentile98 = "Percentile98", - /** Percentile99 */ - Percentile99 = "Percentile99", - /** Percentile999 */ - Percentile999 = "Percentile999", - /** Percentile9999 */ - Percentile9999 = "Percentile9999", -} - -/** - * Aggregation type. \ - * {@link KnownAggregationType} can be used interchangeably with AggregationType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **Average** \ - * **Count** \ - * **None** \ - * **Total** \ - * **Percentile75** \ - * **Percentile90** \ - * **Percentile95** \ - * **Percentile96** \ - * **Percentile97** \ - * **Percentile98** \ - * **Percentile99** \ - * **Percentile999** \ - * **Percentile9999** - */ -export type AggregationType = string; - -/** Known values of {@link MetricUnit} that the service accepts. */ -export enum KnownMetricUnit { - /** NotSpecified */ - NotSpecified = "NotSpecified", - /** Percent */ - Percent = "Percent", - /** Count */ - Count = "Count", - /** Seconds */ - Seconds = "Seconds", - /** Milliseconds */ - Milliseconds = "Milliseconds", - /** Bytes */ - Bytes = "Bytes", - /** BytesPerSecond */ - BytesPerSecond = "BytesPerSecond", - /** CountPerSecond */ - CountPerSecond = "CountPerSecond", -} - -/** - * Metric unit. \ - * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NotSpecified** \ - * **Percent** \ - * **Count** \ - * **Seconds** \ - * **Milliseconds** \ - * **Bytes** \ - * **BytesPerSecond** \ - * **CountPerSecond** - */ -export type MetricUnit = string; - -/** Metric availability specifies the time grain (aggregation interval or frequency) */ -export interface MetricAvailability { - /** - * The time grain specifies the aggregation interval for the metric. Expressed as - * a duration 'PT1M', 'PT1H', etc. - */ - timeGrain?: TimeGrain; -} - -/** Represents collection of metric namespaces. */ -export interface MetricNamespaceCollection { - /** The values for the metric namespaces. */ - value: MetricNamespace[]; -} - -/** Metric namespace class specifies the metadata for a metric namespace. */ -export interface MetricNamespace { - /** The namespace description. */ - description?: string; - /** The metric namespace name. */ - name?: string; -} - -/** Filters to fetch the set of metric. */ -export interface MetricRequestPayload { - /** - * Get metrics for specific dimension values. Example: Metric contains dimension - * like SamplerName, Error. To retrieve all the time series data where SamplerName - * is equals to HTTPRequest1 or HTTPRequest2, the DimensionFilter value will be - * {"SamplerName", ["HTTPRequest1", "HTTPRequest2"} - */ - filters?: DimensionFilter[]; -} - -export function metricRequestPayloadSerializer( - item: MetricRequestPayload, -): Record { - return { - filters: - item["filters"] === undefined - ? item["filters"] - : item["filters"].map(dimensionFilterSerializer), - }; -} - -/** Dimension name and values to filter */ -export interface DimensionFilter { - /** The dimension name */ - name?: string; - /** The dimension values. Maximum values can be 20. */ - values?: string[]; -} - -export function dimensionFilterSerializer( - item: DimensionFilter, -): Record { - return { - name: item["name"], - values: item["values"], - }; -} - -/** The response to a metrics query. */ -export interface _Metrics { - /** The TimeSeriesElement items on this page */ - value: TimeSeriesElement[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** The time series returned when a data query is performed. */ -export interface TimeSeriesElement { - /** An array of data points representing the metric values. */ - data?: MetricValue[]; - /** The dimension values */ - dimensionValues?: DimensionValue[]; -} - -/** Represents a metric value. */ -export interface MetricValue { - /** The timestamp for the metric value in RFC 3339 format. */ - timestamp?: Date; - /** The metric value. */ - value?: number; -} - -/** Represents a metric dimension value. */ -export interface DimensionValue { - /** The name of the dimension. */ - name?: string; - /** The value of the dimension. */ - value?: string; -} - -/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ -export interface TestProfile { - /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileId: string; - /** Display name of the test profile. */ - displayName?: string; - /** Description for the test profile. */ - description?: string; - /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ - testId?: string; - /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ - targetResourceId?: string; - /** Configurations of the target resource on which testing would be done. */ - targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileSerializer( - item: TestProfile, -): Record { - return { - displayName: item["displayName"], - description: item["description"], - testId: item["testId"], - targetResourceId: item["targetResourceId"], - targetResourceConfigurations: !item.targetResourceConfigurations - ? item.targetResourceConfigurations - : targetResourceConfigurationsUnionSerializer( - item.targetResourceConfigurations, - ), - }; -} - -/** Configurations of a target resource. This varies with the kind of resource. */ -export interface TargetResourceConfigurations { - /** the discriminator possible values: FunctionsFlexConsumption */ - kind: ResourceKind; -} - -export function targetResourceConfigurationsUnionSerializer( - item: TargetResourceConfigurationsUnion, -) { - switch (item.kind) { - case "FunctionsFlexConsumption": - return functionFlexConsumptionTargetResourceConfigurationsSerializer( - item as FunctionFlexConsumptionTargetResourceConfigurations, - ); - - default: - return targetResourceConfigurationsSerializer(item); - } -} - -export function targetResourceConfigurationsSerializer( - item: TargetResourceConfigurationsUnion, -): Record { - return { - kind: item["kind"], - }; -} - -/** Configurations for a Function App using Flex Consumption Plan. */ -export interface FunctionFlexConsumptionTargetResourceConfigurations - extends TargetResourceConfigurations { - /** - * The kind value to use when providing configuration. - * This should typically be not changed from its value. - */ - kind: "FunctionsFlexConsumption"; - /** A map of configurations for a Function app using Flex Consumption Plan. */ - configurations?: Record; -} - -export function functionFlexConsumptionTargetResourceConfigurationsSerializer( - item: FunctionFlexConsumptionTargetResourceConfigurations, -): Record { - return { - kind: item["kind"], - configurations: !item.configurations - ? item.configurations - : (serializeRecord( - item.configurations as any, - functionFlexConsumptionResourceConfigurationSerializer, - ) as any), - }; -} - -/** Resource configuration instance for a Flex Consumption based Azure Function App. */ -export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 2048, 4096. */ - instanceMemoryMB: number; - /** HTTP Concurrency for the function app. */ - httpConcurrency: number; -} - -export function functionFlexConsumptionResourceConfigurationSerializer( - item: FunctionFlexConsumptionResourceConfiguration, -): Record { - return { - instanceMemoryMB: item["instanceMemoryMB"], - httpConcurrency: item["httpConcurrency"], - }; -} - -/** Known values of {@link ResourceKind} that the service accepts. */ -export enum KnownResourceKind { - /** FunctionsFlexConsumption */ - FunctionsFlexConsumption = "FunctionsFlexConsumption", -} - -/** - * Kind of the resource on which test profile is created. \ - * {@link KnownResourceKind} can be used interchangeably with ResourceKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **FunctionsFlexConsumption** - */ -export type ResourceKind = string; - -/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ -export interface TestProfileRun { - /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileRunId: string; - /** Display name for the test profile run. */ - displayName?: string; - /** The test profile run description */ - description?: string; - /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ - testProfileId?: string; - /** Target resource ID on which the test profile run is created */ - readonly targetResourceId?: string; - /** Configurations of the target resource on which the test profile ran. */ - readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The test profile run status. */ - readonly status?: TestProfileRunStatus; - /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ - readonly errorDetails?: ErrorDetails[]; - /** The test profile run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test profile run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; - /** Test profile run duration in seconds. */ - readonly durationInSeconds?: number; - /** - * Details of the test runs ran as part of the test profile run. - * Key is the testRunId of the corresponding testRun. - */ - readonly testRunDetails?: Record; - /** Recommendations provided based on a successful test profile run. */ - readonly recommendations?: TestProfileRunRecommendation[]; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileRunSerializer( - item: TestProfileRun, -): Record { - return { - displayName: item["displayName"], - description: item["description"], - testProfileId: item["testProfileId"], - }; -} - -/** Known values of {@link TestProfileRunStatus} that the service accepts. */ -export enum KnownTestProfileRunStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test profile run status. \ - * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **EXECUTING** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** - */ -export type TestProfileRunStatus = string; - -/** Details of a particular test run for a test profile run. */ -export interface TestRunDetail { - /** Status of the test run. */ - status: Status; - /** ID of the configuration on which the test ran. */ - configurationId: string; - /** Key value pair of extra properties associated with the test run. */ - properties: Record; -} - -/** A recommendation object that provides a list of configuration that optimizes its category. */ -export interface TestProfileRunRecommendation { - /** Category of the recommendation. */ - category: RecommendationCategory; - /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ - configurations?: string[]; -} - -/** Known values of {@link RecommendationCategory} that the service accepts. */ -export enum KnownRecommendationCategory { - /** ThroughputOptimized */ - ThroughputOptimized = "ThroughputOptimized", - /** CostOptimized */ - CostOptimized = "CostOptimized", -} - -/** - * Category of Recommendation. \ - * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ThroughputOptimized** \ - * **CostOptimized** - */ -export type RecommendationCategory = string; - -/** Paged collection of TestFileInfo items */ -export interface _PagedTestFileInfo { - /** The TestFileInfo items on this page */ - value: TestFileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of Test items */ -export interface _PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestRun items */ -export interface _PagedTestRun { - /** The TestRun items on this page */ - value: TestRun[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestProfile items */ -export interface _PagedTestProfile { - /** The TestProfile items on this page */ - value: TestProfile[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestProfileRun items */ -export interface _PagedTestProfileRun { - /** The TestProfileRun items on this page */ - value: TestProfileRun[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Alias for TargetResourceConfigurationsUnion */ -export type TargetResourceConfigurationsUnion = - | FunctionFlexConsumptionTargetResourceConfigurations - | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/models/index.ts similarity index 90% rename from packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/models/index.ts rename to packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/models/index.ts index 472f9e1a63..a50a8878e2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/models/index.ts @@ -35,7 +35,6 @@ export { AppComponent, TestServerMetricConfig, ResourceMetric, - APIVersions, TestRun, ErrorDetails, TestRunStatistics, @@ -52,8 +51,6 @@ export { RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -63,6 +60,8 @@ export { KnownMetricUnit, MetricUnit, MetricAvailability, + KnownTimeGrain, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -72,10 +71,11 @@ export { DimensionValue, TestProfile, TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, + TargetResourceConfigurationsUnion, KnownResourceKind, ResourceKind, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, TestProfileRun, KnownTestProfileRunStatus, TestProfileRunStatus, @@ -83,11 +83,4 @@ export { TestProfileRunRecommendation, KnownRecommendationCategory, RecommendationCategory, - TargetResourceConfigurationsUnion, } from "./models.js"; -export { - CreateOrUpdateTestProfileOptionalParams, - DeleteTestProfileOptionalParams, - GetTestProfileOptionalParams, - ListTestProfilesOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/models/models.ts new file mode 100644 index 0000000000..676ef53a97 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/models/models.ts @@ -0,0 +1,2546 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** Load test model. */ +export interface Test { + /** Pass fail criteria for a test. */ + passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; + /** + * Secrets can be stored in an Azure Key Vault or any other secret store. If the + * secret is stored in an Azure Key Vault, the value should be the secret + * identifier and the type should be AKV_SECRET_URI. If the secret is stored + * elsewhere, the secret value should be provided directly and the type should be + * SECRET_VALUE. + */ + secrets?: Record; + /** Certificates metadata. */ + certificate?: CertificateMetadata; + /** Environment variables which are defined as a set of pairs. */ + environmentVariables?: Record; + /** The load test configuration. */ + loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; + /** The input artifacts for the test. */ + readonly inputArtifacts?: TestInputArtifacts; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; + /** The test description. */ + description?: string; + /** Display name of a test. */ + displayName?: string; + /** Subnet ID on which the load test instances should run. */ + subnetId?: string; + /** Kind of test. */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; + /** Type of the managed identity referencing the Key vault. */ + keyvaultReferenceIdentityType?: string; + /** Resource Id of the managed identity referencing the Key vault. */ + keyvaultReferenceIdentityId?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testSerializer(item: Test): any { + return { + passFailCriteria: !item["passFailCriteria"] + ? item["passFailCriteria"] + : passFailCriteriaSerializer(item["passFailCriteria"]), + autoStopCriteria: !item["autoStopCriteria"] + ? item["autoStopCriteria"] + : autoStopCriteriaSerializer(item["autoStopCriteria"]), + secrets: !item["secrets"] + ? item["secrets"] + : secretRecordSerializer(item["secrets"]), + certificate: !item["certificate"] + ? item["certificate"] + : certificateMetadataSerializer(item["certificate"]), + environmentVariables: item["environmentVariables"], + loadTestConfiguration: !item["loadTestConfiguration"] + ? item["loadTestConfiguration"] + : loadTestConfigurationSerializer(item["loadTestConfiguration"]), + baselineTestRunId: item["baselineTestRunId"], + description: item["description"], + displayName: item["displayName"], + subnetId: item["subnetId"], + kind: item["kind"], + publicIPDisabled: item["publicIPDisabled"], + keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], + keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], + }; +} + +export function testDeserializer(item: any): Test { + return { + passFailCriteria: !item["passFailCriteria"] + ? item["passFailCriteria"] + : passFailCriteriaDeserializer(item["passFailCriteria"]), + autoStopCriteria: !item["autoStopCriteria"] + ? item["autoStopCriteria"] + : autoStopCriteriaDeserializer(item["autoStopCriteria"]), + secrets: !item["secrets"] + ? item["secrets"] + : secretRecordDeserializer(item["secrets"]), + certificate: !item["certificate"] + ? item["certificate"] + : certificateMetadataDeserializer(item["certificate"]), + environmentVariables: item["environmentVariables"], + loadTestConfiguration: !item["loadTestConfiguration"] + ? item["loadTestConfiguration"] + : loadTestConfigurationDeserializer(item["loadTestConfiguration"]), + baselineTestRunId: item["baselineTestRunId"], + inputArtifacts: !item["inputArtifacts"] + ? item["inputArtifacts"] + : testInputArtifactsDeserializer(item["inputArtifacts"]), + testId: item["testId"], + description: item["description"], + displayName: item["displayName"], + subnetId: item["subnetId"], + kind: item["kind"], + publicIPDisabled: item["publicIPDisabled"], + keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], + keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], + createdDateTime: !item["createdDateTime"] + ? item["createdDateTime"] + : new Date(item["createdDateTime"]), + createdBy: item["createdBy"], + lastModifiedDateTime: !item["lastModifiedDateTime"] + ? item["lastModifiedDateTime"] + : new Date(item["lastModifiedDateTime"]), + lastModifiedBy: item["lastModifiedBy"], + }; +} + +/** Pass fail criteria for a test. */ +export interface PassFailCriteria { + /** Map of id and pass fail metrics { id : pass fail metrics }. */ + passFailMetrics?: Record; +} + +export function passFailCriteriaSerializer(item: PassFailCriteria): any { + return { + passFailMetrics: !item["passFailMetrics"] + ? item["passFailMetrics"] + : passFailMetricRecordSerializer(item["passFailMetrics"]), + }; +} + +export function passFailCriteriaDeserializer(item: any): PassFailCriteria { + return { + passFailMetrics: !item["passFailMetrics"] + ? item["passFailMetrics"] + : passFailMetricRecordDeserializer(item["passFailMetrics"]), + }; +} + +/** Pass fail metric */ +export interface PassFailMetric { + /** The client metric on which the criteria should be applied. */ + clientMetric?: PFMetrics; + /** + * The aggregation function to be applied on the client metric. Allowed functions + * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, + * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, + * ‘count’ - for requests + */ + aggregate?: PFAgFunc; + /** The comparison operator. Supported types ‘>’, ‘<’ */ + condition?: string; + /** Request name for which the Pass fail criteria has to be applied */ + requestName?: string; + /** + * The value to compare with the client metric. Allowed values - ‘error : [0.0 , + * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. + */ + value?: number; + /** Action taken after the threshold is met. Default is ‘continue’. */ + action?: PFAction; + /** The actual value of the client metric for the test run. */ + readonly actualValue?: number; + /** Outcome of the test run. */ + readonly result?: PFResult; +} + +export function passFailMetricSerializer(item: PassFailMetric): any { + return { + clientMetric: item["clientMetric"], + aggregate: item["aggregate"], + condition: item["condition"], + requestName: item["requestName"], + value: item["value"], + action: item["action"], + }; +} + +export function passFailMetricDeserializer(item: any): PassFailMetric { + return { + clientMetric: item["clientMetric"], + aggregate: item["aggregate"], + condition: item["condition"], + requestName: item["requestName"], + value: item["value"], + action: item["action"], + actualValue: item["actualValue"], + result: item["result"], + }; +} + +/** Metrics for pass/fail criteria. */ +export enum KnownPFMetrics { + /** Pass fail criteria for response time metric in milliseconds. */ + response_time_ms = "response_time_ms", + /** Pass fail criteria for latency metric in milliseconds. */ + latency = "latency", + /** Pass fail criteria for error metric. */ + error = "error", + /** Pass fail criteria for total requests. */ + requests = "requests", + /** Pass fail criteria for request per second. */ + requests_per_sec = "requests_per_sec", +} + +/** + * Metrics for pass/fail criteria. \ + * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **response_time_ms**: Pass fail criteria for response time metric in milliseconds. \ + * **latency**: Pass fail criteria for latency metric in milliseconds. \ + * **error**: Pass fail criteria for error metric. \ + * **requests**: Pass fail criteria for total requests. \ + * **requests_per_sec**: Pass fail criteria for request per second. + */ +export type PFMetrics = string; + +/** Aggregation functions for pass/fail criteria. */ +export enum KnownPFAgFunc { + /** Criteria applies for count value. */ + count = "count", + /** Criteria applies for given percentage value. */ + percentage = "percentage", + /** Criteria applies for avg value. */ + avg = "avg", + /** Criteria applies for 50th percentile value. */ + p50 = "p50", + /** Criteria applies for 75th percentile value. */ + p75 = "p75", + /** Criteria applies for 90th percentile value. */ + p90 = "p90", + /** Criteria applies for 95th percentile value. */ + p95 = "p95", + /** Criteria applies for 96th percentile value. */ + p96 = "p96", + /** Criteria applies for 97th percentile value. */ + p97 = "p97", + /** Criteria applies for 98th percentile value. */ + p98 = "p98", + /** Criteria applies for 99th percentile value. */ + p99 = "p99", + /** Criteria applies for 99.9th percentile value. */ + "p99.9" = "p99.9", + /** Criteria applies for 99.99th percentile value. */ + "p99.99" = "p99.99", + /** Criteria applies for minimum value. */ + min = "min", + /** Criteria applies for maximum value. */ + max = "max", +} + +/** + * Aggregation functions for pass/fail criteria. \ + * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **count**: Criteria applies for count value. \ + * **percentage**: Criteria applies for given percentage value. \ + * **avg**: Criteria applies for avg value. \ + * **p50**: Criteria applies for 50th percentile value. \ + * **p75**: Criteria applies for 75th percentile value. \ + * **p90**: Criteria applies for 90th percentile value. \ + * **p95**: Criteria applies for 95th percentile value. \ + * **p96**: Criteria applies for 96th percentile value. \ + * **p97**: Criteria applies for 97th percentile value. \ + * **p98**: Criteria applies for 98th percentile value. \ + * **p99**: Criteria applies for 99th percentile value. \ + * **p99.9**: Criteria applies for 99.9th percentile value. \ + * **p99.99**: Criteria applies for 99.99th percentile value. \ + * **min**: Criteria applies for minimum value. \ + * **max**: Criteria applies for maximum value. + */ +export type PFAgFunc = string; + +/** Action to take on failure of pass/fail criteria. */ +export enum KnownPFAction { + /** Test will continue to run even if pass fail metric criteria metric gets failed. */ + "continue" = "continue", + /** Test run will stop if pass fail criteria metric is not passed. */ + stop = "stop", +} + +/** + * Action to take on failure of pass/fail criteria. \ + * {@link KnownPFAction} can be used interchangeably with PFAction, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **continue**: Test will continue to run even if pass fail metric criteria metric gets failed. \ + * **stop**: Test run will stop if pass fail criteria metric is not passed. + */ +export type PFAction = string; + +/** Pass/fail criteria result. */ +export enum KnownPFResult { + /** Given pass fail criteria metric has passed. */ + passed = "passed", + /** Given pass fail criteria metric couldn't determine. */ + undetermined = "undetermined", + /** Given pass fail criteria metric has failed. */ + failed = "failed", +} + +/** + * Pass/fail criteria result. \ + * {@link KnownPFResult} can be used interchangeably with PFResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **passed**: Given pass fail criteria metric has passed. \ + * **undetermined**: Given pass fail criteria metric couldn't determine. \ + * **failed**: Given pass fail criteria metric has failed. + */ +export type PFResult = string; + +export function passFailMetricRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] ? item[key] : passFailMetricSerializer(item[key]); + }); + return result; +} + +export function passFailMetricRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : passFailMetricDeserializer(item[key]); + }); + return result; +} + +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + +export function autoStopCriteriaSerializer(item: AutoStopCriteria): any { + return { + autoStopDisabled: item["autoStopDisabled"], + errorRate: item["errorRate"], + errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], + }; +} + +export function autoStopCriteriaDeserializer(item: any): AutoStopCriteria { + return { + autoStopDisabled: item["autoStopDisabled"], + errorRate: item["errorRate"], + errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], + }; +} + +/** Secret */ +export interface Secret { + /** The value of the secret for the respective type */ + value?: string; + /** Type of secret */ + type?: SecretType; +} + +export function secretSerializer(item: Secret): any { + return { value: item["value"], type: item["type"] }; +} + +export function secretDeserializer(item: any): Secret { + return { + value: item["value"], + type: item["type"], + }; +} + +/** Types of secrets supported. */ +export enum KnownSecretType { + /** If the secret is stored in an Azure Key Vault. */ + AKV_SECRET_URI = "AKV_SECRET_URI", + /** If the secret value provided as plain text. */ + SECRET_VALUE = "SECRET_VALUE", +} + +/** + * Types of secrets supported. \ + * {@link KnownSecretType} can be used interchangeably with SecretType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_SECRET_URI**: If the secret is stored in an Azure Key Vault. \ + * **SECRET_VALUE**: If the secret value provided as plain text. + */ +export type SecretType = string; + +export function secretRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] ? item[key] : secretSerializer(item[key]); + }); + return result; +} + +export function secretRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] ? item[key] : secretDeserializer(item[key]); + }); + return result; +} + +/** Certificates metadata */ +export interface CertificateMetadata { + /** The value of the certificate for respective type */ + value?: string; + /** Type of certificate */ + type?: CertificateType; + /** Name of the certificate. */ + name?: string; +} + +export function certificateMetadataSerializer(item: CertificateMetadata): any { + return { value: item["value"], type: item["type"], name: item["name"] }; +} + +export function certificateMetadataDeserializer( + item: any, +): CertificateMetadata { + return { + value: item["value"], + type: item["type"], + name: item["name"], + }; +} + +/** Types of certificates supported. */ +export enum KnownCertificateType { + /** If the certificate is stored in an Azure Key Vault. */ + AKV_CERT_URI = "AKV_CERT_URI", +} + +/** + * Types of certificates supported. \ + * {@link KnownCertificateType} can be used interchangeably with CertificateType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_CERT_URI**: If the certificate is stored in an Azure Key Vault. + */ +export type CertificateType = string; + +/** Configurations for the load test. */ +export interface LoadTestConfiguration { + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ + engineInstances?: number; + /** + * If false, Azure Load Testing copies and processes your input files unmodified + * across all test engine instances. If true, Azure Load Testing splits the CSV + * input data evenly across all engine instances. If you provide multiple CSV + * files, each file will be split evenly. + */ + splitAllCSVs?: boolean; + /** + * If true, optionalLoadTestConfig is required and JMX script for the load test is + * not required to upload. + */ + quickStartTest?: boolean; + /** Configuration for quick load test */ + optionalLoadTestConfig?: OptionalLoadTestConfig; + /** Region distribution configuration for the load test. */ + regionalLoadTestConfig?: RegionalConfiguration[]; +} + +export function loadTestConfigurationSerializer( + item: LoadTestConfiguration, +): any { + return { + engineInstances: item["engineInstances"], + splitAllCSVs: item["splitAllCSVs"], + quickStartTest: item["quickStartTest"], + optionalLoadTestConfig: !item["optionalLoadTestConfig"] + ? item["optionalLoadTestConfig"] + : optionalLoadTestConfigSerializer(item["optionalLoadTestConfig"]), + regionalLoadTestConfig: !item["regionalLoadTestConfig"] + ? item["regionalLoadTestConfig"] + : regionalConfigurationArraySerializer(item["regionalLoadTestConfig"]), + }; +} + +export function loadTestConfigurationDeserializer( + item: any, +): LoadTestConfiguration { + return { + engineInstances: item["engineInstances"], + splitAllCSVs: item["splitAllCSVs"], + quickStartTest: item["quickStartTest"], + optionalLoadTestConfig: !item["optionalLoadTestConfig"] + ? item["optionalLoadTestConfig"] + : optionalLoadTestConfigDeserializer(item["optionalLoadTestConfig"]), + regionalLoadTestConfig: !item["regionalLoadTestConfig"] + ? item["regionalLoadTestConfig"] + : regionalConfigurationArrayDeserializer(item["regionalLoadTestConfig"]), + }; +} + +/** Configuration for quick load test */ +export interface OptionalLoadTestConfig { + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ + endpointUrl?: string; + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ + virtualUsers?: number; + /** Ramp up time in seconds. */ + rampUpTime?: number; + /** Test run duration in seconds. */ + duration?: number; +} + +export function optionalLoadTestConfigSerializer( + item: OptionalLoadTestConfig, +): any { + return { + endpointUrl: item["endpointUrl"], + requestsPerSecond: item["requestsPerSecond"], + maxResponseTimeInMs: item["maxResponseTimeInMs"], + virtualUsers: item["virtualUsers"], + rampUpTime: item["rampUpTime"], + duration: item["duration"], + }; +} + +export function optionalLoadTestConfigDeserializer( + item: any, +): OptionalLoadTestConfig { + return { + endpointUrl: item["endpointUrl"], + requestsPerSecond: item["requestsPerSecond"], + maxResponseTimeInMs: item["maxResponseTimeInMs"], + virtualUsers: item["virtualUsers"], + rampUpTime: item["rampUpTime"], + duration: item["duration"], + }; +} + +/** Region distribution configuration for the load test. */ +export interface RegionalConfiguration { + /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ + engineInstances: number; + /** + * Azure region name. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + region: string; +} + +export function regionalConfigurationSerializer( + item: RegionalConfiguration, +): any { + return { engineInstances: item["engineInstances"], region: item["region"] }; +} + +export function regionalConfigurationDeserializer( + item: any, +): RegionalConfiguration { + return { + engineInstances: item["engineInstances"], + region: item["region"], + }; +} + +export function regionalConfigurationArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return regionalConfigurationSerializer(item); + }); +} + +export function regionalConfigurationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return regionalConfigurationDeserializer(item); + }); +} + +/** The input artifacts for the test. */ +export interface TestInputArtifacts { + /** File info */ + configFileInfo?: TestFileInfo; + /** File info */ + testScriptFileInfo?: TestFileInfo; + /** File info */ + userPropFileInfo?: TestFileInfo; + /** File info */ + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; + /** Additional supported files for the test run */ + readonly additionalFileInfo?: TestFileInfo[]; +} + +export function testInputArtifactsDeserializer(item: any): TestInputArtifacts { + return { + configFileInfo: !item["configFileInfo"] + ? item["configFileInfo"] + : testFileInfoDeserializer(item["configFileInfo"]), + testScriptFileInfo: !item["testScriptFileInfo"] + ? item["testScriptFileInfo"] + : testFileInfoDeserializer(item["testScriptFileInfo"]), + userPropFileInfo: !item["userPropFileInfo"] + ? item["userPropFileInfo"] + : testFileInfoDeserializer(item["userPropFileInfo"]), + inputArtifactsZipFileInfo: !item["inputArtifactsZipFileInfo"] + ? item["inputArtifactsZipFileInfo"] + : testFileInfoDeserializer(item["inputArtifactsZipFileInfo"]), + urlTestConfigFileInfo: !item["urlTestConfigFileInfo"] + ? item["urlTestConfigFileInfo"] + : testFileInfoDeserializer(item["urlTestConfigFileInfo"]), + additionalFileInfo: !item["additionalFileInfo"] + ? item["additionalFileInfo"] + : testFileInfoArrayDeserializer(item["additionalFileInfo"]), + }; +} + +/** Test file info. */ +export interface TestFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; +} + +export function testFileInfoDeserializer(item: any): TestFileInfo { + return { + fileName: item["fileName"], + url: item["url"], + fileType: item["fileType"], + expireDateTime: !item["expireDateTime"] + ? item["expireDateTime"] + : new Date(item["expireDateTime"]), + validationStatus: item["validationStatus"], + validationFailureDetails: item["validationFailureDetails"], + }; +} + +/** Types of file supported. */ +export enum KnownFileType { + /** If the file is a JMX script. */ + JMX_FILE = "JMX_FILE", + /** If the file is a user properties file. */ + USER_PROPERTIES = "USER_PROPERTIES", + /** If the file is not among any of the other supported file types. */ + ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", + /** If the file is a compressed archive containing a collection of various artifacts or resources. */ + ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", + /** If the file is a JSON config file to define the requests for a URL test. */ + URL_TEST_CONFIG = "URL_TEST_CONFIG", + /** If the file is a test script. */ + TEST_SCRIPT = "TEST_SCRIPT", +} + +/** + * Types of file supported. \ + * {@link KnownFileType} can be used interchangeably with FileType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **JMX_FILE**: If the file is a JMX script. \ + * **USER_PROPERTIES**: If the file is a user properties file. \ + * **ADDITIONAL_ARTIFACTS**: If the file is not among any of the other supported file types. \ + * **ZIPPED_ARTIFACTS**: If the file is a compressed archive containing a collection of various artifacts or resources. \ + * **URL_TEST_CONFIG**: If the file is a JSON config file to define the requests for a URL test. \ + * **TEST_SCRIPT**: If the file is a test script. + */ +export type FileType = string; + +/** File status. */ +export enum KnownFileStatus { + /** File is not validated. */ + NOT_VALIDATED = "NOT_VALIDATED", + /** File is validated. */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** File validation is failed. */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", + /** File validation is in progress. */ + VALIDATION_INITIATED = "VALIDATION_INITIATED", + /** Validation is not required. */ + VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", +} + +/** + * File status. \ + * {@link KnownFileStatus} can be used interchangeably with FileStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NOT_VALIDATED**: File is not validated. \ + * **VALIDATION_SUCCESS**: File is validated. \ + * **VALIDATION_FAILURE**: File validation is failed. \ + * **VALIDATION_INITIATED**: File validation is in progress. \ + * **VALIDATION_NOT_REQUIRED**: Validation is not required. + */ +export type FileStatus = string; + +export function testFileInfoArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return testFileInfoDeserializer(item); + }); +} + +/** Test kind */ +export enum KnownTestKind { + /** URL Test */ + URL = "URL", + /** JMX Test */ + JMX = "JMX", + /** Locust Test */ + Locust = "Locust", +} + +/** + * Test kind \ + * {@link KnownTestKind} can be used interchangeably with TestKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **URL**: URL Test \ + * **JMX**: JMX Test \ + * **Locust**: Locust Test + */ +export type TestKind = string; + +/** Test app components */ +export interface TestAppComponents { + /** + * Azure resource collection { resource id (fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) + * : resource object } + */ + components: Record; + /** Test identifier */ + readonly testId?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testAppComponentsSerializer(item: TestAppComponents): any { + return { components: appComponentRecordSerializer(item["components"]) }; +} + +export function testAppComponentsDeserializer(item: any): TestAppComponents { + return { + components: appComponentRecordDeserializer(item["components"]), + testId: item["testId"], + createdDateTime: !item["createdDateTime"] + ? item["createdDateTime"] + : new Date(item["createdDateTime"]), + createdBy: item["createdBy"], + lastModifiedDateTime: !item["lastModifiedDateTime"] + ? item["lastModifiedDateTime"] + : new Date(item["lastModifiedDateTime"]), + lastModifiedBy: item["lastModifiedBy"], + }; +} + +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ +export interface AppComponent { + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; + /** Azure resource name, required while creating the app component. */ + resourceName: string; + /** Azure resource type, required while creating the app component. */ + resourceType: string; + /** Azure resource display name */ + displayName?: string; + /** Resource group name of the Azure resource */ + readonly resourceGroup?: string; + /** Subscription Id of the Azure resource */ + readonly subscriptionId?: string; + /** Kind of Azure resource type */ + kind?: string; +} + +export function appComponentSerializer(item: AppComponent): any { + return { + resourceName: item["resourceName"], + resourceType: item["resourceType"], + displayName: item["displayName"], + kind: item["kind"], + }; +} + +export function appComponentDeserializer(item: any): AppComponent { + return { + resourceId: item["resourceId"], + resourceName: item["resourceName"], + resourceType: item["resourceType"], + displayName: item["displayName"], + resourceGroup: item["resourceGroup"], + subscriptionId: item["subscriptionId"], + kind: item["kind"], + }; +} + +export function appComponentRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] ? item[key] : appComponentSerializer(item[key]); + }); + return result; +} + +export function appComponentRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] ? item[key] : appComponentDeserializer(item[key]); + }); + return result; +} + +/** Test server metrics configuration */ +export interface TestServerMetricConfig { + /** Test identifier */ + readonly testId?: string; + /** + * Azure resource metrics collection {metric id : metrics object} (Refer : + * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition + * for metric id). + */ + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testServerMetricConfigSerializer( + item: TestServerMetricConfig, +): any { + return { metrics: resourceMetricRecordSerializer(item["metrics"]) }; +} + +export function testServerMetricConfigDeserializer( + item: any, +): TestServerMetricConfig { + return { + testId: item["testId"], + metrics: resourceMetricRecordDeserializer(item["metrics"]), + createdDateTime: !item["createdDateTime"] + ? item["createdDateTime"] + : new Date(item["createdDateTime"]), + createdBy: item["createdBy"], + lastModifiedDateTime: !item["lastModifiedDateTime"] + ? item["lastModifiedDateTime"] + : new Date(item["lastModifiedDateTime"]), + lastModifiedBy: item["lastModifiedBy"], + }; +} + +/** + * Associated metric definition for particular metrics of the azure resource ( + * Refer : + * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition). + */ +export interface ResourceMetric { + /** Unique name for metric. */ + readonly id?: string; + /** Azure resource id. */ + resourceId: string; + /** Metric name space. */ + metricNamespace: string; + /** Metric description. */ + displayDescription?: string; + /** The invariant value of metric name */ + name: string; + /** Metric aggregation. */ + aggregation: string; + /** Metric unit. */ + unit?: string; + /** Azure resource type. */ + resourceType: string; +} + +export function resourceMetricSerializer(item: ResourceMetric): any { + return { + resourceId: item["resourceId"], + metricNamespace: item["metricNamespace"], + displayDescription: item["displayDescription"], + name: item["name"], + aggregation: item["aggregation"], + unit: item["unit"], + resourceType: item["resourceType"], + }; +} + +export function resourceMetricDeserializer(item: any): ResourceMetric { + return { + id: item["id"], + resourceId: item["resourceId"], + metricNamespace: item["metricNamespace"], + displayDescription: item["displayDescription"], + name: item["name"], + aggregation: item["aggregation"], + unit: item["unit"], + resourceType: item["resourceType"], + }; +} + +export function resourceMetricRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] ? item[key] : resourceMetricSerializer(item[key]); + }); + return result; +} + +export function resourceMetricRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : resourceMetricDeserializer(item[key]); + }); + return result; +} + +/** Load test run model */ +export interface TestRun { + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testRunId: string; + /** Pass fail criteria for a test. */ + passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; + /** + * Secrets can be stored in an Azure Key Vault or any other secret store. If the + * secret is stored in an Azure Key Vault, the value should be the secret + * identifier and the type should be AKV_SECRET_URI. If the secret is stored + * elsewhere, the secret value should be provided directly and the type should be + * SECRET_VALUE. + */ + secrets?: Record; + /** Certificates metadata */ + certificate?: CertificateMetadata; + /** Environment variables which are defined as a set of pairs. */ + environmentVariables?: Record; + /** Error details if there is any failure in load test run */ + readonly errorDetails?: ErrorDetails[]; + /** + * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. + * The sampler name is the same as the name mentioned in the test script. + * Sampler name "Total" represents the aggregated statistics of all the samplers. + */ + readonly testRunStatistics?: Record; + /** + * Regional statistics. Key is the Azure region name and value is the test run statistics. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + readonly regionalStatistics?: Record; + /** The load test configuration. */ + loadTestConfiguration?: LoadTestConfiguration; + /** Collection of test run artifacts */ + readonly testArtifacts?: TestRunArtifacts; + /** Test result for pass/Fail criteria used during the test run. */ + readonly testResult?: PFTestResult; + /** Number of virtual users, for which test has been run. */ + readonly virtualUsers?: number; + /** Display name of a testRun. */ + displayName?: string; + /** Associated test Id. */ + testId?: string; + /** The test run description. */ + description?: string; + /** The test run status. */ + readonly status?: Status; + /** The test run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; + /** Test run initiated time. */ + readonly executedDateTime?: Date; + /** Portal url. */ + readonly portalUrl?: string; + /** Test run duration in milliseconds. */ + readonly duration?: number; + /** Subnet ID on which the load test instances should run. */ + readonly subnetId?: string; + /** Type of test. */ + readonly kind?: TestKind; + /** Request data collection level for test run */ + requestDataLevel?: RequestDataLevel; + /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ + debugLogsEnabled?: boolean; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testRunSerializer(item: TestRun): any { + return { + passFailCriteria: !item["passFailCriteria"] + ? item["passFailCriteria"] + : passFailCriteriaSerializer(item["passFailCriteria"]), + autoStopCriteria: !item["autoStopCriteria"] + ? item["autoStopCriteria"] + : autoStopCriteriaSerializer(item["autoStopCriteria"]), + secrets: !item["secrets"] + ? item["secrets"] + : secretRecordSerializer(item["secrets"]), + certificate: !item["certificate"] + ? item["certificate"] + : certificateMetadataSerializer(item["certificate"]), + environmentVariables: item["environmentVariables"], + loadTestConfiguration: !item["loadTestConfiguration"] + ? item["loadTestConfiguration"] + : loadTestConfigurationSerializer(item["loadTestConfiguration"]), + displayName: item["displayName"], + testId: item["testId"], + description: item["description"], + requestDataLevel: item["requestDataLevel"], + debugLogsEnabled: item["debugLogsEnabled"], + }; +} + +export function testRunDeserializer(item: any): TestRun { + return { + testRunId: item["testRunId"], + passFailCriteria: !item["passFailCriteria"] + ? item["passFailCriteria"] + : passFailCriteriaDeserializer(item["passFailCriteria"]), + autoStopCriteria: !item["autoStopCriteria"] + ? item["autoStopCriteria"] + : autoStopCriteriaDeserializer(item["autoStopCriteria"]), + secrets: !item["secrets"] + ? item["secrets"] + : secretRecordDeserializer(item["secrets"]), + certificate: !item["certificate"] + ? item["certificate"] + : certificateMetadataDeserializer(item["certificate"]), + environmentVariables: item["environmentVariables"], + errorDetails: !item["errorDetails"] + ? item["errorDetails"] + : errorDetailsArrayDeserializer(item["errorDetails"]), + testRunStatistics: !item["testRunStatistics"] + ? item["testRunStatistics"] + : testRunStatisticsRecordDeserializer(item["testRunStatistics"]), + regionalStatistics: !item["regionalStatistics"] + ? item["regionalStatistics"] + : testRunStatisticsRecordDeserializer(item["regionalStatistics"]), + loadTestConfiguration: !item["loadTestConfiguration"] + ? item["loadTestConfiguration"] + : loadTestConfigurationDeserializer(item["loadTestConfiguration"]), + testArtifacts: !item["testArtifacts"] + ? item["testArtifacts"] + : testRunArtifactsDeserializer(item["testArtifacts"]), + testResult: item["testResult"], + virtualUsers: item["virtualUsers"], + displayName: item["displayName"], + testId: item["testId"], + description: item["description"], + status: item["status"], + startDateTime: !item["startDateTime"] + ? item["startDateTime"] + : new Date(item["startDateTime"]), + endDateTime: !item["endDateTime"] + ? item["endDateTime"] + : new Date(item["endDateTime"]), + executedDateTime: !item["executedDateTime"] + ? item["executedDateTime"] + : new Date(item["executedDateTime"]), + portalUrl: item["portalUrl"], + duration: item["duration"], + subnetId: item["subnetId"], + kind: item["kind"], + requestDataLevel: item["requestDataLevel"], + debugLogsEnabled: item["debugLogsEnabled"], + publicIPDisabled: item["publicIPDisabled"], + createdDateTime: !item["createdDateTime"] + ? item["createdDateTime"] + : new Date(item["createdDateTime"]), + createdBy: item["createdBy"], + lastModifiedDateTime: !item["lastModifiedDateTime"] + ? item["lastModifiedDateTime"] + : new Date(item["lastModifiedDateTime"]), + lastModifiedBy: item["lastModifiedBy"], + }; +} + +/** Error details if there is any failure in load test run */ +export interface ErrorDetails { + /** Error details in case test run was not successfully run. */ + readonly message?: string; +} + +export function errorDetailsDeserializer(item: any): ErrorDetails { + return { + message: item["message"], + }; +} + +export function errorDetailsArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return errorDetailsDeserializer(item); + }); +} + +/** Test run statistics. */ +export interface TestRunStatistics { + /** Transaction name. */ + readonly transaction?: string; + /** Sampler count. */ + readonly sampleCount?: number; + /** Error count. */ + readonly errorCount?: number; + /** Error percentage. */ + readonly errorPct?: number; + /** Mean response time. */ + readonly meanResTime?: number; + /** Median response time. */ + readonly medianResTime?: number; + /** Max response time. */ + readonly maxResTime?: number; + /** Minimum response time. */ + readonly minResTime?: number; + /** 90 percentile response time. */ + readonly pct1ResTime?: number; + /** 95 percentile response time. */ + readonly pct2ResTime?: number; + /** 99 percentile response time. */ + readonly pct3ResTime?: number; + /** 75 percentile response time. */ + readonly pct75ResTime?: number; + /** 96 percentile response time. */ + readonly pct96ResTime?: number; + /** 97 percentile response time. */ + readonly pct97ResTime?: number; + /** 98 percentile response time. */ + readonly pct98ResTime?: number; + /** 99.9 percentile response time. */ + readonly pct999ResTime?: number; + /** 99.99 percentile response time. */ + readonly pct9999ResTime?: number; + /** Throughput. */ + readonly throughput?: number; + /** Received network bytes. */ + readonly receivedKBytesPerSec?: number; + /** Send network bytes. */ + readonly sentKBytesPerSec?: number; +} + +export function testRunStatisticsDeserializer(item: any): TestRunStatistics { + return { + transaction: item["transaction"], + sampleCount: item["sampleCount"], + errorCount: item["errorCount"], + errorPct: item["errorPct"], + meanResTime: item["meanResTime"], + medianResTime: item["medianResTime"], + maxResTime: item["maxResTime"], + minResTime: item["minResTime"], + pct1ResTime: item["pct1ResTime"], + pct2ResTime: item["pct2ResTime"], + pct3ResTime: item["pct3ResTime"], + pct75ResTime: item["pct75ResTime"], + pct96ResTime: item["pct96ResTime"], + pct97ResTime: item["pct97ResTime"], + pct98ResTime: item["pct98ResTime"], + pct999ResTime: item["pct999ResTime"], + pct9999ResTime: item["pct9999ResTime"], + throughput: item["throughput"], + receivedKBytesPerSec: item["receivedKBytesPerSec"], + sentKBytesPerSec: item["sentKBytesPerSec"], + }; +} + +export function testRunStatisticsRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : testRunStatisticsDeserializer(item[key]); + }); + return result; +} + +/** Collection of test run artifacts */ +export interface TestRunArtifacts { + /** The input artifacts for the test run. */ + readonly inputArtifacts?: TestRunInputArtifacts; + /** The output artifacts for the test run. */ + outputArtifacts?: TestRunOutputArtifacts; +} + +export function testRunArtifactsDeserializer(item: any): TestRunArtifacts { + return { + inputArtifacts: !item["inputArtifacts"] + ? item["inputArtifacts"] + : testRunInputArtifactsDeserializer(item["inputArtifacts"]), + outputArtifacts: !item["outputArtifacts"] + ? item["outputArtifacts"] + : testRunOutputArtifactsDeserializer(item["outputArtifacts"]), + }; +} + +/** The input artifacts for the test run. */ +export interface TestRunInputArtifacts { + /** File info */ + configFileInfo?: TestRunFileInfo; + /** File info */ + testScriptFileInfo?: TestRunFileInfo; + /** File info */ + userPropFileInfo?: TestRunFileInfo; + /** File info */ + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; + /** Additional supported files for the test run */ + readonly additionalFileInfo?: TestRunFileInfo[]; +} + +export function testRunInputArtifactsDeserializer( + item: any, +): TestRunInputArtifacts { + return { + configFileInfo: !item["configFileInfo"] + ? item["configFileInfo"] + : testRunFileInfoDeserializer(item["configFileInfo"]), + testScriptFileInfo: !item["testScriptFileInfo"] + ? item["testScriptFileInfo"] + : testRunFileInfoDeserializer(item["testScriptFileInfo"]), + userPropFileInfo: !item["userPropFileInfo"] + ? item["userPropFileInfo"] + : testRunFileInfoDeserializer(item["userPropFileInfo"]), + inputArtifactsZipFileInfo: !item["inputArtifactsZipFileInfo"] + ? item["inputArtifactsZipFileInfo"] + : testRunFileInfoDeserializer(item["inputArtifactsZipFileInfo"]), + urlTestConfigFileInfo: !item["urlTestConfigFileInfo"] + ? item["urlTestConfigFileInfo"] + : testRunFileInfoDeserializer(item["urlTestConfigFileInfo"]), + additionalFileInfo: !item["additionalFileInfo"] + ? item["additionalFileInfo"] + : testRunFileInfoArrayDeserializer(item["additionalFileInfo"]), + }; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; +} + +export function testRunFileInfoDeserializer(item: any): TestRunFileInfo { + return { + fileName: item["fileName"], + url: item["url"], + fileType: item["fileType"], + expireDateTime: !item["expireDateTime"] + ? item["expireDateTime"] + : new Date(item["expireDateTime"]), + validationStatus: item["validationStatus"], + validationFailureDetails: item["validationFailureDetails"], + }; +} + +export function testRunFileInfoArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return testRunFileInfoDeserializer(item); + }); +} + +/** The output artifacts for the test run. */ +export interface TestRunOutputArtifacts { + /** File info */ + resultFileInfo?: TestRunFileInfo; + /** File info */ + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; + /** The report file for the test run. */ + reportFileInfo?: TestRunFileInfo; +} + +export function testRunOutputArtifactsDeserializer( + item: any, +): TestRunOutputArtifacts { + return { + resultFileInfo: !item["resultFileInfo"] + ? item["resultFileInfo"] + : testRunFileInfoDeserializer(item["resultFileInfo"]), + logsFileInfo: !item["logsFileInfo"] + ? item["logsFileInfo"] + : testRunFileInfoDeserializer(item["logsFileInfo"]), + artifactsContainerInfo: !item["artifactsContainerInfo"] + ? item["artifactsContainerInfo"] + : artifactsContainerInfoDeserializer(item["artifactsContainerInfo"]), + reportFileInfo: !item["reportFileInfo"] + ? item["reportFileInfo"] + : testRunFileInfoDeserializer(item["reportFileInfo"]), + }; +} + +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date; +} + +export function artifactsContainerInfoDeserializer( + item: any, +): ArtifactsContainerInfo { + return { + url: item["url"], + expireDateTime: !item["expireDateTime"] + ? item["expireDateTime"] + : new Date(item["expireDateTime"]), + }; +} + +/** Test result based on pass/fail criteria. */ +export enum KnownPFTestResult { + /** Pass/fail criteria has passed. */ + PASSED = "PASSED", + /** Pass/fail criteria is not applicable. */ + NOT_APPLICABLE = "NOT_APPLICABLE", + /** Pass/fail criteria has failed. */ + FAILED = "FAILED", +} + +/** + * Test result based on pass/fail criteria. \ + * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PASSED**: Pass\/fail criteria has passed. \ + * **NOT_APPLICABLE**: Pass\/fail criteria is not applicable. \ + * **FAILED**: Pass\/fail criteria has failed. + */ +export type PFTestResult = string; + +/** Test run status. */ +export enum KnownStatus { + /** Test run request is accepted. */ + ACCEPTED = "ACCEPTED", + /** Test run is not yet started. */ + NOTSTARTED = "NOTSTARTED", + /** Test run is provisioning. */ + PROVISIONING = "PROVISIONING", + /** Test run is provisioned. */ + PROVISIONED = "PROVISIONED", + /** Test run is getting configured. */ + CONFIGURING = "CONFIGURING", + /** Test run configuration is done. */ + CONFIGURED = "CONFIGURED", + /** Test run has started executing. */ + EXECUTING = "EXECUTING", + /** Test run execution is completed. */ + EXECUTED = "EXECUTED", + /** Test run is getting deprovisioned. */ + DEPROVISIONING = "DEPROVISIONING", + /** Test run is deprovisioned. */ + DEPROVISIONED = "DEPROVISIONED", + /** Test run is completed. */ + DONE = "DONE", + /** Test run is being cancelled. */ + CANCELLING = "CANCELLING", + /** Test run request is cancelled. */ + CANCELLED = "CANCELLED", + /** Test run request is failed. */ + FAILED = "FAILED", + /** Test run JMX file is validated. */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** Test run JMX file validation is failed. */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", +} + +/** + * Test run status. \ + * {@link KnownStatus} can be used interchangeably with Status, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED**: Test run request is accepted. \ + * **NOTSTARTED**: Test run is not yet started. \ + * **PROVISIONING**: Test run is provisioning. \ + * **PROVISIONED**: Test run is provisioned. \ + * **CONFIGURING**: Test run is getting configured. \ + * **CONFIGURED**: Test run configuration is done. \ + * **EXECUTING**: Test run has started executing. \ + * **EXECUTED**: Test run execution is completed. \ + * **DEPROVISIONING**: Test run is getting deprovisioned. \ + * **DEPROVISIONED**: Test run is deprovisioned. \ + * **DONE**: Test run is completed. \ + * **CANCELLING**: Test run is being cancelled. \ + * **CANCELLED**: Test run request is cancelled. \ + * **FAILED**: Test run request is failed. \ + * **VALIDATION_SUCCESS**: Test run JMX file is validated. \ + * **VALIDATION_FAILURE**: Test run JMX file validation is failed. + */ +export type Status = string; + +/** Request data collection level for test run */ +export enum KnownRequestDataLevel { + /** No request data will be collected */ + NONE = "NONE", + /** Request data will be collected in case of failed requests */ + ERRORS = "ERRORS", +} + +/** + * Request data collection level for test run \ + * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NONE**: No request data will be collected \ + * **ERRORS**: Request data will be collected in case of failed requests + */ +export type RequestDataLevel = string; + +/** Test run app component */ +export interface TestRunAppComponents { + /** + * Azure resource collection { resource id (fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) + * : resource object } + */ + components: Record; + /** Test run identifier */ + readonly testRunId?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testRunAppComponentsSerializer( + item: TestRunAppComponents, +): any { + return { components: appComponentRecordSerializer(item["components"]) }; +} + +export function testRunAppComponentsDeserializer( + item: any, +): TestRunAppComponents { + return { + components: appComponentRecordDeserializer(item["components"]), + testRunId: item["testRunId"], + createdDateTime: !item["createdDateTime"] + ? item["createdDateTime"] + : new Date(item["createdDateTime"]), + createdBy: item["createdBy"], + lastModifiedDateTime: !item["lastModifiedDateTime"] + ? item["lastModifiedDateTime"] + : new Date(item["lastModifiedDateTime"]), + lastModifiedBy: item["lastModifiedBy"], + }; +} + +/** Test run server metrics configuration */ +export interface TestRunServerMetricConfig { + /** Test run identifier */ + readonly testRunId?: string; + /** + * Azure resource metrics collection {metric id : metrics object} (Refer : + * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition + * for metric id). + */ + metrics?: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testRunServerMetricConfigSerializer( + item: TestRunServerMetricConfig, +): any { + return { + metrics: !item["metrics"] + ? item["metrics"] + : resourceMetricRecordSerializer(item["metrics"]), + }; +} + +export function testRunServerMetricConfigDeserializer( + item: any, +): TestRunServerMetricConfig { + return { + testRunId: item["testRunId"], + metrics: !item["metrics"] + ? item["metrics"] + : resourceMetricRecordDeserializer(item["metrics"]), + createdDateTime: !item["createdDateTime"] + ? item["createdDateTime"] + : new Date(item["createdDateTime"]), + createdBy: item["createdBy"], + lastModifiedDateTime: !item["lastModifiedDateTime"] + ? item["lastModifiedDateTime"] + : new Date(item["lastModifiedDateTime"]), + lastModifiedBy: item["lastModifiedBy"], + }; +} + +/** Metrics dimension values. */ +export interface DimensionValueList { + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; +} + +export function dimensionValueListDeserializer(item: any): DimensionValueList { + return { + name: item["name"], + value: !item["value"] + ? item["value"] + : item["value"].map((p: any) => { + return p; + }), + nextLink: item["nextLink"], + }; +} + +/** Represents collection of metric definitions. */ +export interface MetricDefinitionCollection { + /** the values for the metric definitions. */ + value: MetricDefinition[]; +} + +export function metricDefinitionCollectionDeserializer( + item: any, +): MetricDefinitionCollection { + return { + value: metricDefinitionArrayDeserializer(item["value"]), + }; +} + +/** Metric definition */ +export interface MetricDefinition { + /** List of dimensions */ + dimensions?: NameAndDesc[]; + /** The metric description */ + description?: string; + /** The metric name */ + name?: string; + /** The namespace the metric belongs to. */ + namespace?: string; + /** The primary aggregation type value defining how to use the values for display. */ + primaryAggregationType?: AggregationType; + /** The collection of what all aggregation types are supported. */ + supportedAggregationTypes?: string[]; + /** The unit of the metric. */ + unit?: MetricUnit; + /** + * Metric availability specifies the time grain (aggregation interval or + * frequency). + */ + metricAvailabilities?: MetricAvailability[]; +} + +export function metricDefinitionDeserializer(item: any): MetricDefinition { + return { + dimensions: !item["dimensions"] + ? item["dimensions"] + : nameAndDescArrayDeserializer(item["dimensions"]), + description: item["description"], + name: item["name"], + namespace: item["namespace"], + primaryAggregationType: item["primaryAggregationType"], + supportedAggregationTypes: !item["supportedAggregationTypes"] + ? item["supportedAggregationTypes"] + : item["supportedAggregationTypes"].map((p: any) => { + return p; + }), + unit: item["unit"], + metricAvailabilities: !item["metricAvailabilities"] + ? item["metricAvailabilities"] + : metricAvailabilityArrayDeserializer(item["metricAvailabilities"]), + }; +} + +/** The name and description */ +export interface NameAndDesc { + /** The description */ + description?: string; + /** The name */ + name?: string; +} + +export function nameAndDescDeserializer(item: any): NameAndDesc { + return { + description: item["description"], + name: item["name"], + }; +} + +export function nameAndDescArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return nameAndDescDeserializer(item); + }); +} + +/** Aggregation type. */ +export enum KnownAggregationType { + /** Average value. */ + Average = "Average", + /** Total count. */ + Count = "Count", + /** Aggregation will be average in this case. */ + None = "None", + /** Total sum. */ + Total = "Total", + /** 75th percentile. */ + Percentile75 = "Percentile75", + /** 90th percentile. */ + Percentile90 = "Percentile90", + /** 95th percentile. */ + Percentile95 = "Percentile95", + /** 96th percentile. */ + Percentile96 = "Percentile96", + /** 97th percentile. */ + Percentile97 = "Percentile97", + /** 98th percentile. */ + Percentile98 = "Percentile98", + /** 99th percentile. */ + Percentile99 = "Percentile99", + /** 99.9th percentile. */ + Percentile999 = "Percentile999", + /** 99.99th percentile. */ + Percentile9999 = "Percentile9999", +} + +/** + * Aggregation type. \ + * {@link KnownAggregationType} can be used interchangeably with AggregationType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Average**: Average value. \ + * **Count**: Total count. \ + * **None**: Aggregation will be average in this case. \ + * **Total**: Total sum. \ + * **Percentile75**: 75th percentile. \ + * **Percentile90**: 90th percentile. \ + * **Percentile95**: 95th percentile. \ + * **Percentile96**: 96th percentile. \ + * **Percentile97**: 97th percentile. \ + * **Percentile98**: 98th percentile. \ + * **Percentile99**: 99th percentile. \ + * **Percentile999**: 99.9th percentile. \ + * **Percentile9999**: 99.99th percentile. + */ +export type AggregationType = string; + +/** Metric unit. */ +export enum KnownMetricUnit { + /** No unit specified. */ + NotSpecified = "NotSpecified", + /** Percentage. */ + Percent = "Percent", + /** Value count. */ + Count = "Count", + /** Seconds. */ + Seconds = "Seconds", + /** Milliseconds */ + Milliseconds = "Milliseconds", + /** Bytes */ + Bytes = "Bytes", + /** Bytes per second */ + BytesPerSecond = "BytesPerSecond", + /** Count per second */ + CountPerSecond = "CountPerSecond", +} + +/** + * Metric unit. \ + * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NotSpecified**: No unit specified. \ + * **Percent**: Percentage. \ + * **Count**: Value count. \ + * **Seconds**: Seconds. \ + * **Milliseconds**: Milliseconds \ + * **Bytes**: Bytes \ + * **BytesPerSecond**: Bytes per second \ + * **CountPerSecond**: Count per second + */ +export type MetricUnit = string; + +/** Metric availability specifies the time grain (aggregation interval or frequency) */ +export interface MetricAvailability { + /** + * The time grain specifies the aggregation interval for the metric. Expressed as + * a duration 'PT1M', 'PT1H', etc. + */ + timeGrain?: TimeGrain; +} + +export function metricAvailabilityDeserializer(item: any): MetricAvailability { + return { + timeGrain: item["timeGrain"], + }; +} + +/** Time Grain */ +export enum KnownTimeGrain { + /** 5 seconds, available only if test run duration is less than 10 minutes. */ + PT5S = "PT5S", + /** 10 seconds, available only if test run duration is less than 10 minutes. */ + PT10S = "PT10S", + /** 1 minute */ + PT1M = "PT1M", + /** 5 minutes, available only if test run duration is greater than 1 minute. */ + PT5M = "PT5M", + /** 1 hour, available only if test run duration is greater than 1 minute. */ + PT1H = "PT1H", +} + +/** + * Time Grain \ + * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PT5S**: 5 seconds, available only if test run duration is less than 10 minutes. \ + * **PT10S**: 10 seconds, available only if test run duration is less than 10 minutes. \ + * **PT1M**: 1 minute \ + * **PT5M**: 5 minutes, available only if test run duration is greater than 1 minute. \ + * **PT1H**: 1 hour, available only if test run duration is greater than 1 minute. + */ +export type TimeGrain = string; + +export function metricAvailabilityArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return metricAvailabilityDeserializer(item); + }); +} + +export function metricDefinitionArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return metricDefinitionDeserializer(item); + }); +} + +/** Represents collection of metric namespaces. */ +export interface MetricNamespaceCollection { + /** The values for the metric namespaces. */ + value: MetricNamespace[]; +} + +export function metricNamespaceCollectionDeserializer( + item: any, +): MetricNamespaceCollection { + return { + value: metricNamespaceArrayDeserializer(item["value"]), + }; +} + +/** Metric namespace class specifies the metadata for a metric namespace. */ +export interface MetricNamespace { + /** The namespace description. */ + description?: string; + /** The metric namespace name. */ + name?: string; +} + +export function metricNamespaceDeserializer(item: any): MetricNamespace { + return { + description: item["description"], + name: item["name"], + }; +} + +export function metricNamespaceArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return metricNamespaceDeserializer(item); + }); +} + +/** Filters to fetch the set of metric. */ +export interface MetricRequestPayload { + /** + * Get metrics for specific dimension values. Example: Metric contains dimension + * like SamplerName, Error. To retrieve all the time series data where SamplerName + * is equals to HTTPRequest1 or HTTPRequest2, the DimensionFilter value will be + * {"SamplerName", ["HTTPRequest1", "HTTPRequest2"} + */ + filters?: DimensionFilter[]; +} + +export function metricRequestPayloadSerializer( + item: MetricRequestPayload, +): any { + return { + filters: !item["filters"] + ? item["filters"] + : dimensionFilterArraySerializer(item["filters"]), + }; +} + +/** Dimension name and values to filter */ +export interface DimensionFilter { + /** The dimension name */ + name?: string; + /** The dimension values. Maximum values can be 20. */ + values?: string[]; +} + +export function dimensionFilterSerializer(item: DimensionFilter): any { + return { + name: item["name"], + values: !item["values"] + ? item["values"] + : item["values"].map((p: any) => { + return p; + }), + }; +} + +export function dimensionFilterArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return dimensionFilterSerializer(item); + }); +} + +/** The response to a metrics query. */ +export interface _Metrics { + /** The TimeSeriesElement items on this page */ + value: TimeSeriesElement[]; + /** The link to the next page of items */ + nextLink?: string; +} + +export function _metricsDeserializer(item: any): _Metrics { + return { + value: timeSeriesElementArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +/** The time series returned when a data query is performed. */ +export interface TimeSeriesElement { + /** An array of data points representing the metric values. */ + data?: MetricValue[]; + /** The dimension values */ + dimensionValues?: DimensionValue[]; +} + +export function timeSeriesElementDeserializer(item: any): TimeSeriesElement { + return { + data: !item["data"] + ? item["data"] + : metricValueArrayDeserializer(item["data"]), + dimensionValues: !item["dimensionValues"] + ? item["dimensionValues"] + : dimensionValueArrayDeserializer(item["dimensionValues"]), + }; +} + +/** Represents a metric value. */ +export interface MetricValue { + /** The timestamp for the metric value in RFC 3339 format. */ + timestamp?: Date; + /** The metric value. */ + value?: number; +} + +export function metricValueDeserializer(item: any): MetricValue { + return { + timestamp: !item["timestamp"] + ? item["timestamp"] + : new Date(item["timestamp"]), + value: item["value"], + }; +} + +export function metricValueArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return metricValueDeserializer(item); + }); +} + +/** Represents a metric dimension value. */ +export interface DimensionValue { + /** The name of the dimension. */ + name?: string; + /** The value of the dimension. */ + value?: string; +} + +export function dimensionValueDeserializer(item: any): DimensionValue { + return { + name: item["name"], + value: item["value"], + }; +} + +export function dimensionValueArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return dimensionValueDeserializer(item); + }); +} + +export function timeSeriesElementArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return timeSeriesElementDeserializer(item); + }); +} + +/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ +export interface TestProfile { + /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileId: string; + /** Display name of the test profile. */ + displayName?: string; + /** Description for the test profile. */ + description?: string; + /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ + testId?: string; + /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ + targetResourceId?: string; + /** Configurations of the target resource on which testing would be done. */ + targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileSerializer(item: TestProfile): any { + return { + displayName: item["displayName"], + description: item["description"], + testId: item["testId"], + targetResourceId: item["targetResourceId"], + targetResourceConfigurations: !item["targetResourceConfigurations"] + ? item["targetResourceConfigurations"] + : targetResourceConfigurationsUnionSerializer( + item["targetResourceConfigurations"], + ), + }; +} + +export function testProfileDeserializer(item: any): TestProfile { + return { + testProfileId: item["testProfileId"], + displayName: item["displayName"], + description: item["description"], + testId: item["testId"], + targetResourceId: item["targetResourceId"], + targetResourceConfigurations: !item["targetResourceConfigurations"] + ? item["targetResourceConfigurations"] + : targetResourceConfigurationsUnionDeserializer( + item["targetResourceConfigurations"], + ), + createdDateTime: !item["createdDateTime"] + ? item["createdDateTime"] + : new Date(item["createdDateTime"]), + createdBy: item["createdBy"], + lastModifiedDateTime: !item["lastModifiedDateTime"] + ? item["lastModifiedDateTime"] + : new Date(item["lastModifiedDateTime"]), + lastModifiedBy: item["lastModifiedBy"], + }; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export interface TargetResourceConfigurations { + /** Kind of the resource for which the configurations apply. */ + /** The discriminator possible values: FunctionsFlexConsumption */ + kind: ResourceKind; +} + +export function targetResourceConfigurationsSerializer( + item: TargetResourceConfigurations, +): any { + return { kind: item["kind"] }; +} + +export function targetResourceConfigurationsDeserializer( + item: any, +): TargetResourceConfigurations { + return { + kind: item["kind"], + }; +} + +/** Alias for TargetResourceConfigurationsUnion */ +export type TargetResourceConfigurationsUnion = + | FunctionFlexConsumptionTargetResourceConfigurations + | TargetResourceConfigurations; + +export function targetResourceConfigurationsUnionSerializer( + item: TargetResourceConfigurationsUnion, +): any { + switch (item.kind) { + case "FunctionsFlexConsumption": + return functionFlexConsumptionTargetResourceConfigurationsSerializer( + item as FunctionFlexConsumptionTargetResourceConfigurations, + ); + + default: + return targetResourceConfigurationsSerializer(item); + } +} + +export function targetResourceConfigurationsUnionDeserializer( + item: any, +): TargetResourceConfigurationsUnion { + switch (item.kind) { + case "FunctionsFlexConsumption": + return functionFlexConsumptionTargetResourceConfigurationsDeserializer( + item as FunctionFlexConsumptionTargetResourceConfigurations, + ); + + default: + return targetResourceConfigurationsDeserializer(item); + } +} + +/** Kind of the resource on which test profile is created. */ +export enum KnownResourceKind { + /** Resource is a Azure FunctionApp on Flex Consumption Plan. */ + FunctionsFlexConsumption = "FunctionsFlexConsumption", +} + +/** + * Kind of the resource on which test profile is created. \ + * {@link KnownResourceKind} can be used interchangeably with ResourceKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **FunctionsFlexConsumption**: Resource is a Azure FunctionApp on Flex Consumption Plan. + */ +export type ResourceKind = string; + +/** Configurations for a Function App using Flex Consumption Plan. */ +export interface FunctionFlexConsumptionTargetResourceConfigurations + extends TargetResourceConfigurations { + /** + * The kind value to use when providing configuration. + * This should typically be not changed from its value. + */ + kind: "FunctionsFlexConsumption"; + /** A map of configurations for a Function app using Flex Consumption Plan. */ + configurations?: Record; +} + +export function functionFlexConsumptionTargetResourceConfigurationsSerializer( + item: FunctionFlexConsumptionTargetResourceConfigurations, +): any { + return { + kind: item["kind"], + configurations: !item["configurations"] + ? item["configurations"] + : functionFlexConsumptionResourceConfigurationRecordSerializer( + item["configurations"], + ), + }; +} + +export function functionFlexConsumptionTargetResourceConfigurationsDeserializer( + item: any, +): FunctionFlexConsumptionTargetResourceConfigurations { + return { + kind: item["kind"], + configurations: !item["configurations"] + ? item["configurations"] + : functionFlexConsumptionResourceConfigurationRecordDeserializer( + item["configurations"], + ), + }; +} + +/** Resource configuration instance for a Flex Consumption based Azure Function App. */ +export interface FunctionFlexConsumptionResourceConfiguration { + /** Memory size of the instance. Supported values are 2048, 4096. */ + instanceMemoryMB: number; + /** HTTP Concurrency for the function app. */ + httpConcurrency: number; +} + +export function functionFlexConsumptionResourceConfigurationSerializer( + item: FunctionFlexConsumptionResourceConfiguration, +): any { + return { + instanceMemoryMB: item["instanceMemoryMB"], + httpConcurrency: item["httpConcurrency"], + }; +} + +export function functionFlexConsumptionResourceConfigurationDeserializer( + item: any, +): FunctionFlexConsumptionResourceConfiguration { + return { + instanceMemoryMB: item["instanceMemoryMB"], + httpConcurrency: item["httpConcurrency"], + }; +} + +export function functionFlexConsumptionResourceConfigurationRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : functionFlexConsumptionResourceConfigurationSerializer(item[key]); + }); + return result; +} + +export function functionFlexConsumptionResourceConfigurationRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : functionFlexConsumptionResourceConfigurationDeserializer(item[key]); + }); + return result; +} + +/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ +export interface TestProfileRun { + /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileRunId: string; + /** Display name for the test profile run. */ + displayName?: string; + /** The test profile run description */ + description?: string; + /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ + testProfileId?: string; + /** Target resource ID on which the test profile run is created */ + readonly targetResourceId?: string; + /** Configurations of the target resource on which the test profile ran. */ + readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The test profile run status. */ + readonly status?: TestProfileRunStatus; + /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ + readonly errorDetails?: ErrorDetails[]; + /** The test profile run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test profile run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; + /** Test profile run duration in seconds. */ + readonly durationInSeconds?: number; + /** + * Details of the test runs ran as part of the test profile run. + * Key is the testRunId of the corresponding testRun. + */ + readonly testRunDetails?: Record; + /** Recommendations provided based on a successful test profile run. */ + readonly recommendations?: TestProfileRunRecommendation[]; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileRunSerializer(item: TestProfileRun): any { + return { + displayName: item["displayName"], + description: item["description"], + testProfileId: item["testProfileId"], + }; +} + +export function testProfileRunDeserializer(item: any): TestProfileRun { + return { + testProfileRunId: item["testProfileRunId"], + displayName: item["displayName"], + description: item["description"], + testProfileId: item["testProfileId"], + targetResourceId: item["targetResourceId"], + targetResourceConfigurations: !item["targetResourceConfigurations"] + ? item["targetResourceConfigurations"] + : targetResourceConfigurationsUnionDeserializer( + item["targetResourceConfigurations"], + ), + status: item["status"], + errorDetails: !item["errorDetails"] + ? item["errorDetails"] + : errorDetailsArrayDeserializer(item["errorDetails"]), + startDateTime: !item["startDateTime"] + ? item["startDateTime"] + : new Date(item["startDateTime"]), + endDateTime: !item["endDateTime"] + ? item["endDateTime"] + : new Date(item["endDateTime"]), + durationInSeconds: item["durationInSeconds"], + testRunDetails: !item["testRunDetails"] + ? item["testRunDetails"] + : testRunDetailRecordDeserializer(item["testRunDetails"]), + recommendations: !item["recommendations"] + ? item["recommendations"] + : testProfileRunRecommendationArrayDeserializer(item["recommendations"]), + createdDateTime: !item["createdDateTime"] + ? item["createdDateTime"] + : new Date(item["createdDateTime"]), + createdBy: item["createdBy"], + lastModifiedDateTime: !item["lastModifiedDateTime"] + ? item["lastModifiedDateTime"] + : new Date(item["lastModifiedDateTime"]), + lastModifiedBy: item["lastModifiedBy"], + }; +} + +/** Test profile run status. */ +export enum KnownTestProfileRunStatus { + /** Test profile run request is accepted. */ + ACCEPTED = "ACCEPTED", + /** Test profile run is not yet started. */ + NOTSTARTED = "NOTSTARTED", + /** Test profile run has started executing. */ + EXECUTING = "EXECUTING", + /** Test profile run has completed successfully. */ + DONE = "DONE", + /** Test profile run is being cancelled. */ + CANCELLING = "CANCELLING", + /** Test profile run is cancelled. */ + CANCELLED = "CANCELLED", + /** Test profile run has failed. */ + FAILED = "FAILED", +} + +/** + * Test profile run status. \ + * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED**: Test profile run request is accepted. \ + * **NOTSTARTED**: Test profile run is not yet started. \ + * **EXECUTING**: Test profile run has started executing. \ + * **DONE**: Test profile run has completed successfully. \ + * **CANCELLING**: Test profile run is being cancelled. \ + * **CANCELLED**: Test profile run is cancelled. \ + * **FAILED**: Test profile run has failed. + */ +export type TestProfileRunStatus = string; + +/** Details of a particular test run for a test profile run. */ +export interface TestRunDetail { + /** Status of the test run. */ + status: Status; + /** ID of the configuration on which the test ran. */ + configurationId: string; + /** Key value pair of extra properties associated with the test run. */ + properties: Record; +} + +export function testRunDetailDeserializer(item: any): TestRunDetail { + return { + status: item["status"], + configurationId: item["configurationId"], + properties: item["properties"], + }; +} + +export function testRunDetailRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] ? item[key] : testRunDetailDeserializer(item[key]); + }); + return result; +} + +/** A recommendation object that provides a list of configuration that optimizes its category. */ +export interface TestProfileRunRecommendation { + /** Category of the recommendation. */ + category: RecommendationCategory; + /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ + configurations?: string[]; +} + +export function testProfileRunRecommendationDeserializer( + item: any, +): TestProfileRunRecommendation { + return { + category: item["category"], + configurations: !item["configurations"] + ? item["configurations"] + : item["configurations"].map((p: any) => { + return p; + }), + }; +} + +/** Category of Recommendation. */ +export enum KnownRecommendationCategory { + /** The recommendation for this category optimizes the throughput/RPS (Requests per Second) of the app. */ + ThroughputOptimized = "ThroughputOptimized", + /** The recommendation for this category optimizes the cost of the app. */ + CostOptimized = "CostOptimized", +} + +/** + * Category of Recommendation. \ + * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ThroughputOptimized**: The recommendation for this category optimizes the throughput\/RPS (Requests per Second) of the app. \ + * **CostOptimized**: The recommendation for this category optimizes the cost of the app. + */ +export type RecommendationCategory = string; + +export function testProfileRunRecommendationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return testProfileRunRecommendationDeserializer(item); + }); +} + +/** Paged collection of TestFileInfo items */ +export interface _PagedTestFileInfo { + /** The TestFileInfo items on this page */ + value: TestFileInfo[]; + /** The link to the next page of items */ + nextLink?: string; +} + +export function _pagedTestFileInfoDeserializer(item: any): _PagedTestFileInfo { + return { + value: testFileInfoArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +/** Paged collection of Test items */ +export interface _PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +export function _pagedTestDeserializer(item: any): _PagedTest { + return { + value: testArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function testArraySerializer(result: Array): any[] { + return result.map((item) => { + return testSerializer(item); + }); +} + +export function testArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return testDeserializer(item); + }); +} + +/** Paged collection of TestRun items */ +export interface _PagedTestRun { + /** The TestRun items on this page */ + value: TestRun[]; + /** The link to the next page of items */ + nextLink?: string; +} + +export function _pagedTestRunDeserializer(item: any): _PagedTestRun { + return { + value: testRunArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function testRunArraySerializer(result: Array): any[] { + return result.map((item) => { + return testRunSerializer(item); + }); +} + +export function testRunArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return testRunDeserializer(item); + }); +} + +/** Paged collection of TestProfile items */ +export interface _PagedTestProfile { + /** The TestProfile items on this page */ + value: TestProfile[]; + /** The link to the next page of items */ + nextLink?: string; +} + +export function _pagedTestProfileDeserializer(item: any): _PagedTestProfile { + return { + value: testProfileArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function testProfileArraySerializer(result: Array): any[] { + return result.map((item) => { + return testProfileSerializer(item); + }); +} + +export function testProfileArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return testProfileDeserializer(item); + }); +} + +/** Paged collection of TestProfileRun items */ +export interface _PagedTestProfileRun { + /** The TestProfileRun items on this page */ + value: TestProfileRun[]; + /** The link to the next page of items */ + nextLink?: string; +} + +export function _pagedTestProfileRunDeserializer( + item: any, +): _PagedTestProfileRun { + return { + value: testProfileRunArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function testProfileRunArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return testProfileRunSerializer(item); + }); +} + +export function testProfileRunArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return testProfileRunDeserializer(item); + }); +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/index.ts index 47cb18d325..3c55ffe9d3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/index.ts @@ -7,8 +7,14 @@ export { getTestProfile, listTestProfiles, } from "./operations.js"; +export { + CreateOrUpdateTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + GetTestProfileOptionalParams, + ListTestProfilesOptionalParams, +} from "./options.js"; export { createTestProfileAdministration, - LoadTestServiceContext, + TestProfileAdministrationContext, TestProfileAdministrationClientOptionalParams, } from "./testProfileAdministrationContext.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/operations.ts index bf44fca598..20e50d48a3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/operations.ts @@ -2,27 +2,29 @@ // Licensed under the MIT License. import { - targetResourceConfigurationsUnionSerializer, + TestProfileAdministrationContext as Client, + CreateOrUpdateTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + GetTestProfileOptionalParams, + ListTestProfilesOptionalParams, +} from "./index.js"; +import { TestProfile, + testProfileSerializer, + testProfileDeserializer, _PagedTestProfile, -} from "../models/models.js"; -import { LoadTestServiceContext as Client } from "./index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; + _pagedTestProfileDeserializer, +} from "../../models/models.js"; import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../../static-helpers/pagingHelpers.js"; import { - CreateOrUpdateTestProfileOptionalParams, - DeleteTestProfileOptionalParams, - GetTestProfileOptionalParams, - ListTestProfilesOptionalParams, -} from "../models/options.js"; + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; export function _createOrUpdateTestProfileSend( context: Client, @@ -36,17 +38,7 @@ export function _createOrUpdateTestProfileSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { - displayName: body["displayName"], - description: body["description"], - testId: body["testId"], - targetResourceId: body["targetResourceId"], - targetResourceConfigurations: !body.targetResourceConfigurations - ? body.targetResourceConfigurations - : targetResourceConfigurationsUnionSerializer( - body.targetResourceConfigurations, - ), - }, + body: testProfileSerializer(body), }); } @@ -58,26 +50,7 @@ export async function _createOrUpdateTestProfileDeserialize( throw createRestError(result); } - return { - testProfileId: result.body["testProfileId"], - displayName: result.body["displayName"], - description: result.body["description"], - testId: result.body["testId"], - targetResourceId: result.body["targetResourceId"], - targetResourceConfigurations: !result.body.targetResourceConfigurations - ? undefined - : { kind: result.body.targetResourceConfigurations?.["kind"] }, - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testProfileDeserializer(result.body); } /** Create a new test profile or update an existing test profile by providing the test profile Id. */ @@ -145,26 +118,7 @@ export async function _getTestProfileDeserialize( throw createRestError(result); } - return { - testProfileId: result.body["testProfileId"], - displayName: result.body["displayName"], - description: result.body["description"], - testId: result.body["testId"], - targetResourceId: result.body["targetResourceId"], - targetResourceConfigurations: !result.body.targetResourceConfigurations - ? undefined - : { kind: result.body.targetResourceConfigurations?.["kind"] }, - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testProfileDeserializer(result.body); } /** Get load test profile details by test profile Id. */ @@ -203,31 +157,7 @@ export async function _listTestProfilesDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - testProfileId: p["testProfileId"], - displayName: p["displayName"], - description: p["description"], - testId: p["testId"], - targetResourceId: p["targetResourceId"], - targetResourceConfigurations: !p.targetResourceConfigurations - ? undefined - : { kind: p.targetResourceConfigurations?.["kind"] }, - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, - createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: p["lastModifiedBy"], - }; - }), - nextLink: result.body["nextLink"], - }; + return _pagedTestProfileDeserializer(result.body); } /** Get all test profiles for the given filters. */ diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/options.ts similarity index 100% rename from packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/models/options.ts rename to packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/options.ts diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/testProfileAdministrationContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/testProfileAdministrationContext.ts index 3aadb37634..bae632ebe7 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/testProfileAdministrationContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/testProfileAdministrationContext.ts @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { TokenCredential } from "@azure/core-auth"; -export interface LoadTestServiceContext extends Client {} +export interface TestProfileAdministrationContext extends Client {} /** Optional parameters for the client. */ export interface TestProfileAdministrationClientOptionalParams @@ -18,7 +18,7 @@ export function createTestProfileAdministration( endpointParam: string, credential: TokenCredential, options: TestProfileAdministrationClientOptionalParams = {}, -): LoadTestServiceContext { +): TestProfileAdministrationContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/index.ts index d85598fb5e..9cd5d80591 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/index.ts @@ -1,95 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +export { TestProfileAdministrationClient } from "./testProfileAdministrationClient.js"; export { - TestProfileAdministrationClient, - TestProfileAdministrationClientOptionalParams, -} from "./testProfileAdministrationClient.js"; -export { - Test, - PassFailCriteria, - PassFailMetric, - KnownPFMetrics, - PFMetrics, - KnownPFAgFunc, - PFAgFunc, - KnownPFAction, - PFAction, - KnownPFResult, - PFResult, - AutoStopCriteria, - Secret, - KnownSecretType, - SecretType, - CertificateMetadata, - KnownCertificateType, - CertificateType, - LoadTestConfiguration, - OptionalLoadTestConfig, - RegionalConfiguration, - TestInputArtifacts, - TestFileInfo, - KnownFileType, - FileType, - KnownFileStatus, - FileStatus, - KnownTestKind, - TestKind, - TestAppComponents, - AppComponent, - TestServerMetricConfig, - ResourceMetric, - APIVersions, - TestRun, - ErrorDetails, - TestRunStatistics, - TestRunArtifacts, - TestRunInputArtifacts, - TestRunFileInfo, - TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, - PFTestResult, - KnownStatus, - Status, - KnownRequestDataLevel, - RequestDataLevel, - TestRunAppComponents, - TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, - DimensionValueList, - MetricDefinitionCollection, - MetricDefinition, - NameAndDesc, - KnownAggregationType, - AggregationType, - KnownMetricUnit, - MetricUnit, - MetricAvailability, - MetricNamespaceCollection, - MetricNamespace, - MetricRequestPayload, - DimensionFilter, - TimeSeriesElement, - MetricValue, - DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, CreateOrUpdateTestProfileOptionalParams, DeleteTestProfileOptionalParams, GetTestProfileOptionalParams, ListTestProfilesOptionalParams, -} from "./models/index.js"; + TestProfileAdministrationContext, + TestProfileAdministrationClientOptionalParams, +} from "./api/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/models/models.ts deleted file mode 100644 index 046c225d0a..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/models/models.ts +++ /dev/null @@ -1,1615 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { serializeRecord } from "../../helpers/serializerHelpers.js"; - -/** Load test model. */ -export interface Test { - /** Pass fail criteria for a test. */ - passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; - /** - * Secrets can be stored in an Azure Key Vault or any other secret store. If the - * secret is stored in an Azure Key Vault, the value should be the secret - * identifier and the type should be AKV_SECRET_URI. If the secret is stored - * elsewhere, the secret value should be provided directly and the type should be - * SECRET_VALUE. - */ - secrets?: Record; - /** Certificates metadata. */ - certificate?: CertificateMetadata; - /** Environment variables which are defined as a set of pairs. */ - environmentVariables?: Record; - /** The load test configuration. */ - loadTestConfiguration?: LoadTestConfiguration; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; - /** The input artifacts for the test. */ - readonly inputArtifacts?: TestInputArtifacts; - /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testId: string; - /** The test description. */ - description?: string; - /** Display name of a test. */ - displayName?: string; - /** Subnet ID on which the load test instances should run. */ - subnetId?: string; - /** Kind of test. */ - kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; - /** Type of the managed identity referencing the Key vault. */ - keyvaultReferenceIdentityType?: string; - /** Resource Id of the managed identity referencing the Key vault. */ - keyvaultReferenceIdentityId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testSerializer(item: Test): Record { - return { - passFailCriteria: !item.passFailCriteria - ? item.passFailCriteria - : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), - secrets: !item.secrets - ? item.secrets - : (serializeRecord(item.secrets as any, secretSerializer) as any), - certificate: !item.certificate - ? item.certificate - : certificateMetadataSerializer(item.certificate), - environmentVariables: !item.environmentVariables - ? item.environmentVariables - : (serializeRecord(item.environmentVariables as any) as any), - loadTestConfiguration: !item.loadTestConfiguration - ? item.loadTestConfiguration - : loadTestConfigurationSerializer(item.loadTestConfiguration), - baselineTestRunId: item["baselineTestRunId"], - description: item["description"], - displayName: item["displayName"], - subnetId: item["subnetId"], - kind: item["kind"], - publicIPDisabled: item["publicIPDisabled"], - keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], - keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], - }; -} - -/** Pass fail criteria for a test. */ -export interface PassFailCriteria { - /** Map of id and pass fail metrics { id : pass fail metrics }. */ - passFailMetrics?: Record; -} - -export function passFailCriteriaSerializer( - item: PassFailCriteria, -): Record { - return { - passFailMetrics: !item.passFailMetrics - ? item.passFailMetrics - : (serializeRecord( - item.passFailMetrics as any, - passFailMetricSerializer, - ) as any), - }; -} - -/** Pass fail metric */ -export interface PassFailMetric { - /** The client metric on which the criteria should be applied. */ - clientMetric?: PFMetrics; - /** - * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, - * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, - * ‘count’ - for requests - */ - aggregate?: PFAgFunc; - /** The comparison operator. Supported types ‘>’, ‘<’ */ - condition?: string; - /** Request name for which the Pass fail criteria has to be applied */ - requestName?: string; - /** - * The value to compare with the client metric. Allowed values - ‘error : [0.0 , - * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. - */ - value?: number; - /** Action taken after the threshold is met. Default is ‘continue’. */ - action?: PFAction; - /** The actual value of the client metric for the test run. */ - readonly actualValue?: number; - /** Outcome of the test run. */ - readonly result?: PFResult; -} - -export function passFailMetricSerializer( - item: PassFailMetric, -): Record { - return { - clientMetric: item["clientMetric"], - aggregate: item["aggregate"], - condition: item["condition"], - requestName: item["requestName"], - value: item["value"], - action: item["action"], - }; -} - -/** Known values of {@link PFMetrics} that the service accepts. */ -export enum KnownPFMetrics { - /** response_time_ms */ - response_time_ms = "response_time_ms", - /** latency */ - latency = "latency", - /** error */ - error = "error", - /** requests */ - requests = "requests", - /** requests_per_sec */ - requests_per_sec = "requests_per_sec", -} - -/** - * Metrics for pass/fail criteria. \ - * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **response_time_ms** \ - * **latency** \ - * **error** \ - * **requests** \ - * **requests_per_sec** - */ -export type PFMetrics = string; - -/** Known values of {@link PFAgFunc} that the service accepts. */ -export enum KnownPFAgFunc { - /** count */ - count = "count", - /** percentage */ - percentage = "percentage", - /** avg */ - avg = "avg", - /** p50 */ - p50 = "p50", - /** p75 */ - p75 = "p75", - /** p90 */ - p90 = "p90", - /** p95 */ - p95 = "p95", - /** p96 */ - p96 = "p96", - /** p97 */ - p97 = "p97", - /** p98 */ - p98 = "p98", - /** p99 */ - p99 = "p99", - /** p99.9 */ - "p99.9" = "p99.9", - /** p99.99 */ - "p99.99" = "p99.99", - /** min */ - min = "min", - /** max */ - max = "max", -} - -/** - * Aggregation functions for pass/fail criteria. \ - * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **count** \ - * **percentage** \ - * **avg** \ - * **p50** \ - * **p75** \ - * **p90** \ - * **p95** \ - * **p96** \ - * **p97** \ - * **p98** \ - * **p99** \ - * **p99.9** \ - * **p99.99** \ - * **min** \ - * **max** - */ -export type PFAgFunc = string; - -/** Known values of {@link PFAction} that the service accepts. */ -export enum KnownPFAction { - /** continue */ - "continue" = "continue", - /** stop */ - stop = "stop", -} - -/** - * Action to take on failure of pass/fail criteria. \ - * {@link KnownPFAction} can be used interchangeably with PFAction, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **continue** \ - * **stop** - */ -export type PFAction = string; - -/** Known values of {@link PFResult} that the service accepts. */ -export enum KnownPFResult { - /** passed */ - passed = "passed", - /** undetermined */ - undetermined = "undetermined", - /** failed */ - failed = "failed", -} - -/** - * Pass/fail criteria result. \ - * {@link KnownPFResult} can be used interchangeably with PFResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **passed** \ - * **undetermined** \ - * **failed** - */ -export type PFResult = string; - -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteria { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} - -export function autoStopCriteriaSerializer( - item: AutoStopCriteria, -): Record { - return { - autoStopDisabled: item["autoStopDisabled"], - errorRate: item["errorRate"], - errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], - }; -} - -/** Secret */ -export interface Secret { - /** The value of the secret for the respective type */ - value?: string; - /** Type of secret */ - type?: SecretType; -} - -export function secretSerializer(item: Secret): Record { - return { - value: item["value"], - type: item["type"], - }; -} - -/** Known values of {@link SecretType} that the service accepts. */ -export enum KnownSecretType { - /** AKV_SECRET_URI */ - AKV_SECRET_URI = "AKV_SECRET_URI", - /** SECRET_VALUE */ - SECRET_VALUE = "SECRET_VALUE", -} - -/** - * Types of secrets supported. \ - * {@link KnownSecretType} can be used interchangeably with SecretType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_SECRET_URI** \ - * **SECRET_VALUE** - */ -export type SecretType = string; - -/** Certificates metadata */ -export interface CertificateMetadata { - /** The value of the certificate for respective type */ - value?: string; - /** Type of certificate */ - type?: CertificateType; - /** Name of the certificate. */ - name?: string; -} - -export function certificateMetadataSerializer( - item: CertificateMetadata, -): Record { - return { - value: item["value"], - type: item["type"], - name: item["name"], - }; -} - -/** Known values of {@link CertificateType} that the service accepts. */ -export enum KnownCertificateType { - /** AKV_CERT_URI */ - AKV_CERT_URI = "AKV_CERT_URI", -} - -/** - * Types of certificates supported. \ - * {@link KnownCertificateType} can be used interchangeably with CertificateType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_CERT_URI** - */ -export type CertificateType = string; - -/** Configurations for the load test. */ -export interface LoadTestConfiguration { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ - engineInstances?: number; - /** - * If false, Azure Load Testing copies and processes your input files unmodified - * across all test engine instances. If true, Azure Load Testing splits the CSV - * input data evenly across all engine instances. If you provide multiple CSV - * files, each file will be split evenly. - */ - splitAllCSVs?: boolean; - /** - * If true, optionalLoadTestConfig is required and JMX script for the load test is - * not required to upload. - */ - quickStartTest?: boolean; - /** Configuration for quick load test */ - optionalLoadTestConfig?: OptionalLoadTestConfig; - /** Region distribution configuration for the load test. */ - regionalLoadTestConfig?: RegionalConfiguration[]; -} - -export function loadTestConfigurationSerializer( - item: LoadTestConfiguration, -): Record { - return { - engineInstances: item["engineInstances"], - splitAllCSVs: item["splitAllCSVs"], - quickStartTest: item["quickStartTest"], - optionalLoadTestConfig: !item.optionalLoadTestConfig - ? item.optionalLoadTestConfig - : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), - regionalLoadTestConfig: - item["regionalLoadTestConfig"] === undefined - ? item["regionalLoadTestConfig"] - : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), - }; -} - -/** Configuration for quick load test */ -export interface OptionalLoadTestConfig { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ - endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ - virtualUsers?: number; - /** Ramp up time in seconds. */ - rampUpTime?: number; - /** Test run duration in seconds. */ - duration?: number; -} - -export function optionalLoadTestConfigSerializer( - item: OptionalLoadTestConfig, -): Record { - return { - endpointUrl: item["endpointUrl"], - requestsPerSecond: item["requestsPerSecond"], - maxResponseTimeInMs: item["maxResponseTimeInMs"], - virtualUsers: item["virtualUsers"], - rampUpTime: item["rampUpTime"], - duration: item["duration"], - }; -} - -/** Region distribution configuration for the load test. */ -export interface RegionalConfiguration { - /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ - engineInstances: number; - /** - * Azure region name. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - region: string; -} - -export function regionalConfigurationSerializer( - item: RegionalConfiguration, -): Record { - return { - engineInstances: item["engineInstances"], - region: item["region"], - }; -} - -/** The input artifacts for the test. */ -export interface TestInputArtifacts { - /** File info */ - configFileInfo?: TestFileInfo; - /** File info */ - testScriptFileInfo?: TestFileInfo; - /** File info */ - userPropFileInfo?: TestFileInfo; - /** File info */ - inputArtifactsZipFileInfo?: TestFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfo; - /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestFileInfo[]; -} - -/** Test file info. */ -export interface TestFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; -} - -/** Known values of {@link FileType} that the service accepts. */ -export enum KnownFileType { - /** JMX_FILE */ - JMX_FILE = "JMX_FILE", - /** USER_PROPERTIES */ - USER_PROPERTIES = "USER_PROPERTIES", - /** ADDITIONAL_ARTIFACTS */ - ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", - /** ZIPPED_ARTIFACTS */ - ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", - /** URL_TEST_CONFIG */ - URL_TEST_CONFIG = "URL_TEST_CONFIG", - /** TEST_SCRIPT */ - TEST_SCRIPT = "TEST_SCRIPT", -} - -/** - * Types of file supported. \ - * {@link KnownFileType} can be used interchangeably with FileType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **JMX_FILE** \ - * **USER_PROPERTIES** \ - * **ADDITIONAL_ARTIFACTS** \ - * **ZIPPED_ARTIFACTS** \ - * **URL_TEST_CONFIG** \ - * **TEST_SCRIPT** - */ -export type FileType = string; - -/** Known values of {@link FileStatus} that the service accepts. */ -export enum KnownFileStatus { - /** NOT_VALIDATED */ - NOT_VALIDATED = "NOT_VALIDATED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", - /** VALIDATION_INITIATED */ - VALIDATION_INITIATED = "VALIDATION_INITIATED", - /** VALIDATION_NOT_REQUIRED */ - VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", -} - -/** - * File status. \ - * {@link KnownFileStatus} can be used interchangeably with FileStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NOT_VALIDATED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** \ - * **VALIDATION_INITIATED** \ - * **VALIDATION_NOT_REQUIRED** - */ -export type FileStatus = string; - -/** Known values of {@link TestKind} that the service accepts. */ -export enum KnownTestKind { - /** URL */ - URL = "URL", - /** JMX */ - JMX = "JMX", - /** Locust */ - Locust = "Locust", -} - -/** - * Test kind \ - * {@link KnownTestKind} can be used interchangeably with TestKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **URL** \ - * **JMX** \ - * **Locust** - */ -export type TestKind = string; - -/** Test app components */ -export interface TestAppComponents { - /** - * Azure resource collection { resource id (fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) - * : resource object } - */ - components: Record; - /** Test identifier */ - readonly testId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testAppComponentsSerializer( - item: TestAppComponents, -): Record { - return { - components: serializeRecord( - item.components as any, - appComponentSerializer, - ) as any, - }; -} - -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ -export interface AppComponent { - /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ - readonly resourceId: string; - /** Azure resource name, required while creating the app component. */ - resourceName: string; - /** Azure resource type, required while creating the app component. */ - resourceType: string; - /** Azure resource display name */ - displayName?: string; - /** Resource group name of the Azure resource */ - readonly resourceGroup?: string; - /** Subscription Id of the Azure resource */ - readonly subscriptionId?: string; - /** Kind of Azure resource type */ - kind?: string; -} - -export function appComponentSerializer( - item: AppComponent, -): Record { - return { - resourceName: item["resourceName"], - resourceType: item["resourceType"], - displayName: item["displayName"], - kind: item["kind"], - }; -} - -/** Test server metrics configuration */ -export interface TestServerMetricConfig { - /** Test identifier */ - readonly testId?: string; - /** - * Azure resource metrics collection {metric id : metrics object} (Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition - * for metric id). - */ - metrics: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testServerMetricConfigSerializer( - item: TestServerMetricConfig, -): Record { - return { - metrics: serializeRecord( - item.metrics as any, - resourceMetricSerializer, - ) as any, - }; -} - -/** - * Associated metric definition for particular metrics of the azure resource ( - * Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition). - */ -export interface ResourceMetric { - /** Unique name for metric. */ - readonly id?: string; - /** Azure resource id. */ - resourceId: string; - /** Metric name space. */ - metricNamespace: string; - /** Metric description. */ - displayDescription?: string; - /** The invariant value of metric name */ - name: string; - /** Metric aggregation. */ - aggregation: string; - /** Metric unit. */ - unit?: string; - /** Azure resource type. */ - resourceType: string; -} - -export function resourceMetricSerializer( - item: ResourceMetric, -): Record { - return { - resourceId: item["resourceId"], - metricNamespace: item["metricNamespace"], - displayDescription: item["displayDescription"], - name: item["name"], - aggregation: item["aggregation"], - unit: item["unit"], - resourceType: item["resourceType"], - }; -} - -/** Azure Load Testing API versions. */ -export type APIVersions = - | "2022-11-01" - | "2023-04-01-preview" - | "2024-03-01-preview" - | "2024-05-01-preview"; - -/** Load test run model */ -export interface TestRun { - /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testRunId: string; - /** Pass fail criteria for a test. */ - passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; - /** - * Secrets can be stored in an Azure Key Vault or any other secret store. If the - * secret is stored in an Azure Key Vault, the value should be the secret - * identifier and the type should be AKV_SECRET_URI. If the secret is stored - * elsewhere, the secret value should be provided directly and the type should be - * SECRET_VALUE. - */ - secrets?: Record; - /** Certificates metadata */ - certificate?: CertificateMetadata; - /** Environment variables which are defined as a set of pairs. */ - environmentVariables?: Record; - /** Error details if there is any failure in load test run */ - readonly errorDetails?: ErrorDetails[]; - /** - * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. - * The sampler name is the same as the name mentioned in the test script. - * Sampler name "Total" represents the aggregated statistics of all the samplers. - */ - readonly testRunStatistics?: Record; - /** - * Regional statistics. Key is the Azure region name and value is the test run statistics. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - readonly regionalStatistics?: Record; - /** The load test configuration. */ - loadTestConfiguration?: LoadTestConfiguration; - /** Collection of test run artifacts */ - readonly testArtifacts?: TestRunArtifacts; - /** Test result for pass/Fail criteria used during the test run. */ - readonly testResult?: PFTestResult; - /** Number of virtual users, for which test has been run. */ - readonly virtualUsers?: number; - /** Display name of a testRun. */ - displayName?: string; - /** Associated test Id. */ - testId?: string; - /** The test run description. */ - description?: string; - /** The test run status. */ - readonly status?: Status; - /** The test run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; - /** Test run initiated time. */ - readonly executedDateTime?: Date; - /** Portal url. */ - readonly portalUrl?: string; - /** Test run duration in milliseconds. */ - readonly duration?: number; - /** Subnet ID on which the load test instances should run. */ - readonly subnetId?: string; - /** Type of test. */ - readonly kind?: TestKind; - /** Request data collection level for test run */ - requestDataLevel?: RequestDataLevel; - /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ - debugLogsEnabled?: boolean; - /** Inject load test engines without deploying public IP for outbound access */ - readonly publicIPDisabled?: boolean; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunSerializer(item: TestRun): Record { - return { - passFailCriteria: !item.passFailCriteria - ? item.passFailCriteria - : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), - secrets: !item.secrets - ? item.secrets - : (serializeRecord(item.secrets as any, secretSerializer) as any), - certificate: !item.certificate - ? item.certificate - : certificateMetadataSerializer(item.certificate), - environmentVariables: !item.environmentVariables - ? item.environmentVariables - : (serializeRecord(item.environmentVariables as any) as any), - loadTestConfiguration: !item.loadTestConfiguration - ? item.loadTestConfiguration - : loadTestConfigurationSerializer(item.loadTestConfiguration), - displayName: item["displayName"], - testId: item["testId"], - description: item["description"], - requestDataLevel: item["requestDataLevel"], - debugLogsEnabled: item["debugLogsEnabled"], - }; -} - -/** Error details if there is any failure in load test run */ -export interface ErrorDetails { - /** Error details in case test run was not successfully run. */ - readonly message?: string; -} - -/** Test run statistics. */ -export interface TestRunStatistics { - /** Transaction name. */ - readonly transaction?: string; - /** Sampler count. */ - readonly sampleCount?: number; - /** Error count. */ - readonly errorCount?: number; - /** Error percentage. */ - readonly errorPct?: number; - /** Mean response time. */ - readonly meanResTime?: number; - /** Median response time. */ - readonly medianResTime?: number; - /** Max response time. */ - readonly maxResTime?: number; - /** Minimum response time. */ - readonly minResTime?: number; - /** 90 percentile response time. */ - readonly pct1ResTime?: number; - /** 95 percentile response time. */ - readonly pct2ResTime?: number; - /** 99 percentile response time. */ - readonly pct3ResTime?: number; - /** 75 percentile response time. */ - readonly pct75ResTime?: number; - /** 96 percentile response time. */ - readonly pct96ResTime?: number; - /** 97 percentile response time. */ - readonly pct97ResTime?: number; - /** 98 percentile response time. */ - readonly pct98ResTime?: number; - /** 99.9 percentile response time. */ - readonly pct999ResTime?: number; - /** 99.99 percentile response time. */ - readonly pct9999ResTime?: number; - /** Throughput. */ - readonly throughput?: number; - /** Received network bytes. */ - readonly receivedKBytesPerSec?: number; - /** Send network bytes. */ - readonly sentKBytesPerSec?: number; -} - -/** Collection of test run artifacts */ -export interface TestRunArtifacts { - /** The input artifacts for the test run. */ - readonly inputArtifacts?: TestRunInputArtifacts; - /** The output artifacts for the test run. */ - outputArtifacts?: TestRunOutputArtifacts; -} - -/** The input artifacts for the test run. */ -export interface TestRunInputArtifacts { - /** File info */ - configFileInfo?: TestRunFileInfo; - /** File info */ - testScriptFileInfo?: TestRunFileInfo; - /** File info */ - userPropFileInfo?: TestRunFileInfo; - /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfo; - /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestRunFileInfo[]; -} - -/** Test run file info. */ -export interface TestRunFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; -} - -/** The output artifacts for the test run. */ -export interface TestRunOutputArtifacts { - /** File info */ - resultFileInfo?: TestRunFileInfo; - /** File info */ - logsFileInfo?: TestRunFileInfo; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfo; - /** The report file for the test run. */ - reportFileInfo?: TestRunFileInfo; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfo { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: Date; -} - -/** Known values of {@link PFTestResult} that the service accepts. */ -export enum KnownPFTestResult { - /** PASSED */ - PASSED = "PASSED", - /** NOT_APPLICABLE */ - NOT_APPLICABLE = "NOT_APPLICABLE", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test result based on pass/fail criteria. \ - * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PASSED** \ - * **NOT_APPLICABLE** \ - * **FAILED** - */ -export type PFTestResult = string; - -/** Known values of {@link Status} that the service accepts. */ -export enum KnownStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** PROVISIONING */ - PROVISIONING = "PROVISIONING", - /** PROVISIONED */ - PROVISIONED = "PROVISIONED", - /** CONFIGURING */ - CONFIGURING = "CONFIGURING", - /** CONFIGURED */ - CONFIGURED = "CONFIGURED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** EXECUTED */ - EXECUTED = "EXECUTED", - /** DEPROVISIONING */ - DEPROVISIONING = "DEPROVISIONING", - /** DEPROVISIONED */ - DEPROVISIONED = "DEPROVISIONED", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", -} - -/** - * Test run status. \ - * {@link KnownStatus} can be used interchangeably with Status, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **PROVISIONING** \ - * **PROVISIONED** \ - * **CONFIGURING** \ - * **CONFIGURED** \ - * **EXECUTING** \ - * **EXECUTED** \ - * **DEPROVISIONING** \ - * **DEPROVISIONED** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** - */ -export type Status = string; - -/** Known values of {@link RequestDataLevel} that the service accepts. */ -export enum KnownRequestDataLevel { - /** NONE */ - NONE = "NONE", - /** ERRORS */ - ERRORS = "ERRORS", -} - -/** - * Request data collection level for test run \ - * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NONE** \ - * **ERRORS** - */ -export type RequestDataLevel = string; - -/** Test run app component */ -export interface TestRunAppComponents { - /** - * Azure resource collection { resource id (fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) - * : resource object } - */ - components: Record; - /** Test run identifier */ - readonly testRunId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunAppComponentsSerializer( - item: TestRunAppComponents, -): Record { - return { - components: serializeRecord( - item.components as any, - appComponentSerializer, - ) as any, - }; -} - -/** Test run server metrics configuration */ -export interface TestRunServerMetricConfig { - /** Test run identifier */ - readonly testRunId?: string; - /** - * Azure resource metrics collection {metric id : metrics object} (Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition - * for metric id). - */ - metrics?: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunServerMetricConfigSerializer( - item: TestRunServerMetricConfig, -): Record { - return { - metrics: !item.metrics - ? item.metrics - : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), - }; -} - -/** Known values of {@link TimeGrain} that the service accepts. */ -export enum KnownTimeGrain { - /** PT5S */ - PT5S = "PT5S", - /** PT10S */ - PT10S = "PT10S", - /** PT1M */ - PT1M = "PT1M", - /** PT5M */ - PT5M = "PT5M", - /** PT1H */ - PT1H = "PT1H", -} - -/** - * Time Grain \ - * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PT5S** \ - * **PT10S** \ - * **PT1M** \ - * **PT5M** \ - * **PT1H** - */ -export type TimeGrain = string; - -/** Metrics dimension values. */ -export interface DimensionValueList { - /** The dimension name */ - readonly name?: string; - /** The dimension value */ - value?: string[]; - /** Link for the next set of values in case of paginated results, if applicable. */ - nextLink?: string; -} - -/** Represents collection of metric definitions. */ -export interface MetricDefinitionCollection { - /** the values for the metric definitions. */ - value: MetricDefinition[]; -} - -/** Metric definition */ -export interface MetricDefinition { - /** List of dimensions */ - dimensions?: NameAndDesc[]; - /** The metric description */ - description?: string; - /** The metric name */ - name?: string; - /** The namespace the metric belongs to. */ - namespace?: string; - /** The primary aggregation type value defining how to use the values for display. */ - primaryAggregationType?: AggregationType; - /** The collection of what all aggregation types are supported. */ - supportedAggregationTypes?: string[]; - /** The unit of the metric. */ - unit?: MetricUnit; - /** - * Metric availability specifies the time grain (aggregation interval or - * frequency). - */ - metricAvailabilities?: MetricAvailability[]; -} - -/** The name and description */ -export interface NameAndDesc { - /** The description */ - description?: string; - /** The name */ - name?: string; -} - -/** Known values of {@link AggregationType} that the service accepts. */ -export enum KnownAggregationType { - /** Average */ - Average = "Average", - /** Count */ - Count = "Count", - /** None */ - None = "None", - /** Total */ - Total = "Total", - /** Percentile75 */ - Percentile75 = "Percentile75", - /** Percentile90 */ - Percentile90 = "Percentile90", - /** Percentile95 */ - Percentile95 = "Percentile95", - /** Percentile96 */ - Percentile96 = "Percentile96", - /** Percentile97 */ - Percentile97 = "Percentile97", - /** Percentile98 */ - Percentile98 = "Percentile98", - /** Percentile99 */ - Percentile99 = "Percentile99", - /** Percentile999 */ - Percentile999 = "Percentile999", - /** Percentile9999 */ - Percentile9999 = "Percentile9999", -} - -/** - * Aggregation type. \ - * {@link KnownAggregationType} can be used interchangeably with AggregationType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **Average** \ - * **Count** \ - * **None** \ - * **Total** \ - * **Percentile75** \ - * **Percentile90** \ - * **Percentile95** \ - * **Percentile96** \ - * **Percentile97** \ - * **Percentile98** \ - * **Percentile99** \ - * **Percentile999** \ - * **Percentile9999** - */ -export type AggregationType = string; - -/** Known values of {@link MetricUnit} that the service accepts. */ -export enum KnownMetricUnit { - /** NotSpecified */ - NotSpecified = "NotSpecified", - /** Percent */ - Percent = "Percent", - /** Count */ - Count = "Count", - /** Seconds */ - Seconds = "Seconds", - /** Milliseconds */ - Milliseconds = "Milliseconds", - /** Bytes */ - Bytes = "Bytes", - /** BytesPerSecond */ - BytesPerSecond = "BytesPerSecond", - /** CountPerSecond */ - CountPerSecond = "CountPerSecond", -} - -/** - * Metric unit. \ - * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NotSpecified** \ - * **Percent** \ - * **Count** \ - * **Seconds** \ - * **Milliseconds** \ - * **Bytes** \ - * **BytesPerSecond** \ - * **CountPerSecond** - */ -export type MetricUnit = string; - -/** Metric availability specifies the time grain (aggregation interval or frequency) */ -export interface MetricAvailability { - /** - * The time grain specifies the aggregation interval for the metric. Expressed as - * a duration 'PT1M', 'PT1H', etc. - */ - timeGrain?: TimeGrain; -} - -/** Represents collection of metric namespaces. */ -export interface MetricNamespaceCollection { - /** The values for the metric namespaces. */ - value: MetricNamespace[]; -} - -/** Metric namespace class specifies the metadata for a metric namespace. */ -export interface MetricNamespace { - /** The namespace description. */ - description?: string; - /** The metric namespace name. */ - name?: string; -} - -/** Filters to fetch the set of metric. */ -export interface MetricRequestPayload { - /** - * Get metrics for specific dimension values. Example: Metric contains dimension - * like SamplerName, Error. To retrieve all the time series data where SamplerName - * is equals to HTTPRequest1 or HTTPRequest2, the DimensionFilter value will be - * {"SamplerName", ["HTTPRequest1", "HTTPRequest2"} - */ - filters?: DimensionFilter[]; -} - -export function metricRequestPayloadSerializer( - item: MetricRequestPayload, -): Record { - return { - filters: - item["filters"] === undefined - ? item["filters"] - : item["filters"].map(dimensionFilterSerializer), - }; -} - -/** Dimension name and values to filter */ -export interface DimensionFilter { - /** The dimension name */ - name?: string; - /** The dimension values. Maximum values can be 20. */ - values?: string[]; -} - -export function dimensionFilterSerializer( - item: DimensionFilter, -): Record { - return { - name: item["name"], - values: item["values"], - }; -} - -/** The response to a metrics query. */ -export interface _Metrics { - /** The TimeSeriesElement items on this page */ - value: TimeSeriesElement[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** The time series returned when a data query is performed. */ -export interface TimeSeriesElement { - /** An array of data points representing the metric values. */ - data?: MetricValue[]; - /** The dimension values */ - dimensionValues?: DimensionValue[]; -} - -/** Represents a metric value. */ -export interface MetricValue { - /** The timestamp for the metric value in RFC 3339 format. */ - timestamp?: Date; - /** The metric value. */ - value?: number; -} - -/** Represents a metric dimension value. */ -export interface DimensionValue { - /** The name of the dimension. */ - name?: string; - /** The value of the dimension. */ - value?: string; -} - -/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ -export interface TestProfile { - /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileId: string; - /** Display name of the test profile. */ - displayName?: string; - /** Description for the test profile. */ - description?: string; - /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ - testId?: string; - /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ - targetResourceId?: string; - /** Configurations of the target resource on which testing would be done. */ - targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileSerializer( - item: TestProfile, -): Record { - return { - displayName: item["displayName"], - description: item["description"], - testId: item["testId"], - targetResourceId: item["targetResourceId"], - targetResourceConfigurations: !item.targetResourceConfigurations - ? item.targetResourceConfigurations - : targetResourceConfigurationsUnionSerializer( - item.targetResourceConfigurations, - ), - }; -} - -/** Configurations of a target resource. This varies with the kind of resource. */ -export interface TargetResourceConfigurations { - /** the discriminator possible values: FunctionsFlexConsumption */ - kind: ResourceKind; -} - -export function targetResourceConfigurationsUnionSerializer( - item: TargetResourceConfigurationsUnion, -) { - switch (item.kind) { - case "FunctionsFlexConsumption": - return functionFlexConsumptionTargetResourceConfigurationsSerializer( - item as FunctionFlexConsumptionTargetResourceConfigurations, - ); - - default: - return targetResourceConfigurationsSerializer(item); - } -} - -export function targetResourceConfigurationsSerializer( - item: TargetResourceConfigurationsUnion, -): Record { - return { - kind: item["kind"], - }; -} - -/** Configurations for a Function App using Flex Consumption Plan. */ -export interface FunctionFlexConsumptionTargetResourceConfigurations - extends TargetResourceConfigurations { - /** - * The kind value to use when providing configuration. - * This should typically be not changed from its value. - */ - kind: "FunctionsFlexConsumption"; - /** A map of configurations for a Function app using Flex Consumption Plan. */ - configurations?: Record; -} - -export function functionFlexConsumptionTargetResourceConfigurationsSerializer( - item: FunctionFlexConsumptionTargetResourceConfigurations, -): Record { - return { - kind: item["kind"], - configurations: !item.configurations - ? item.configurations - : (serializeRecord( - item.configurations as any, - functionFlexConsumptionResourceConfigurationSerializer, - ) as any), - }; -} - -/** Resource configuration instance for a Flex Consumption based Azure Function App. */ -export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 2048, 4096. */ - instanceMemoryMB: number; - /** HTTP Concurrency for the function app. */ - httpConcurrency: number; -} - -export function functionFlexConsumptionResourceConfigurationSerializer( - item: FunctionFlexConsumptionResourceConfiguration, -): Record { - return { - instanceMemoryMB: item["instanceMemoryMB"], - httpConcurrency: item["httpConcurrency"], - }; -} - -/** Known values of {@link ResourceKind} that the service accepts. */ -export enum KnownResourceKind { - /** FunctionsFlexConsumption */ - FunctionsFlexConsumption = "FunctionsFlexConsumption", -} - -/** - * Kind of the resource on which test profile is created. \ - * {@link KnownResourceKind} can be used interchangeably with ResourceKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **FunctionsFlexConsumption** - */ -export type ResourceKind = string; - -/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ -export interface TestProfileRun { - /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileRunId: string; - /** Display name for the test profile run. */ - displayName?: string; - /** The test profile run description */ - description?: string; - /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ - testProfileId?: string; - /** Target resource ID on which the test profile run is created */ - readonly targetResourceId?: string; - /** Configurations of the target resource on which the test profile ran. */ - readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The test profile run status. */ - readonly status?: TestProfileRunStatus; - /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ - readonly errorDetails?: ErrorDetails[]; - /** The test profile run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test profile run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; - /** Test profile run duration in seconds. */ - readonly durationInSeconds?: number; - /** - * Details of the test runs ran as part of the test profile run. - * Key is the testRunId of the corresponding testRun. - */ - readonly testRunDetails?: Record; - /** Recommendations provided based on a successful test profile run. */ - readonly recommendations?: TestProfileRunRecommendation[]; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileRunSerializer( - item: TestProfileRun, -): Record { - return { - displayName: item["displayName"], - description: item["description"], - testProfileId: item["testProfileId"], - }; -} - -/** Known values of {@link TestProfileRunStatus} that the service accepts. */ -export enum KnownTestProfileRunStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test profile run status. \ - * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **EXECUTING** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** - */ -export type TestProfileRunStatus = string; - -/** Details of a particular test run for a test profile run. */ -export interface TestRunDetail { - /** Status of the test run. */ - status: Status; - /** ID of the configuration on which the test ran. */ - configurationId: string; - /** Key value pair of extra properties associated with the test run. */ - properties: Record; -} - -/** A recommendation object that provides a list of configuration that optimizes its category. */ -export interface TestProfileRunRecommendation { - /** Category of the recommendation. */ - category: RecommendationCategory; - /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ - configurations?: string[]; -} - -/** Known values of {@link RecommendationCategory} that the service accepts. */ -export enum KnownRecommendationCategory { - /** ThroughputOptimized */ - ThroughputOptimized = "ThroughputOptimized", - /** CostOptimized */ - CostOptimized = "CostOptimized", -} - -/** - * Category of Recommendation. \ - * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ThroughputOptimized** \ - * **CostOptimized** - */ -export type RecommendationCategory = string; - -/** Paged collection of TestFileInfo items */ -export interface _PagedTestFileInfo { - /** The TestFileInfo items on this page */ - value: TestFileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of Test items */ -export interface _PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestRun items */ -export interface _PagedTestRun { - /** The TestRun items on this page */ - value: TestRun[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestProfile items */ -export interface _PagedTestProfile { - /** The TestProfile items on this page */ - value: TestProfile[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestProfileRun items */ -export interface _PagedTestProfileRun { - /** The TestProfileRun items on this page */ - value: TestProfileRun[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Alias for TargetResourceConfigurationsUnion */ -export type TargetResourceConfigurationsUnion = - | FunctionFlexConsumptionTargetResourceConfigurations - | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/testProfileAdministrationClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/testProfileAdministrationClient.ts index a4dfac96c8..44400053cc 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/testProfileAdministrationClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/testProfileAdministrationClient.ts @@ -1,30 +1,28 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; -import { TestProfile } from "./models/models.js"; -import { - CreateOrUpdateTestProfileOptionalParams, - DeleteTestProfileOptionalParams, - GetTestProfileOptionalParams, - ListTestProfilesOptionalParams, -} from "./models/options.js"; import { createOrUpdateTestProfile, deleteTestProfile, getTestProfile, listTestProfiles, + CreateOrUpdateTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + GetTestProfileOptionalParams, + ListTestProfilesOptionalParams, createTestProfileAdministration, - LoadTestServiceContext, + TestProfileAdministrationContext, TestProfileAdministrationClientOptionalParams, } from "./api/index.js"; +import { TestProfile } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../static-helpers/pagingHelpers.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TokenCredential } from "@azure/core-auth"; export { TestProfileAdministrationClientOptionalParams } from "./api/testProfileAdministrationContext.js"; export class TestProfileAdministrationClient { - private _client: LoadTestServiceContext; + private _client: TestProfileAdministrationContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/index.ts index 8d168d300c..4f3d1b732f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/index.ts @@ -8,8 +8,15 @@ export { listTestProfileRuns, stopTestProfileRun, } from "./operations.js"; +export { + CreateOrUpdateTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + GetTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + StopTestProfileRunOptionalParams, +} from "./options.js"; export { createTestProfileRun, - LoadTestServiceContext, + TestProfileRunContext, TestProfileRunClientOptionalParams, } from "./testProfileRunContext.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/operations.ts index f866af3378..865818a82f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/operations.ts @@ -1,25 +1,31 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TestProfileRun, _PagedTestProfileRun } from "../models/models.js"; -import { LoadTestServiceContext as Client } from "./index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; -import { - PagedAsyncIterableIterator, - buildPagedAsyncIterator, -} from "../../static-helpers/pagingHelpers.js"; import { + TestProfileRunContext as Client, CreateOrUpdateTestProfileRunOptionalParams, DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, StopTestProfileRunOptionalParams, -} from "../models/options.js"; +} from "./index.js"; +import { + TestProfileRun, + testProfileRunSerializer, + testProfileRunDeserializer, + _PagedTestProfileRun, + _pagedTestProfileRunDeserializer, +} from "../../models/models.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../../static-helpers/pagingHelpers.js"; +import { + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; export function _createOrUpdateTestProfileRunSend( context: Client, @@ -33,11 +39,7 @@ export function _createOrUpdateTestProfileRunSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { - displayName: body["displayName"], - description: body["description"], - testProfileId: body["testProfileId"], - }, + body: testProfileRunSerializer(body), }); } @@ -49,52 +51,7 @@ export async function _createOrUpdateTestProfileRunDeserialize( throw createRestError(result); } - return { - testProfileRunId: result.body["testProfileRunId"], - displayName: result.body["displayName"], - description: result.body["description"], - testProfileId: result.body["testProfileId"], - targetResourceId: result.body["targetResourceId"], - targetResourceConfigurations: !result.body.targetResourceConfigurations - ? undefined - : { kind: result.body.targetResourceConfigurations?.["kind"] }, - status: result.body["status"], - errorDetails: - result.body["errorDetails"] === undefined - ? result.body["errorDetails"] - : result.body["errorDetails"].map((p: any) => { - return { message: p["message"] }; - }), - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - durationInSeconds: result.body["durationInSeconds"], - testRunDetails: result.body["testRunDetails"], - recommendations: - result.body["recommendations"] === undefined - ? result.body["recommendations"] - : result.body["recommendations"].map((p: any) => { - return { - category: p["category"], - configurations: p["configurations"], - }; - }), - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testProfileRunDeserializer(result.body); } /** Create and start a new test profile run with the given test profile run Id. */ @@ -166,52 +123,7 @@ export async function _getTestProfileRunDeserialize( throw createRestError(result); } - return { - testProfileRunId: result.body["testProfileRunId"], - displayName: result.body["displayName"], - description: result.body["description"], - testProfileId: result.body["testProfileId"], - targetResourceId: result.body["targetResourceId"], - targetResourceConfigurations: !result.body.targetResourceConfigurations - ? undefined - : { kind: result.body.targetResourceConfigurations?.["kind"] }, - status: result.body["status"], - errorDetails: - result.body["errorDetails"] === undefined - ? result.body["errorDetails"] - : result.body["errorDetails"].map((p: any) => { - return { message: p["message"] }; - }), - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - durationInSeconds: result.body["durationInSeconds"], - testRunDetails: result.body["testRunDetails"], - recommendations: - result.body["recommendations"] === undefined - ? result.body["recommendations"] - : result.body["recommendations"].map((p: any) => { - return { - category: p["category"], - configurations: p["configurations"], - }; - }), - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testProfileRunDeserializer(result.body); } /** Get test profile run details by test profile run Id. */ @@ -259,57 +171,7 @@ export async function _listTestProfileRunsDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { - testProfileRunId: p["testProfileRunId"], - displayName: p["displayName"], - description: p["description"], - testProfileId: p["testProfileId"], - targetResourceId: p["targetResourceId"], - targetResourceConfigurations: !p.targetResourceConfigurations - ? undefined - : { kind: p.targetResourceConfigurations?.["kind"] }, - status: p["status"], - errorDetails: - p["errorDetails"] === undefined - ? p["errorDetails"] - : p["errorDetails"].map((p: any) => { - return { message: p["message"] }; - }), - startDateTime: - p["startDateTime"] !== undefined - ? new Date(p["startDateTime"]) - : undefined, - endDateTime: - p["endDateTime"] !== undefined - ? new Date(p["endDateTime"]) - : undefined, - durationInSeconds: p["durationInSeconds"], - testRunDetails: p["testRunDetails"], - recommendations: - p["recommendations"] === undefined - ? p["recommendations"] - : p["recommendations"].map((p: any) => { - return { - category: p["category"], - configurations: p["configurations"], - }; - }), - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, - createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: p["lastModifiedBy"], - }; - }), - nextLink: result.body["nextLink"], - }; + return _pagedTestProfileRunDeserializer(result.body); } /** Get all test profile runs for the given filters. */ @@ -344,52 +206,7 @@ export async function _stopTestProfileRunDeserialize( throw createRestError(result); } - return { - testProfileRunId: result.body["testProfileRunId"], - displayName: result.body["displayName"], - description: result.body["description"], - testProfileId: result.body["testProfileId"], - targetResourceId: result.body["targetResourceId"], - targetResourceConfigurations: !result.body.targetResourceConfigurations - ? undefined - : { kind: result.body.targetResourceConfigurations?.["kind"] }, - status: result.body["status"], - errorDetails: - result.body["errorDetails"] === undefined - ? result.body["errorDetails"] - : result.body["errorDetails"].map((p: any) => { - return { message: p["message"] }; - }), - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - durationInSeconds: result.body["durationInSeconds"], - testRunDetails: result.body["testRunDetails"], - recommendations: - result.body["recommendations"] === undefined - ? result.body["recommendations"] - : result.body["recommendations"].map((p: any) => { - return { - category: p["category"], - configurations: p["configurations"], - }; - }), - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, - createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: result.body["lastModifiedBy"], - }; + return testProfileRunDeserializer(result.body); } /** Stop test profile run for the given test profile run Id. */ diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/options.ts similarity index 100% rename from packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/models/options.ts rename to packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/options.ts diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/testProfileRunContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/testProfileRunContext.ts index ae85ac5291..c0f3dd947b 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/testProfileRunContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/testProfileRunContext.ts @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { TokenCredential } from "@azure/core-auth"; -export interface LoadTestServiceContext extends Client {} +export interface TestProfileRunContext extends Client {} /** Optional parameters for the client. */ export interface TestProfileRunClientOptionalParams extends ClientOptions { @@ -17,7 +17,7 @@ export function createTestProfileRun( endpointParam: string, credential: TokenCredential, options: TestProfileRunClientOptionalParams = {}, -): LoadTestServiceContext { +): TestProfileRunContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/index.ts index f68c26412d..6ec95ed4ae 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/index.ts @@ -1,96 +1,13 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +export { TestProfileRunClient } from "./testProfileRunClient.js"; export { - TestProfileRunClient, - TestProfileRunClientOptionalParams, -} from "./testProfileRunClient.js"; -export { - Test, - PassFailCriteria, - PassFailMetric, - KnownPFMetrics, - PFMetrics, - KnownPFAgFunc, - PFAgFunc, - KnownPFAction, - PFAction, - KnownPFResult, - PFResult, - AutoStopCriteria, - Secret, - KnownSecretType, - SecretType, - CertificateMetadata, - KnownCertificateType, - CertificateType, - LoadTestConfiguration, - OptionalLoadTestConfig, - RegionalConfiguration, - TestInputArtifacts, - TestFileInfo, - KnownFileType, - FileType, - KnownFileStatus, - FileStatus, - KnownTestKind, - TestKind, - TestAppComponents, - AppComponent, - TestServerMetricConfig, - ResourceMetric, - APIVersions, - TestRun, - ErrorDetails, - TestRunStatistics, - TestRunArtifacts, - TestRunInputArtifacts, - TestRunFileInfo, - TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, - PFTestResult, - KnownStatus, - Status, - KnownRequestDataLevel, - RequestDataLevel, - TestRunAppComponents, - TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, - DimensionValueList, - MetricDefinitionCollection, - MetricDefinition, - NameAndDesc, - KnownAggregationType, - AggregationType, - KnownMetricUnit, - MetricUnit, - MetricAvailability, - MetricNamespaceCollection, - MetricNamespace, - MetricRequestPayload, - DimensionFilter, - TimeSeriesElement, - MetricValue, - DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, CreateOrUpdateTestProfileRunOptionalParams, DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, StopTestProfileRunOptionalParams, -} from "./models/index.js"; + TestProfileRunContext, + TestProfileRunClientOptionalParams, +} from "./api/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/models/index.ts deleted file mode 100644 index 4191597b05..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/models/index.ts +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -export { - Test, - PassFailCriteria, - PassFailMetric, - KnownPFMetrics, - PFMetrics, - KnownPFAgFunc, - PFAgFunc, - KnownPFAction, - PFAction, - KnownPFResult, - PFResult, - AutoStopCriteria, - Secret, - KnownSecretType, - SecretType, - CertificateMetadata, - KnownCertificateType, - CertificateType, - LoadTestConfiguration, - OptionalLoadTestConfig, - RegionalConfiguration, - TestInputArtifacts, - TestFileInfo, - KnownFileType, - FileType, - KnownFileStatus, - FileStatus, - KnownTestKind, - TestKind, - TestAppComponents, - AppComponent, - TestServerMetricConfig, - ResourceMetric, - APIVersions, - TestRun, - ErrorDetails, - TestRunStatistics, - TestRunArtifacts, - TestRunInputArtifacts, - TestRunFileInfo, - TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, - PFTestResult, - KnownStatus, - Status, - KnownRequestDataLevel, - RequestDataLevel, - TestRunAppComponents, - TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, - DimensionValueList, - MetricDefinitionCollection, - MetricDefinition, - NameAndDesc, - KnownAggregationType, - AggregationType, - KnownMetricUnit, - MetricUnit, - MetricAvailability, - MetricNamespaceCollection, - MetricNamespace, - MetricRequestPayload, - DimensionFilter, - TimeSeriesElement, - MetricValue, - DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, -} from "./models.js"; -export { - CreateOrUpdateTestProfileRunOptionalParams, - DeleteTestProfileRunOptionalParams, - GetTestProfileRunOptionalParams, - ListTestProfileRunsOptionalParams, - StopTestProfileRunOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/models/models.ts deleted file mode 100644 index 046c225d0a..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/models/models.ts +++ /dev/null @@ -1,1615 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { serializeRecord } from "../../helpers/serializerHelpers.js"; - -/** Load test model. */ -export interface Test { - /** Pass fail criteria for a test. */ - passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; - /** - * Secrets can be stored in an Azure Key Vault or any other secret store. If the - * secret is stored in an Azure Key Vault, the value should be the secret - * identifier and the type should be AKV_SECRET_URI. If the secret is stored - * elsewhere, the secret value should be provided directly and the type should be - * SECRET_VALUE. - */ - secrets?: Record; - /** Certificates metadata. */ - certificate?: CertificateMetadata; - /** Environment variables which are defined as a set of pairs. */ - environmentVariables?: Record; - /** The load test configuration. */ - loadTestConfiguration?: LoadTestConfiguration; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; - /** The input artifacts for the test. */ - readonly inputArtifacts?: TestInputArtifacts; - /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testId: string; - /** The test description. */ - description?: string; - /** Display name of a test. */ - displayName?: string; - /** Subnet ID on which the load test instances should run. */ - subnetId?: string; - /** Kind of test. */ - kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; - /** Type of the managed identity referencing the Key vault. */ - keyvaultReferenceIdentityType?: string; - /** Resource Id of the managed identity referencing the Key vault. */ - keyvaultReferenceIdentityId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testSerializer(item: Test): Record { - return { - passFailCriteria: !item.passFailCriteria - ? item.passFailCriteria - : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), - secrets: !item.secrets - ? item.secrets - : (serializeRecord(item.secrets as any, secretSerializer) as any), - certificate: !item.certificate - ? item.certificate - : certificateMetadataSerializer(item.certificate), - environmentVariables: !item.environmentVariables - ? item.environmentVariables - : (serializeRecord(item.environmentVariables as any) as any), - loadTestConfiguration: !item.loadTestConfiguration - ? item.loadTestConfiguration - : loadTestConfigurationSerializer(item.loadTestConfiguration), - baselineTestRunId: item["baselineTestRunId"], - description: item["description"], - displayName: item["displayName"], - subnetId: item["subnetId"], - kind: item["kind"], - publicIPDisabled: item["publicIPDisabled"], - keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], - keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], - }; -} - -/** Pass fail criteria for a test. */ -export interface PassFailCriteria { - /** Map of id and pass fail metrics { id : pass fail metrics }. */ - passFailMetrics?: Record; -} - -export function passFailCriteriaSerializer( - item: PassFailCriteria, -): Record { - return { - passFailMetrics: !item.passFailMetrics - ? item.passFailMetrics - : (serializeRecord( - item.passFailMetrics as any, - passFailMetricSerializer, - ) as any), - }; -} - -/** Pass fail metric */ -export interface PassFailMetric { - /** The client metric on which the criteria should be applied. */ - clientMetric?: PFMetrics; - /** - * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, - * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, - * ‘count’ - for requests - */ - aggregate?: PFAgFunc; - /** The comparison operator. Supported types ‘>’, ‘<’ */ - condition?: string; - /** Request name for which the Pass fail criteria has to be applied */ - requestName?: string; - /** - * The value to compare with the client metric. Allowed values - ‘error : [0.0 , - * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. - */ - value?: number; - /** Action taken after the threshold is met. Default is ‘continue’. */ - action?: PFAction; - /** The actual value of the client metric for the test run. */ - readonly actualValue?: number; - /** Outcome of the test run. */ - readonly result?: PFResult; -} - -export function passFailMetricSerializer( - item: PassFailMetric, -): Record { - return { - clientMetric: item["clientMetric"], - aggregate: item["aggregate"], - condition: item["condition"], - requestName: item["requestName"], - value: item["value"], - action: item["action"], - }; -} - -/** Known values of {@link PFMetrics} that the service accepts. */ -export enum KnownPFMetrics { - /** response_time_ms */ - response_time_ms = "response_time_ms", - /** latency */ - latency = "latency", - /** error */ - error = "error", - /** requests */ - requests = "requests", - /** requests_per_sec */ - requests_per_sec = "requests_per_sec", -} - -/** - * Metrics for pass/fail criteria. \ - * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **response_time_ms** \ - * **latency** \ - * **error** \ - * **requests** \ - * **requests_per_sec** - */ -export type PFMetrics = string; - -/** Known values of {@link PFAgFunc} that the service accepts. */ -export enum KnownPFAgFunc { - /** count */ - count = "count", - /** percentage */ - percentage = "percentage", - /** avg */ - avg = "avg", - /** p50 */ - p50 = "p50", - /** p75 */ - p75 = "p75", - /** p90 */ - p90 = "p90", - /** p95 */ - p95 = "p95", - /** p96 */ - p96 = "p96", - /** p97 */ - p97 = "p97", - /** p98 */ - p98 = "p98", - /** p99 */ - p99 = "p99", - /** p99.9 */ - "p99.9" = "p99.9", - /** p99.99 */ - "p99.99" = "p99.99", - /** min */ - min = "min", - /** max */ - max = "max", -} - -/** - * Aggregation functions for pass/fail criteria. \ - * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **count** \ - * **percentage** \ - * **avg** \ - * **p50** \ - * **p75** \ - * **p90** \ - * **p95** \ - * **p96** \ - * **p97** \ - * **p98** \ - * **p99** \ - * **p99.9** \ - * **p99.99** \ - * **min** \ - * **max** - */ -export type PFAgFunc = string; - -/** Known values of {@link PFAction} that the service accepts. */ -export enum KnownPFAction { - /** continue */ - "continue" = "continue", - /** stop */ - stop = "stop", -} - -/** - * Action to take on failure of pass/fail criteria. \ - * {@link KnownPFAction} can be used interchangeably with PFAction, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **continue** \ - * **stop** - */ -export type PFAction = string; - -/** Known values of {@link PFResult} that the service accepts. */ -export enum KnownPFResult { - /** passed */ - passed = "passed", - /** undetermined */ - undetermined = "undetermined", - /** failed */ - failed = "failed", -} - -/** - * Pass/fail criteria result. \ - * {@link KnownPFResult} can be used interchangeably with PFResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **passed** \ - * **undetermined** \ - * **failed** - */ -export type PFResult = string; - -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteria { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} - -export function autoStopCriteriaSerializer( - item: AutoStopCriteria, -): Record { - return { - autoStopDisabled: item["autoStopDisabled"], - errorRate: item["errorRate"], - errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], - }; -} - -/** Secret */ -export interface Secret { - /** The value of the secret for the respective type */ - value?: string; - /** Type of secret */ - type?: SecretType; -} - -export function secretSerializer(item: Secret): Record { - return { - value: item["value"], - type: item["type"], - }; -} - -/** Known values of {@link SecretType} that the service accepts. */ -export enum KnownSecretType { - /** AKV_SECRET_URI */ - AKV_SECRET_URI = "AKV_SECRET_URI", - /** SECRET_VALUE */ - SECRET_VALUE = "SECRET_VALUE", -} - -/** - * Types of secrets supported. \ - * {@link KnownSecretType} can be used interchangeably with SecretType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_SECRET_URI** \ - * **SECRET_VALUE** - */ -export type SecretType = string; - -/** Certificates metadata */ -export interface CertificateMetadata { - /** The value of the certificate for respective type */ - value?: string; - /** Type of certificate */ - type?: CertificateType; - /** Name of the certificate. */ - name?: string; -} - -export function certificateMetadataSerializer( - item: CertificateMetadata, -): Record { - return { - value: item["value"], - type: item["type"], - name: item["name"], - }; -} - -/** Known values of {@link CertificateType} that the service accepts. */ -export enum KnownCertificateType { - /** AKV_CERT_URI */ - AKV_CERT_URI = "AKV_CERT_URI", -} - -/** - * Types of certificates supported. \ - * {@link KnownCertificateType} can be used interchangeably with CertificateType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_CERT_URI** - */ -export type CertificateType = string; - -/** Configurations for the load test. */ -export interface LoadTestConfiguration { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ - engineInstances?: number; - /** - * If false, Azure Load Testing copies and processes your input files unmodified - * across all test engine instances. If true, Azure Load Testing splits the CSV - * input data evenly across all engine instances. If you provide multiple CSV - * files, each file will be split evenly. - */ - splitAllCSVs?: boolean; - /** - * If true, optionalLoadTestConfig is required and JMX script for the load test is - * not required to upload. - */ - quickStartTest?: boolean; - /** Configuration for quick load test */ - optionalLoadTestConfig?: OptionalLoadTestConfig; - /** Region distribution configuration for the load test. */ - regionalLoadTestConfig?: RegionalConfiguration[]; -} - -export function loadTestConfigurationSerializer( - item: LoadTestConfiguration, -): Record { - return { - engineInstances: item["engineInstances"], - splitAllCSVs: item["splitAllCSVs"], - quickStartTest: item["quickStartTest"], - optionalLoadTestConfig: !item.optionalLoadTestConfig - ? item.optionalLoadTestConfig - : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), - regionalLoadTestConfig: - item["regionalLoadTestConfig"] === undefined - ? item["regionalLoadTestConfig"] - : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), - }; -} - -/** Configuration for quick load test */ -export interface OptionalLoadTestConfig { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ - endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ - virtualUsers?: number; - /** Ramp up time in seconds. */ - rampUpTime?: number; - /** Test run duration in seconds. */ - duration?: number; -} - -export function optionalLoadTestConfigSerializer( - item: OptionalLoadTestConfig, -): Record { - return { - endpointUrl: item["endpointUrl"], - requestsPerSecond: item["requestsPerSecond"], - maxResponseTimeInMs: item["maxResponseTimeInMs"], - virtualUsers: item["virtualUsers"], - rampUpTime: item["rampUpTime"], - duration: item["duration"], - }; -} - -/** Region distribution configuration for the load test. */ -export interface RegionalConfiguration { - /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ - engineInstances: number; - /** - * Azure region name. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - region: string; -} - -export function regionalConfigurationSerializer( - item: RegionalConfiguration, -): Record { - return { - engineInstances: item["engineInstances"], - region: item["region"], - }; -} - -/** The input artifacts for the test. */ -export interface TestInputArtifacts { - /** File info */ - configFileInfo?: TestFileInfo; - /** File info */ - testScriptFileInfo?: TestFileInfo; - /** File info */ - userPropFileInfo?: TestFileInfo; - /** File info */ - inputArtifactsZipFileInfo?: TestFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfo; - /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestFileInfo[]; -} - -/** Test file info. */ -export interface TestFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; -} - -/** Known values of {@link FileType} that the service accepts. */ -export enum KnownFileType { - /** JMX_FILE */ - JMX_FILE = "JMX_FILE", - /** USER_PROPERTIES */ - USER_PROPERTIES = "USER_PROPERTIES", - /** ADDITIONAL_ARTIFACTS */ - ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", - /** ZIPPED_ARTIFACTS */ - ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", - /** URL_TEST_CONFIG */ - URL_TEST_CONFIG = "URL_TEST_CONFIG", - /** TEST_SCRIPT */ - TEST_SCRIPT = "TEST_SCRIPT", -} - -/** - * Types of file supported. \ - * {@link KnownFileType} can be used interchangeably with FileType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **JMX_FILE** \ - * **USER_PROPERTIES** \ - * **ADDITIONAL_ARTIFACTS** \ - * **ZIPPED_ARTIFACTS** \ - * **URL_TEST_CONFIG** \ - * **TEST_SCRIPT** - */ -export type FileType = string; - -/** Known values of {@link FileStatus} that the service accepts. */ -export enum KnownFileStatus { - /** NOT_VALIDATED */ - NOT_VALIDATED = "NOT_VALIDATED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", - /** VALIDATION_INITIATED */ - VALIDATION_INITIATED = "VALIDATION_INITIATED", - /** VALIDATION_NOT_REQUIRED */ - VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", -} - -/** - * File status. \ - * {@link KnownFileStatus} can be used interchangeably with FileStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NOT_VALIDATED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** \ - * **VALIDATION_INITIATED** \ - * **VALIDATION_NOT_REQUIRED** - */ -export type FileStatus = string; - -/** Known values of {@link TestKind} that the service accepts. */ -export enum KnownTestKind { - /** URL */ - URL = "URL", - /** JMX */ - JMX = "JMX", - /** Locust */ - Locust = "Locust", -} - -/** - * Test kind \ - * {@link KnownTestKind} can be used interchangeably with TestKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **URL** \ - * **JMX** \ - * **Locust** - */ -export type TestKind = string; - -/** Test app components */ -export interface TestAppComponents { - /** - * Azure resource collection { resource id (fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) - * : resource object } - */ - components: Record; - /** Test identifier */ - readonly testId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testAppComponentsSerializer( - item: TestAppComponents, -): Record { - return { - components: serializeRecord( - item.components as any, - appComponentSerializer, - ) as any, - }; -} - -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ -export interface AppComponent { - /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ - readonly resourceId: string; - /** Azure resource name, required while creating the app component. */ - resourceName: string; - /** Azure resource type, required while creating the app component. */ - resourceType: string; - /** Azure resource display name */ - displayName?: string; - /** Resource group name of the Azure resource */ - readonly resourceGroup?: string; - /** Subscription Id of the Azure resource */ - readonly subscriptionId?: string; - /** Kind of Azure resource type */ - kind?: string; -} - -export function appComponentSerializer( - item: AppComponent, -): Record { - return { - resourceName: item["resourceName"], - resourceType: item["resourceType"], - displayName: item["displayName"], - kind: item["kind"], - }; -} - -/** Test server metrics configuration */ -export interface TestServerMetricConfig { - /** Test identifier */ - readonly testId?: string; - /** - * Azure resource metrics collection {metric id : metrics object} (Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition - * for metric id). - */ - metrics: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testServerMetricConfigSerializer( - item: TestServerMetricConfig, -): Record { - return { - metrics: serializeRecord( - item.metrics as any, - resourceMetricSerializer, - ) as any, - }; -} - -/** - * Associated metric definition for particular metrics of the azure resource ( - * Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition). - */ -export interface ResourceMetric { - /** Unique name for metric. */ - readonly id?: string; - /** Azure resource id. */ - resourceId: string; - /** Metric name space. */ - metricNamespace: string; - /** Metric description. */ - displayDescription?: string; - /** The invariant value of metric name */ - name: string; - /** Metric aggregation. */ - aggregation: string; - /** Metric unit. */ - unit?: string; - /** Azure resource type. */ - resourceType: string; -} - -export function resourceMetricSerializer( - item: ResourceMetric, -): Record { - return { - resourceId: item["resourceId"], - metricNamespace: item["metricNamespace"], - displayDescription: item["displayDescription"], - name: item["name"], - aggregation: item["aggregation"], - unit: item["unit"], - resourceType: item["resourceType"], - }; -} - -/** Azure Load Testing API versions. */ -export type APIVersions = - | "2022-11-01" - | "2023-04-01-preview" - | "2024-03-01-preview" - | "2024-05-01-preview"; - -/** Load test run model */ -export interface TestRun { - /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testRunId: string; - /** Pass fail criteria for a test. */ - passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; - /** - * Secrets can be stored in an Azure Key Vault or any other secret store. If the - * secret is stored in an Azure Key Vault, the value should be the secret - * identifier and the type should be AKV_SECRET_URI. If the secret is stored - * elsewhere, the secret value should be provided directly and the type should be - * SECRET_VALUE. - */ - secrets?: Record; - /** Certificates metadata */ - certificate?: CertificateMetadata; - /** Environment variables which are defined as a set of pairs. */ - environmentVariables?: Record; - /** Error details if there is any failure in load test run */ - readonly errorDetails?: ErrorDetails[]; - /** - * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. - * The sampler name is the same as the name mentioned in the test script. - * Sampler name "Total" represents the aggregated statistics of all the samplers. - */ - readonly testRunStatistics?: Record; - /** - * Regional statistics. Key is the Azure region name and value is the test run statistics. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - readonly regionalStatistics?: Record; - /** The load test configuration. */ - loadTestConfiguration?: LoadTestConfiguration; - /** Collection of test run artifacts */ - readonly testArtifacts?: TestRunArtifacts; - /** Test result for pass/Fail criteria used during the test run. */ - readonly testResult?: PFTestResult; - /** Number of virtual users, for which test has been run. */ - readonly virtualUsers?: number; - /** Display name of a testRun. */ - displayName?: string; - /** Associated test Id. */ - testId?: string; - /** The test run description. */ - description?: string; - /** The test run status. */ - readonly status?: Status; - /** The test run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; - /** Test run initiated time. */ - readonly executedDateTime?: Date; - /** Portal url. */ - readonly portalUrl?: string; - /** Test run duration in milliseconds. */ - readonly duration?: number; - /** Subnet ID on which the load test instances should run. */ - readonly subnetId?: string; - /** Type of test. */ - readonly kind?: TestKind; - /** Request data collection level for test run */ - requestDataLevel?: RequestDataLevel; - /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ - debugLogsEnabled?: boolean; - /** Inject load test engines without deploying public IP for outbound access */ - readonly publicIPDisabled?: boolean; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunSerializer(item: TestRun): Record { - return { - passFailCriteria: !item.passFailCriteria - ? item.passFailCriteria - : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), - secrets: !item.secrets - ? item.secrets - : (serializeRecord(item.secrets as any, secretSerializer) as any), - certificate: !item.certificate - ? item.certificate - : certificateMetadataSerializer(item.certificate), - environmentVariables: !item.environmentVariables - ? item.environmentVariables - : (serializeRecord(item.environmentVariables as any) as any), - loadTestConfiguration: !item.loadTestConfiguration - ? item.loadTestConfiguration - : loadTestConfigurationSerializer(item.loadTestConfiguration), - displayName: item["displayName"], - testId: item["testId"], - description: item["description"], - requestDataLevel: item["requestDataLevel"], - debugLogsEnabled: item["debugLogsEnabled"], - }; -} - -/** Error details if there is any failure in load test run */ -export interface ErrorDetails { - /** Error details in case test run was not successfully run. */ - readonly message?: string; -} - -/** Test run statistics. */ -export interface TestRunStatistics { - /** Transaction name. */ - readonly transaction?: string; - /** Sampler count. */ - readonly sampleCount?: number; - /** Error count. */ - readonly errorCount?: number; - /** Error percentage. */ - readonly errorPct?: number; - /** Mean response time. */ - readonly meanResTime?: number; - /** Median response time. */ - readonly medianResTime?: number; - /** Max response time. */ - readonly maxResTime?: number; - /** Minimum response time. */ - readonly minResTime?: number; - /** 90 percentile response time. */ - readonly pct1ResTime?: number; - /** 95 percentile response time. */ - readonly pct2ResTime?: number; - /** 99 percentile response time. */ - readonly pct3ResTime?: number; - /** 75 percentile response time. */ - readonly pct75ResTime?: number; - /** 96 percentile response time. */ - readonly pct96ResTime?: number; - /** 97 percentile response time. */ - readonly pct97ResTime?: number; - /** 98 percentile response time. */ - readonly pct98ResTime?: number; - /** 99.9 percentile response time. */ - readonly pct999ResTime?: number; - /** 99.99 percentile response time. */ - readonly pct9999ResTime?: number; - /** Throughput. */ - readonly throughput?: number; - /** Received network bytes. */ - readonly receivedKBytesPerSec?: number; - /** Send network bytes. */ - readonly sentKBytesPerSec?: number; -} - -/** Collection of test run artifacts */ -export interface TestRunArtifacts { - /** The input artifacts for the test run. */ - readonly inputArtifacts?: TestRunInputArtifacts; - /** The output artifacts for the test run. */ - outputArtifacts?: TestRunOutputArtifacts; -} - -/** The input artifacts for the test run. */ -export interface TestRunInputArtifacts { - /** File info */ - configFileInfo?: TestRunFileInfo; - /** File info */ - testScriptFileInfo?: TestRunFileInfo; - /** File info */ - userPropFileInfo?: TestRunFileInfo; - /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfo; - /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestRunFileInfo[]; -} - -/** Test run file info. */ -export interface TestRunFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; -} - -/** The output artifacts for the test run. */ -export interface TestRunOutputArtifacts { - /** File info */ - resultFileInfo?: TestRunFileInfo; - /** File info */ - logsFileInfo?: TestRunFileInfo; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfo; - /** The report file for the test run. */ - reportFileInfo?: TestRunFileInfo; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfo { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: Date; -} - -/** Known values of {@link PFTestResult} that the service accepts. */ -export enum KnownPFTestResult { - /** PASSED */ - PASSED = "PASSED", - /** NOT_APPLICABLE */ - NOT_APPLICABLE = "NOT_APPLICABLE", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test result based on pass/fail criteria. \ - * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PASSED** \ - * **NOT_APPLICABLE** \ - * **FAILED** - */ -export type PFTestResult = string; - -/** Known values of {@link Status} that the service accepts. */ -export enum KnownStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** PROVISIONING */ - PROVISIONING = "PROVISIONING", - /** PROVISIONED */ - PROVISIONED = "PROVISIONED", - /** CONFIGURING */ - CONFIGURING = "CONFIGURING", - /** CONFIGURED */ - CONFIGURED = "CONFIGURED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** EXECUTED */ - EXECUTED = "EXECUTED", - /** DEPROVISIONING */ - DEPROVISIONING = "DEPROVISIONING", - /** DEPROVISIONED */ - DEPROVISIONED = "DEPROVISIONED", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", -} - -/** - * Test run status. \ - * {@link KnownStatus} can be used interchangeably with Status, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **PROVISIONING** \ - * **PROVISIONED** \ - * **CONFIGURING** \ - * **CONFIGURED** \ - * **EXECUTING** \ - * **EXECUTED** \ - * **DEPROVISIONING** \ - * **DEPROVISIONED** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** - */ -export type Status = string; - -/** Known values of {@link RequestDataLevel} that the service accepts. */ -export enum KnownRequestDataLevel { - /** NONE */ - NONE = "NONE", - /** ERRORS */ - ERRORS = "ERRORS", -} - -/** - * Request data collection level for test run \ - * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NONE** \ - * **ERRORS** - */ -export type RequestDataLevel = string; - -/** Test run app component */ -export interface TestRunAppComponents { - /** - * Azure resource collection { resource id (fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) - * : resource object } - */ - components: Record; - /** Test run identifier */ - readonly testRunId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunAppComponentsSerializer( - item: TestRunAppComponents, -): Record { - return { - components: serializeRecord( - item.components as any, - appComponentSerializer, - ) as any, - }; -} - -/** Test run server metrics configuration */ -export interface TestRunServerMetricConfig { - /** Test run identifier */ - readonly testRunId?: string; - /** - * Azure resource metrics collection {metric id : metrics object} (Refer : - * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition - * for metric id). - */ - metrics?: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testRunServerMetricConfigSerializer( - item: TestRunServerMetricConfig, -): Record { - return { - metrics: !item.metrics - ? item.metrics - : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), - }; -} - -/** Known values of {@link TimeGrain} that the service accepts. */ -export enum KnownTimeGrain { - /** PT5S */ - PT5S = "PT5S", - /** PT10S */ - PT10S = "PT10S", - /** PT1M */ - PT1M = "PT1M", - /** PT5M */ - PT5M = "PT5M", - /** PT1H */ - PT1H = "PT1H", -} - -/** - * Time Grain \ - * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PT5S** \ - * **PT10S** \ - * **PT1M** \ - * **PT5M** \ - * **PT1H** - */ -export type TimeGrain = string; - -/** Metrics dimension values. */ -export interface DimensionValueList { - /** The dimension name */ - readonly name?: string; - /** The dimension value */ - value?: string[]; - /** Link for the next set of values in case of paginated results, if applicable. */ - nextLink?: string; -} - -/** Represents collection of metric definitions. */ -export interface MetricDefinitionCollection { - /** the values for the metric definitions. */ - value: MetricDefinition[]; -} - -/** Metric definition */ -export interface MetricDefinition { - /** List of dimensions */ - dimensions?: NameAndDesc[]; - /** The metric description */ - description?: string; - /** The metric name */ - name?: string; - /** The namespace the metric belongs to. */ - namespace?: string; - /** The primary aggregation type value defining how to use the values for display. */ - primaryAggregationType?: AggregationType; - /** The collection of what all aggregation types are supported. */ - supportedAggregationTypes?: string[]; - /** The unit of the metric. */ - unit?: MetricUnit; - /** - * Metric availability specifies the time grain (aggregation interval or - * frequency). - */ - metricAvailabilities?: MetricAvailability[]; -} - -/** The name and description */ -export interface NameAndDesc { - /** The description */ - description?: string; - /** The name */ - name?: string; -} - -/** Known values of {@link AggregationType} that the service accepts. */ -export enum KnownAggregationType { - /** Average */ - Average = "Average", - /** Count */ - Count = "Count", - /** None */ - None = "None", - /** Total */ - Total = "Total", - /** Percentile75 */ - Percentile75 = "Percentile75", - /** Percentile90 */ - Percentile90 = "Percentile90", - /** Percentile95 */ - Percentile95 = "Percentile95", - /** Percentile96 */ - Percentile96 = "Percentile96", - /** Percentile97 */ - Percentile97 = "Percentile97", - /** Percentile98 */ - Percentile98 = "Percentile98", - /** Percentile99 */ - Percentile99 = "Percentile99", - /** Percentile999 */ - Percentile999 = "Percentile999", - /** Percentile9999 */ - Percentile9999 = "Percentile9999", -} - -/** - * Aggregation type. \ - * {@link KnownAggregationType} can be used interchangeably with AggregationType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **Average** \ - * **Count** \ - * **None** \ - * **Total** \ - * **Percentile75** \ - * **Percentile90** \ - * **Percentile95** \ - * **Percentile96** \ - * **Percentile97** \ - * **Percentile98** \ - * **Percentile99** \ - * **Percentile999** \ - * **Percentile9999** - */ -export type AggregationType = string; - -/** Known values of {@link MetricUnit} that the service accepts. */ -export enum KnownMetricUnit { - /** NotSpecified */ - NotSpecified = "NotSpecified", - /** Percent */ - Percent = "Percent", - /** Count */ - Count = "Count", - /** Seconds */ - Seconds = "Seconds", - /** Milliseconds */ - Milliseconds = "Milliseconds", - /** Bytes */ - Bytes = "Bytes", - /** BytesPerSecond */ - BytesPerSecond = "BytesPerSecond", - /** CountPerSecond */ - CountPerSecond = "CountPerSecond", -} - -/** - * Metric unit. \ - * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NotSpecified** \ - * **Percent** \ - * **Count** \ - * **Seconds** \ - * **Milliseconds** \ - * **Bytes** \ - * **BytesPerSecond** \ - * **CountPerSecond** - */ -export type MetricUnit = string; - -/** Metric availability specifies the time grain (aggregation interval or frequency) */ -export interface MetricAvailability { - /** - * The time grain specifies the aggregation interval for the metric. Expressed as - * a duration 'PT1M', 'PT1H', etc. - */ - timeGrain?: TimeGrain; -} - -/** Represents collection of metric namespaces. */ -export interface MetricNamespaceCollection { - /** The values for the metric namespaces. */ - value: MetricNamespace[]; -} - -/** Metric namespace class specifies the metadata for a metric namespace. */ -export interface MetricNamespace { - /** The namespace description. */ - description?: string; - /** The metric namespace name. */ - name?: string; -} - -/** Filters to fetch the set of metric. */ -export interface MetricRequestPayload { - /** - * Get metrics for specific dimension values. Example: Metric contains dimension - * like SamplerName, Error. To retrieve all the time series data where SamplerName - * is equals to HTTPRequest1 or HTTPRequest2, the DimensionFilter value will be - * {"SamplerName", ["HTTPRequest1", "HTTPRequest2"} - */ - filters?: DimensionFilter[]; -} - -export function metricRequestPayloadSerializer( - item: MetricRequestPayload, -): Record { - return { - filters: - item["filters"] === undefined - ? item["filters"] - : item["filters"].map(dimensionFilterSerializer), - }; -} - -/** Dimension name and values to filter */ -export interface DimensionFilter { - /** The dimension name */ - name?: string; - /** The dimension values. Maximum values can be 20. */ - values?: string[]; -} - -export function dimensionFilterSerializer( - item: DimensionFilter, -): Record { - return { - name: item["name"], - values: item["values"], - }; -} - -/** The response to a metrics query. */ -export interface _Metrics { - /** The TimeSeriesElement items on this page */ - value: TimeSeriesElement[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** The time series returned when a data query is performed. */ -export interface TimeSeriesElement { - /** An array of data points representing the metric values. */ - data?: MetricValue[]; - /** The dimension values */ - dimensionValues?: DimensionValue[]; -} - -/** Represents a metric value. */ -export interface MetricValue { - /** The timestamp for the metric value in RFC 3339 format. */ - timestamp?: Date; - /** The metric value. */ - value?: number; -} - -/** Represents a metric dimension value. */ -export interface DimensionValue { - /** The name of the dimension. */ - name?: string; - /** The value of the dimension. */ - value?: string; -} - -/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ -export interface TestProfile { - /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileId: string; - /** Display name of the test profile. */ - displayName?: string; - /** Description for the test profile. */ - description?: string; - /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ - testId?: string; - /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ - targetResourceId?: string; - /** Configurations of the target resource on which testing would be done. */ - targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileSerializer( - item: TestProfile, -): Record { - return { - displayName: item["displayName"], - description: item["description"], - testId: item["testId"], - targetResourceId: item["targetResourceId"], - targetResourceConfigurations: !item.targetResourceConfigurations - ? item.targetResourceConfigurations - : targetResourceConfigurationsUnionSerializer( - item.targetResourceConfigurations, - ), - }; -} - -/** Configurations of a target resource. This varies with the kind of resource. */ -export interface TargetResourceConfigurations { - /** the discriminator possible values: FunctionsFlexConsumption */ - kind: ResourceKind; -} - -export function targetResourceConfigurationsUnionSerializer( - item: TargetResourceConfigurationsUnion, -) { - switch (item.kind) { - case "FunctionsFlexConsumption": - return functionFlexConsumptionTargetResourceConfigurationsSerializer( - item as FunctionFlexConsumptionTargetResourceConfigurations, - ); - - default: - return targetResourceConfigurationsSerializer(item); - } -} - -export function targetResourceConfigurationsSerializer( - item: TargetResourceConfigurationsUnion, -): Record { - return { - kind: item["kind"], - }; -} - -/** Configurations for a Function App using Flex Consumption Plan. */ -export interface FunctionFlexConsumptionTargetResourceConfigurations - extends TargetResourceConfigurations { - /** - * The kind value to use when providing configuration. - * This should typically be not changed from its value. - */ - kind: "FunctionsFlexConsumption"; - /** A map of configurations for a Function app using Flex Consumption Plan. */ - configurations?: Record; -} - -export function functionFlexConsumptionTargetResourceConfigurationsSerializer( - item: FunctionFlexConsumptionTargetResourceConfigurations, -): Record { - return { - kind: item["kind"], - configurations: !item.configurations - ? item.configurations - : (serializeRecord( - item.configurations as any, - functionFlexConsumptionResourceConfigurationSerializer, - ) as any), - }; -} - -/** Resource configuration instance for a Flex Consumption based Azure Function App. */ -export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 2048, 4096. */ - instanceMemoryMB: number; - /** HTTP Concurrency for the function app. */ - httpConcurrency: number; -} - -export function functionFlexConsumptionResourceConfigurationSerializer( - item: FunctionFlexConsumptionResourceConfiguration, -): Record { - return { - instanceMemoryMB: item["instanceMemoryMB"], - httpConcurrency: item["httpConcurrency"], - }; -} - -/** Known values of {@link ResourceKind} that the service accepts. */ -export enum KnownResourceKind { - /** FunctionsFlexConsumption */ - FunctionsFlexConsumption = "FunctionsFlexConsumption", -} - -/** - * Kind of the resource on which test profile is created. \ - * {@link KnownResourceKind} can be used interchangeably with ResourceKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **FunctionsFlexConsumption** - */ -export type ResourceKind = string; - -/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ -export interface TestProfileRun { - /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileRunId: string; - /** Display name for the test profile run. */ - displayName?: string; - /** The test profile run description */ - description?: string; - /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ - testProfileId?: string; - /** Target resource ID on which the test profile run is created */ - readonly targetResourceId?: string; - /** Configurations of the target resource on which the test profile ran. */ - readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The test profile run status. */ - readonly status?: TestProfileRunStatus; - /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ - readonly errorDetails?: ErrorDetails[]; - /** The test profile run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test profile run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; - /** Test profile run duration in seconds. */ - readonly durationInSeconds?: number; - /** - * Details of the test runs ran as part of the test profile run. - * Key is the testRunId of the corresponding testRun. - */ - readonly testRunDetails?: Record; - /** Recommendations provided based on a successful test profile run. */ - readonly recommendations?: TestProfileRunRecommendation[]; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileRunSerializer( - item: TestProfileRun, -): Record { - return { - displayName: item["displayName"], - description: item["description"], - testProfileId: item["testProfileId"], - }; -} - -/** Known values of {@link TestProfileRunStatus} that the service accepts. */ -export enum KnownTestProfileRunStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test profile run status. \ - * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **EXECUTING** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** - */ -export type TestProfileRunStatus = string; - -/** Details of a particular test run for a test profile run. */ -export interface TestRunDetail { - /** Status of the test run. */ - status: Status; - /** ID of the configuration on which the test ran. */ - configurationId: string; - /** Key value pair of extra properties associated with the test run. */ - properties: Record; -} - -/** A recommendation object that provides a list of configuration that optimizes its category. */ -export interface TestProfileRunRecommendation { - /** Category of the recommendation. */ - category: RecommendationCategory; - /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ - configurations?: string[]; -} - -/** Known values of {@link RecommendationCategory} that the service accepts. */ -export enum KnownRecommendationCategory { - /** ThroughputOptimized */ - ThroughputOptimized = "ThroughputOptimized", - /** CostOptimized */ - CostOptimized = "CostOptimized", -} - -/** - * Category of Recommendation. \ - * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ThroughputOptimized** \ - * **CostOptimized** - */ -export type RecommendationCategory = string; - -/** Paged collection of TestFileInfo items */ -export interface _PagedTestFileInfo { - /** The TestFileInfo items on this page */ - value: TestFileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of Test items */ -export interface _PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestRun items */ -export interface _PagedTestRun { - /** The TestRun items on this page */ - value: TestRun[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestProfile items */ -export interface _PagedTestProfile { - /** The TestProfile items on this page */ - value: TestProfile[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestProfileRun items */ -export interface _PagedTestProfileRun { - /** The TestProfileRun items on this page */ - value: TestProfileRun[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Alias for TargetResourceConfigurationsUnion */ -export type TargetResourceConfigurationsUnion = - | FunctionFlexConsumptionTargetResourceConfigurations - | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/testProfileRunClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/testProfileRunClient.ts index a0850e876d..ad88265e59 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/testProfileRunClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/testProfileRunClient.ts @@ -1,32 +1,30 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; -import { TestProfileRun } from "./models/models.js"; -import { - CreateOrUpdateTestProfileRunOptionalParams, - DeleteTestProfileRunOptionalParams, - GetTestProfileRunOptionalParams, - ListTestProfileRunsOptionalParams, - StopTestProfileRunOptionalParams, -} from "./models/options.js"; import { createOrUpdateTestProfileRun, deleteTestProfileRun, getTestProfileRun, listTestProfileRuns, stopTestProfileRun, + CreateOrUpdateTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + GetTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + StopTestProfileRunOptionalParams, createTestProfileRun, - LoadTestServiceContext, + TestProfileRunContext, TestProfileRunClientOptionalParams, } from "./api/index.js"; +import { TestProfileRun } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../static-helpers/pagingHelpers.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TokenCredential } from "@azure/core-auth"; export { TestProfileRunClientOptionalParams } from "./api/testProfileRunContext.js"; export class TestProfileRunClient { - private _client: LoadTestServiceContext; + private _client: TestProfileRunContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md b/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md index c238522a63..880f949032 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md @@ -41,26 +41,26 @@ export interface AudioTranslationsOperations { create: (audio: CreateTranslationRequest, options?: AudioTranslationsCreateOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface ChatCompletionFunctionCallOption { name: string; } -// @public (undocumented) +// @public export interface ChatCompletionFunctionParameters extends Record { } -// @public (undocumented) +// @public export interface ChatCompletionFunctions { description?: string; name: string; parameters: ChatCompletionFunctionParameters; } -// @public (undocumented) +// @public export interface ChatCompletionRequestMessage { content: string | null; - functionCall?: { + function_call?: { name: string; arguments: string; }; @@ -68,10 +68,10 @@ export interface ChatCompletionRequestMessage { role: "system" | "user" | "assistant" | "function"; } -// @public (undocumented) +// @public export interface ChatCompletionResponseMessage { content: string | null; - functionCall?: { + function_call?: { name: string; arguments: string; }; @@ -106,26 +106,26 @@ export interface CompletionsOperations { // @public export interface CompletionUsage { - completionTokens: number; - promptTokens: number; - totalTokens: number; + completion_tokens: number; + prompt_tokens: number; + total_tokens: number; } -// @public (undocumented) +// @public export interface CreateChatCompletionRequest { - frequencyPenalty?: number | null; - functionCall?: "none" | "auto" | ChatCompletionFunctionCallOption; + frequency_penalty?: number | null; + function_call?: "none" | "auto" | ChatCompletionFunctionCallOption; functions?: ChatCompletionFunctions[]; - logitBias?: Record | null; - maxTokens?: number | null; + logit_bias?: Record | null; + max_tokens?: number | null; messages: ChatCompletionRequestMessage[]; - model: string | "gpt4" | "gpt-4-0314" | "gpt-4-0613" | "gpt-4-32k" | "gpt-4-32k-0314" | "gpt-4-32k-0613" | "gpt-3.5-turbo" | "gpt-3.5-turbo-16k" | "gpt-3.5-turbo-0301" | "gpt-3.5-turbo-0613" | "gpt-3.5-turbo-16k-0613"; + model: "gpt4" | "gpt-4-0314" | "gpt-4-0613" | "gpt-4-32k" | "gpt-4-32k-0314" | "gpt-4-32k-0613" | "gpt-3.5-turbo" | "gpt-3.5-turbo-16k" | "gpt-3.5-turbo-0301" | "gpt-3.5-turbo-0613" | "gpt-3.5-turbo-16k-0613"; n?: number | null; - presencePenalty?: number | null; - stop?: Stop; + presence_penalty?: number | null; + stop?: Stop_1 | null; stream?: boolean | null; temperature?: number | null; - topP?: number | null; + top_p?: number | null; user?: string; } @@ -134,7 +134,7 @@ export interface CreateChatCompletionResponse { choices: { index: number; message: ChatCompletionResponseMessage; - finishReason: "stop" | "length" | "function_call" | "content_filter"; + finish_reason: "stop" | "length" | "function_call" | "content_filter"; }[]; created: Date; id: string; @@ -144,23 +144,23 @@ export interface CreateChatCompletionResponse { usage?: CompletionUsage; } -// @public (undocumented) +// @public export interface CreateCompletionRequest { - bestOf?: number | null; + best_of?: number | null; echo?: boolean | null; - frequencyPenalty?: number | null; - logitBias?: Record | null; + frequency_penalty?: number | null; + logit_bias?: Record | null; logprobs?: number | null; - maxTokens?: number | null; - model: string | "babbage-002" | "davinci-002" | "text-davinci-003" | "text-davinci-002" | "text-davinci-001" | "code-davinci-002" | "text-curie-001" | "text-babbage-001" | "text-ada-001"; + max_tokens?: number | null; + model: "babbage-002" | "davinci-002" | "text-davinci-003" | "text-davinci-002" | "text-davinci-001" | "code-davinci-002" | "text-curie-001" | "text-babbage-001" | "text-ada-001"; n?: number | null; - presencePenalty?: number | null; - prompt: Prompt; - stop?: Stop; + presence_penalty?: number | null; + prompt: Prompt | null; + stop?: Stop | null; stream?: boolean | null; suffix?: string | null; temperature?: number | null; - topP?: number | null; + top_p?: number | null; user?: string; } @@ -171,11 +171,11 @@ export interface CreateCompletionResponse { text: string; logprobs: { tokens: string[]; - tokenLogprobs: number[]; - topLogprobs: Record[]; - textOffset: number[]; + token_logprobs: number[]; + top_logprobs: Record[]; + text_offset: number[]; } | null; - finishReason: "stop" | "length" | "content_filter"; + finish_reason: "stop" | "length" | "content_filter"; }[]; created: Date; id: string; @@ -185,22 +185,22 @@ export interface CreateCompletionResponse { usage?: CompletionUsage; } -// @public (undocumented) +// @public export interface CreateEditRequest { input?: string | null; instruction: string; - model: string | "text-davinci-edit-001" | "code-davinci-edit-001"; + model: "text-davinci-edit-001" | "code-davinci-edit-001"; n?: number | null; temperature?: number | null; - topP?: number | null; + top_p?: number | null; } -// @public (undocumented) +// @public export interface CreateEditResponse { choices: { text: string; index: number; - finishReason: "stop" | "length"; + finish_reason: "stop" | "length"; }[]; created: Date; object: "edit"; @@ -208,97 +208,97 @@ export interface CreateEditResponse { usage: CompletionUsage; } -// @public (undocumented) +// @public export interface CreateEmbeddingRequest { input: string | string[] | number[] | number[][]; - model: string | "text-embedding-ada-002"; + model: "text-embedding-ada-002"; // (undocumented) user?: string; } -// @public (undocumented) +// @public export interface CreateEmbeddingResponse { data: Embedding[]; model: string; object: "embedding"; usage: { - promptTokens: number; - totalTokens: number; + prompt_tokens: number; + total_tokens: number; }; } -// @public (undocumented) +// @public export interface CreateFileRequest { file: Uint8Array; purpose: string; } -// @public (undocumented) +// @public export interface CreateFineTuneRequest { - batchSize?: number | null; - classificationBetas?: number[] | null; - classificationNClasses?: number | null; - classificationPositiveClass?: string | null; - computeClassificationMetrics?: boolean | null; - learningRateMultiplier?: number | null; - model?: string | "ada" | "babbage" | "curie" | "davinci"; - nEpochs?: number | null; - promptLossRate?: number | null; + batch_size?: number | null; + classification_betas?: number[] | null; + classification_n_classes?: number | null; + classification_positive_class?: string | null; + compute_classification_metrics?: boolean | null; + learning_rate_multiplier?: number | null; + model?: ("ada" | "babbage" | "curie" | "davinci") | null; + n_epochs?: number | null; + prompt_loss_rate?: number | null; suffix?: string | null; - trainingFile: string; - validationFile?: string | null; + training_file: string; + validation_file?: string | null; } -// @public (undocumented) +// @public export interface CreateFineTuningJobRequest { hyperparameters?: { - nEpochs?: "auto" | number; + n_epochs?: "auto" | number; }; - model: string | "babbage-002" | "davinci-002" | "gpt-3.5-turbo"; + model: "babbage-002" | "davinci-002" | "gpt-3.5-turbo"; suffix?: string | null; - trainingFile: string; - validationFile?: string | null; + training_file: string; + validation_file?: string | null; } -// @public (undocumented) +// @public export interface CreateImageEditRequest { image: Uint8Array; mask?: Uint8Array; n?: number | null; prompt: string; - responseFormat?: "url" | "b64_json"; - size?: "256x256" | "512x512" | "1024x1024"; + response_format?: ("url" | "b64_json") | null; + size?: ("256x256" | "512x512" | "1024x1024") | null; // (undocumented) user?: string; } -// @public (undocumented) +// @public export interface CreateImageRequest { n?: number | null; prompt: string; - responseFormat?: "url" | "b64_json"; - size?: "256x256" | "512x512" | "1024x1024"; + response_format?: ("url" | "b64_json") | null; + size?: ("256x256" | "512x512" | "1024x1024") | null; // (undocumented) user?: string; } -// @public (undocumented) +// @public export interface CreateImageVariationRequest { image: Uint8Array; n?: number | null; - responseFormat?: "url" | "b64_json"; - size?: "256x256" | "512x512" | "1024x1024"; + response_format?: ("url" | "b64_json") | null; + size?: ("256x256" | "512x512" | "1024x1024") | null; // (undocumented) user?: string; } -// @public (undocumented) +// @public export interface CreateModerationRequest { input: string | string[]; - model?: string | "text-moderation-latest" | "text-moderation-stable"; + model?: "text-moderation-latest" | "text-moderation-stable"; } -// @public (undocumented) +// @public export interface CreateModerationResponse { id: string; model: string; @@ -309,22 +309,22 @@ export interface CreateModerationResponse { "hate/threatening": boolean; harassment: boolean; "harassment/threatening": boolean; - selfHarm: boolean; - "selfHarm/intent": boolean; - "selfHarm/instructive": boolean; + "self-harm": boolean; + "self-harm/intent": boolean; + "self-harm/instructive": boolean; sexual: boolean; "sexual/minors": boolean; violence: boolean; "violence/graphic": boolean; }; - categoryScores: { + category_scores: { hate: number; "hate/threatening": number; harassment: number; "harassment/threatening": number; - selfHarm: number; - "selfHarm/intent": number; - "selfHarm/instructive": number; + "self-harm": number; + "self-harm/intent": number; + "self-harm/instructive": number; sexual: number; "sexual/minors": number; violence: number; @@ -333,38 +333,38 @@ export interface CreateModerationResponse { }[]; } -// @public (undocumented) +// @public export interface CreateTranscriptionRequest { file: Uint8Array; language?: string; - model: string | "whisper-1"; + model: "whisper-1"; prompt?: string; - responseFormat?: "json" | "text" | "srt" | "verbose_json" | "vtt"; + response_format?: "json" | "text" | "srt" | "verbose_json" | "vtt"; temperature?: number; } -// @public (undocumented) +// @public export interface CreateTranscriptionResponse { // (undocumented) text: string; } -// @public (undocumented) +// @public export interface CreateTranslationRequest { file: Uint8Array; - model: string | "whisper-1"; + model: "whisper-1"; prompt?: string; - responseFormat?: "json" | "text" | "srt" | "verbose_json" | "vtt"; + response_format?: "json" | "text" | "srt" | "verbose_json" | "vtt"; temperature?: number; } -// @public (undocumented) +// @public export interface CreateTranslationResponse { // (undocumented) text: string; } -// @public (undocumented) +// @public export interface DeleteFileResponse { // (undocumented) deleted: boolean; @@ -374,7 +374,7 @@ export interface DeleteFileResponse { object: string; } -// @public (undocumented) +// @public export interface DeleteModelResponse { // (undocumented) deleted: boolean; @@ -411,7 +411,7 @@ export interface EmbeddingsOperations { create: (embedding: CreateEmbeddingRequest, options?: EmbeddingsCreateOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface ErrorModel { // (undocumented) code: string | null; @@ -423,7 +423,7 @@ export interface ErrorModel { type: string; } -// @public (undocumented) +// @public export interface ErrorResponse { // (undocumented) error: ErrorModel; @@ -466,33 +466,33 @@ export interface FilesRetrieveOptionalParams extends OperationOptions { // @public export interface FineTune { - createdAt: Date; + created_at: Date; events?: FineTuneEvent[]; - fineTunedModel: string | null; + fine_tuned_model: string | null; hyperparams: { - nEpochs: number; - batchSize: number; - promptLossWeight: number; - learningRateMultiplier: number; - computeClassificationMetrics?: boolean; - classificationPositiveClass?: string; - classificationNClasses?: number; + n_epochs: number; + batch_size: number; + prompt_loss_weight: number; + learning_rate_multiplier: number; + compute_classification_metrics?: boolean; + classification_positive_class?: string; + classification_n_classes?: number; }; id: string; model: string; object: "fine-tune"; - organizationId: string; - resultFiles: OpenAIFile[]; + organization_id: string; + result_files: OpenAIFile[]; status: "created" | "running" | "succeeded" | "failed" | "cancelled"; - trainingFiles: OpenAIFile[]; - updatedAt: Date; - validationFiles: OpenAIFile[]; + training_files: OpenAIFile[]; + updated_at: Date; + validation_files: OpenAIFile[]; } -// @public (undocumented) +// @public export interface FineTuneEvent { // (undocumented) - createdAt: Date; + created_at: Date; // (undocumented) level: string; // (undocumented) @@ -536,34 +536,34 @@ export interface FineTunesOperations { export interface FineTunesRetrieveOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTuningJob { - createdAt: Date; + created_at: Date; error: { message?: string; code?: string; param?: string | null; } | null; - fineTunedModel: string | null; - finishedAt: Date | null; + fine_tuned_model: string | null; + finished_at: Date | null; hyperparameters: { - nEpochs?: "auto" | number; + n_epochs?: "auto" | number; }; id: string; model: string; object: "fine_tuning.job"; - organizationId: string; - resultFiles: string[]; + organization_id: string; + result_files: string[]; status: "created" | "pending" | "running" | "succeeded" | "failed" | "cancelled"; - trainedTokens: number | null; - trainingFile: string; - validationFile: string | null; + trained_tokens: number | null; + training_file: string; + validation_file: string | null; } -// @public (undocumented) +// @public export interface FineTuningJobEvent { // (undocumented) - createdAt: Date; + created_at: Date; // (undocumented) id: string; // (undocumented) @@ -619,7 +619,7 @@ export interface FineTuningOperations { // @public export interface Image { - b64Json?: Uint8Array; + b64_json?: Uint8Array; url?: string; } @@ -649,7 +649,7 @@ export interface ImagesOperations { createVariation: (image: CreateImageVariationRequest, options?: ImagesCreateVariationOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface ImagesResponse { // (undocumented) created: Date; @@ -657,7 +657,7 @@ export interface ImagesResponse { data: Image[]; } -// @public (undocumented) +// @public export interface ListFilesResponse { // (undocumented) data: OpenAIFile[]; @@ -665,7 +665,7 @@ export interface ListFilesResponse { object: string; } -// @public (undocumented) +// @public export interface ListFineTuneEventsResponse { // (undocumented) data: FineTuneEvent[]; @@ -673,7 +673,7 @@ export interface ListFineTuneEventsResponse { object: string; } -// @public (undocumented) +// @public export interface ListFineTunesResponse { // (undocumented) data: FineTune[]; @@ -681,7 +681,7 @@ export interface ListFineTunesResponse { object: string; } -// @public (undocumented) +// @public export interface ListFineTuningJobEventsResponse { // (undocumented) data: FineTuningJobEvent[]; @@ -689,7 +689,7 @@ export interface ListFineTuningJobEventsResponse { object: string; } -// @public (undocumented) +// @public export interface ListModelsResponse { // (undocumented) data: Model[]; @@ -697,12 +697,12 @@ export interface ListModelsResponse { object: string; } -// @public (undocumented) +// @public export interface ListPaginatedFineTuningJobsResponse { // (undocumented) data: FineTuningJob[]; // (undocumented) - hasMore: boolean; + has_more: boolean; // (undocumented) object: string; } @@ -712,7 +712,7 @@ export interface Model { created: Date; id: string; object: "model"; - ownedBy: string; + owned_by: string; } // @public @@ -776,7 +776,7 @@ export interface OpenAIFile { object: "file"; purpose: string; status: "uploaded" | "processed" | "pending" | "error" | "deleting" | "deleted"; - statusDetails?: string | null; + status_details?: string | null; } // @public @@ -785,6 +785,9 @@ export type Prompt = string | string[] | number[] | number[][]; // @public export type Stop = string | string[]; +// @public +export type Stop_1 = string | string[]; + // (No @packageDocumentation comment for this package) ``` diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/transcriptions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/transcriptions/index.ts index d1f2d68ad5..26ffb3b318 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/transcriptions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/transcriptions/index.ts @@ -1,19 +1,22 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + AudioTranscriptionsCreateOptionalParams, + OpenAIContext as Client, +} from "../../index.js"; import { CreateTranscriptionRequest, + createTranscriptionRequestSerializer, CreateTranscriptionResponse, + createTranscriptionResponseDeserializer, } from "../../../models/models.js"; -import { OpenAIContext as Client } from "../../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { uint8ArrayToString } from "@azure/core-util"; -import { AudioTranscriptionsCreateOptionalParams } from "../../../models/options.js"; export function _createSend( context: Client, @@ -25,14 +28,7 @@ export function _createSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(audio["file"], "base64"), - model: audio["model"], - prompt: audio["prompt"], - response_format: audio["responseFormat"], - temperature: audio["temperature"], - language: audio["language"], - }, + body: createTranscriptionRequestSerializer(audio), }); } @@ -44,9 +40,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - text: result.body["text"], - }; + return createTranscriptionResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/translations/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/translations/index.ts index 4e36cd923f..876f9d3989 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/translations/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/translations/index.ts @@ -1,19 +1,22 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + AudioTranslationsCreateOptionalParams, + OpenAIContext as Client, +} from "../../index.js"; import { CreateTranslationRequest, + createTranslationRequestSerializer, CreateTranslationResponse, + createTranslationResponseDeserializer, } from "../../../models/models.js"; -import { OpenAIContext as Client } from "../../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { uint8ArrayToString } from "@azure/core-util"; -import { AudioTranslationsCreateOptionalParams } from "../../../models/options.js"; export function _createSend( context: Client, @@ -25,13 +28,7 @@ export function _createSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(audio["file"], "base64"), - model: audio["model"], - prompt: audio["prompt"], - response_format: audio["responseFormat"], - temperature: audio["temperature"], - }, + body: createTranslationRequestSerializer(audio), }); } @@ -43,9 +40,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - text: result.body["text"], - }; + return createTranslationResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts index 9ed93e4cec..780f78bc69 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts @@ -2,20 +2,21 @@ // Licensed under the MIT License. import { - chatCompletionRequestMessageSerializer, - chatCompletionFunctionsSerializer, + ChatCompletionsCreateOptionalParams, + OpenAIContext as Client, +} from "../../index.js"; +import { CreateChatCompletionRequest, + createChatCompletionRequestSerializer, CreateChatCompletionResponse, + createChatCompletionResponseDeserializer, } from "../../../models/models.js"; -import { OpenAIContext as Client } from "../../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { serializeRecord } from "../../../helpers/serializerHelpers.js"; -import { ChatCompletionsCreateOptionalParams } from "../../../models/options.js"; export function _createSend( context: Client, @@ -26,27 +27,7 @@ export function _createSend( .path("/chat/completions") .post({ ...operationOptionsToRequestParameters(options), - body: { - model: body["model"], - messages: body["messages"].map(chatCompletionRequestMessageSerializer), - functions: - body["functions"] === undefined - ? body["functions"] - : body["functions"].map(chatCompletionFunctionsSerializer), - function_call: body["functionCall"], - temperature: body["temperature"], - top_p: body["topP"], - n: body["n"], - max_tokens: body["maxTokens"], - stop: body["stop"], - presence_penalty: body["presencePenalty"], - frequency_penalty: body["frequencyPenalty"], - logit_bias: !body.logitBias - ? body.logitBias - : (serializeRecord(body.logitBias as any) as any), - user: body["user"], - stream: body["stream"], - }, + body: createChatCompletionRequestSerializer(body), }); } @@ -58,35 +39,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - created: new Date(result.body["created"]), - model: result.body["model"], - choices: result.body["choices"].map((p: any) => { - return { - index: p["index"], - message: { - role: p.message["role"], - content: p.message["content"], - functionCall: !p.message.function_call - ? undefined - : { - name: p.message.function_call?.["name"], - arguments: p.message.function_call?.["arguments"], - }, - }, - finishReason: p["finish_reason"], - }; - }), - usage: !result.body.usage - ? undefined - : { - promptTokens: result.body.usage?.["prompt_tokens"], - completionTokens: result.body.usage?.["completion_tokens"], - totalTokens: result.body.usage?.["total_tokens"], - }, - }; + return createChatCompletionResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts index d51ee3899c..c30a9b41b5 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts @@ -1,19 +1,22 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + OpenAIContext as Client, + CompletionsCreateOptionalParams, +} from "../index.js"; import { CreateCompletionRequest, + createCompletionRequestSerializer, CreateCompletionResponse, + createCompletionResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { serializeRecord } from "../../helpers/serializerHelpers.js"; -import { CompletionsCreateOptionalParams } from "../../models/options.js"; export function _createSend( context: Client, @@ -24,26 +27,7 @@ export function _createSend( .path("/completions") .post({ ...operationOptionsToRequestParameters(options), - body: { - model: body["model"], - prompt: body["prompt"], - suffix: body["suffix"], - temperature: body["temperature"], - top_p: body["topP"], - n: body["n"], - max_tokens: body["maxTokens"], - stop: body["stop"], - presence_penalty: body["presencePenalty"], - frequency_penalty: body["frequencyPenalty"], - logit_bias: !body.logitBias - ? body.logitBias - : (serializeRecord(body.logitBias as any) as any), - user: body["user"], - stream: body["stream"], - logprobs: body["logprobs"], - echo: body["echo"], - best_of: body["bestOf"], - }, + body: createCompletionRequestSerializer(body), }); } @@ -55,35 +39,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - created: new Date(result.body["created"]), - model: result.body["model"], - choices: result.body["choices"].map((p: any) => { - return { - index: p["index"], - text: p["text"], - logprobs: - p.logprobs === null - ? null - : { - tokens: p.logprobs["tokens"], - tokenLogprobs: p.logprobs["token_logprobs"], - topLogprobs: p.logprobs["top_logprobs"], - textOffset: p.logprobs["text_offset"], - }, - finishReason: p["finish_reason"], - }; - }), - usage: !result.body.usage - ? undefined - : { - promptTokens: result.body.usage?.["prompt_tokens"], - completionTokens: result.body.usage?.["completion_tokens"], - totalTokens: result.body.usage?.["total_tokens"], - }, - }; + return createCompletionResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/edits/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/edits/index.ts index 15bb8dddcf..5d2b38bb1e 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/edits/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/edits/index.ts @@ -1,15 +1,22 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { CreateEditRequest, CreateEditResponse } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; +import { + OpenAIContext as Client, + EditsCreateOptionalParams, +} from "../index.js"; +import { + CreateEditRequest, + createEditRequestSerializer, + CreateEditResponse, + createEditResponseDeserializer, +} from "../../models/models.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { EditsCreateOptionalParams } from "../../models/options.js"; export function _createSend( context: Client, @@ -20,14 +27,7 @@ export function _createSend( .path("/edits") .post({ ...operationOptionsToRequestParameters(options), - body: { - model: edit["model"], - input: edit["input"], - instruction: edit["instruction"], - n: edit["n"], - temperature: edit["temperature"], - top_p: edit["topP"], - }, + body: createEditRequestSerializer(edit), }); } @@ -39,22 +39,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - created: new Date(result.body["created"]), - choices: result.body["choices"].map((p: any) => { - return { - text: p["text"], - index: p["index"], - finishReason: p["finish_reason"], - }; - }), - usage: { - promptTokens: result.body.usage["prompt_tokens"], - completionTokens: result.body.usage["completion_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; + return createEditResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/embeddings/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/embeddings/index.ts index 654f1f6458..ba2da39b80 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/embeddings/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/embeddings/index.ts @@ -1,18 +1,22 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + OpenAIContext as Client, + EmbeddingsCreateOptionalParams, +} from "../index.js"; import { CreateEmbeddingRequest, + createEmbeddingRequestSerializer, CreateEmbeddingResponse, + createEmbeddingResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { EmbeddingsCreateOptionalParams } from "../../models/options.js"; export function _createSend( context: Client, @@ -23,11 +27,7 @@ export function _createSend( .path("/embeddings") .post({ ...operationOptionsToRequestParameters(options), - body: { - model: embedding["model"], - input: embedding["input"], - user: embedding["user"], - }, + body: createEmbeddingRequestSerializer(embedding), }); } @@ -39,21 +39,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - model: result.body["model"], - data: result.body["data"].map((p: any) => { - return { - index: p["index"], - object: p["object"], - embedding: p["embedding"], - }; - }), - usage: { - promptTokens: result.body.usage["prompt_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; + return createEmbeddingResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/files/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/files/index.ts index 29e98543fc..899412257a 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/files/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/files/index.ts @@ -1,27 +1,30 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + OpenAIContext as Client, + FilesCreateOptionalParams, + FilesDeleteOptionalParams, + FilesDownloadOptionalParams, + FilesListOptionalParams, + FilesRetrieveOptionalParams, +} from "../index.js"; import { OpenAIFile, + openAIFileDeserializer, ListFilesResponse, + listFilesResponseDeserializer, CreateFileRequest, + createFileRequestSerializer, DeleteFileResponse, + deleteFileResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { uint8ArrayToString } from "@azure/core-util"; -import { - FilesListOptionalParams, - FilesCreateOptionalParams, - FilesRetrieveOptionalParams, - FilesDeleteOptionalParams, - FilesDownloadOptionalParams, -} from "../../models/options.js"; export function _listSend( context: Client, @@ -40,21 +43,7 @@ export async function _listDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - }; + return listFilesResponseDeserializer(result.body); } export async function list( @@ -75,10 +64,7 @@ export function _createSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(file["file"], "base64"), - purpose: file["purpose"], - }, + body: createFileRequestSerializer(file), }); } @@ -90,16 +76,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - bytes: result.body["bytes"], - createdAt: new Date(result.body["createdAt"]), - filename: result.body["filename"], - purpose: result.body["purpose"], - status: result.body["status"], - statusDetails: result.body["status_details"], - }; + return openAIFileDeserializer(result.body); } export async function create( @@ -129,16 +106,7 @@ export async function _retrieveDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - bytes: result.body["bytes"], - createdAt: new Date(result.body["createdAt"]), - filename: result.body["filename"], - purpose: result.body["purpose"], - status: result.body["status"], - statusDetails: result.body["status_details"], - }; + return openAIFileDeserializer(result.body); } export async function retrieve( @@ -168,11 +136,7 @@ export async function _$deleteDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - deleted: result.body["deleted"], - }; + return deleteFileResponseDeserializer(result.body); } /** diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTunes/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTunes/index.ts index f3199e58bd..aa5de3fc20 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTunes/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTunes/index.ts @@ -1,26 +1,30 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + OpenAIContext as Client, + FineTunesCancelOptionalParams, + FineTunesCreateOptionalParams, + FineTunesListEventsOptionalParams, + FineTunesListOptionalParams, + FineTunesRetrieveOptionalParams, +} from "../index.js"; import { CreateFineTuneRequest, + createFineTuneRequestSerializer, FineTune, + fineTuneDeserializer, ListFineTunesResponse, + listFineTunesResponseDeserializer, ListFineTuneEventsResponse, + listFineTuneEventsResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { - FineTunesCreateOptionalParams, - FineTunesListOptionalParams, - FineTunesRetrieveOptionalParams, - FineTunesListEventsOptionalParams, - FineTunesCancelOptionalParams, -} from "../../models/options.js"; export function _createSend( context: Client, @@ -31,21 +35,7 @@ export function _createSend( .path("/fine-tunes") .post({ ...operationOptionsToRequestParameters(options), - body: { - training_file: fineTune["trainingFile"], - validation_file: fineTune["validationFile"], - model: fineTune["model"], - n_epochs: fineTune["nEpochs"], - batch_size: fineTune["batchSize"], - learning_rate_multiplier: fineTune["learningRateMultiplier"], - prompt_loss_rate: fineTune["promptLossRate"], - compute_classification_metrics: - fineTune["computeClassificationMetrics"], - classification_n_classes: fineTune["classificationNClasses"], - classification_positive_class: fineTune["classificationPositiveClass"], - classification_betas: fineTune["classificationBetas"], - suffix: fineTune["suffix"], - }, + body: createFineTuneRequestSerializer(fineTune), }); } @@ -57,76 +47,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - updatedAt: new Date(result.body["updated_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparams: { - nEpochs: result.body.hyperparams["n_epochs"], - batchSize: result.body.hyperparams["batch_size"], - promptLossWeight: result.body.hyperparams["prompt_loss_weight"], - learningRateMultiplier: - result.body.hyperparams["learning_rate_multiplier"], - computeClassificationMetrics: - result.body.hyperparams["compute_classification_metrics"], - classificationPositiveClass: - result.body.hyperparams["classification_positive_class"], - classificationNClasses: - result.body.hyperparams["classification_n_classes"], - }, - trainingFiles: result.body["training_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - validationFiles: result.body["validation_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - resultFiles: result.body["result_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - events: - result.body["events"] === undefined - ? result.body["events"] - : result.body["events"].map((p: any) => { - return { - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; + return fineTuneDeserializer(result.body); } export async function create( @@ -155,79 +76,7 @@ export async function _listDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - createdAt: new Date(p["created_at"]), - updatedAt: new Date(p["updated_at"]), - model: p["model"], - fineTunedModel: p["fine_tuned_model"], - organizationId: p["organization_id"], - status: p["status"], - hyperparams: { - nEpochs: p.hyperparams["n_epochs"], - batchSize: p.hyperparams["batch_size"], - promptLossWeight: p.hyperparams["prompt_loss_weight"], - learningRateMultiplier: p.hyperparams["learning_rate_multiplier"], - computeClassificationMetrics: - p.hyperparams["compute_classification_metrics"], - classificationPositiveClass: - p.hyperparams["classification_positive_class"], - classificationNClasses: p.hyperparams["classification_n_classes"], - }, - trainingFiles: p["training_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - validationFiles: p["validation_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - resultFiles: p["result_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - events: - p["events"] === undefined - ? p["events"] - : p["events"].map((p: any) => { - return { - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; - }), - }; + return listFineTunesResponseDeserializer(result.body); } export async function list( @@ -256,76 +105,7 @@ export async function _retrieveDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - updatedAt: new Date(result.body["updated_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparams: { - nEpochs: result.body.hyperparams["n_epochs"], - batchSize: result.body.hyperparams["batch_size"], - promptLossWeight: result.body.hyperparams["prompt_loss_weight"], - learningRateMultiplier: - result.body.hyperparams["learning_rate_multiplier"], - computeClassificationMetrics: - result.body.hyperparams["compute_classification_metrics"], - classificationPositiveClass: - result.body.hyperparams["classification_positive_class"], - classificationNClasses: - result.body.hyperparams["classification_n_classes"], - }, - trainingFiles: result.body["training_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - validationFiles: result.body["validation_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - resultFiles: result.body["result_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - events: - result.body["events"] === undefined - ? result.body["events"] - : result.body["events"].map((p: any) => { - return { - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; + return fineTuneDeserializer(result.body); } export async function retrieve( @@ -358,17 +138,7 @@ export async function _listEventsDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; + return listFineTuneEventsResponseDeserializer(result.body); } export async function listEvents( @@ -398,76 +168,7 @@ export async function _cancelDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - updatedAt: new Date(result.body["updated_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparams: { - nEpochs: result.body.hyperparams["n_epochs"], - batchSize: result.body.hyperparams["batch_size"], - promptLossWeight: result.body.hyperparams["prompt_loss_weight"], - learningRateMultiplier: - result.body.hyperparams["learning_rate_multiplier"], - computeClassificationMetrics: - result.body.hyperparams["compute_classification_metrics"], - classificationPositiveClass: - result.body.hyperparams["classification_positive_class"], - classificationNClasses: - result.body.hyperparams["classification_n_classes"], - }, - trainingFiles: result.body["training_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - validationFiles: result.body["validation_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - resultFiles: result.body["result_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - events: - result.body["events"] === undefined - ? result.body["events"] - : result.body["events"].map((p: any) => { - return { - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; + return fineTuneDeserializer(result.body); } export async function cancel( diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTuning/jobs/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTuning/jobs/index.ts index 33ee6b05c1..07d9c5e064 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTuning/jobs/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTuning/jobs/index.ts @@ -1,26 +1,30 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + OpenAIContext as Client, + FineTuningJobsCancelOptionalParams, + FineTuningJobsCreateOptionalParams, + FineTuningJobsListEventsOptionalParams, + FineTuningJobsListOptionalParams, + FineTuningJobsRetrieveOptionalParams, +} from "../../index.js"; import { CreateFineTuningJobRequest, + createFineTuningJobRequestSerializer, FineTuningJob, + fineTuningJobDeserializer, ListPaginatedFineTuningJobsResponse, + listPaginatedFineTuningJobsResponseDeserializer, ListFineTuningJobEventsResponse, + listFineTuningJobEventsResponseDeserializer, } from "../../../models/models.js"; -import { OpenAIContext as Client } from "../../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { - FineTuningJobsCreateOptionalParams, - FineTuningJobsListOptionalParams, - FineTuningJobsRetrieveOptionalParams, - FineTuningJobsListEventsOptionalParams, - FineTuningJobsCancelOptionalParams, -} from "../../../models/options.js"; export function _createSend( context: Client, @@ -31,15 +35,7 @@ export function _createSend( .path("/fine_tuning/jobs") .post({ ...operationOptionsToRequestParameters(options), - body: { - training_file: job["trainingFile"], - validation_file: job["validationFile"], - model: job["model"], - hyperparameters: !job.hyperparameters - ? undefined - : { n_epochs: job.hyperparameters?.["nEpochs"] }, - suffix: job["suffix"], - }, + body: createFineTuningJobRequestSerializer(job), }); } @@ -51,32 +47,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - finishedAt: - result.body["finished_at"] === null - ? null - : new Date(result.body["finished_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparameters: { nEpochs: result.body.hyperparameters["n_epochs"] }, - trainingFile: result.body["training_file"], - validationFile: result.body["validation_file"], - resultFiles: result.body["result_files"], - trainedTokens: result.body["trained_tokens"], - error: - result.body.error === null - ? null - : { - message: result.body.error["message"], - code: result.body.error["code"], - param: result.body.error["param"], - }, - }; + return fineTuningJobDeserializer(result.body); } /** @@ -116,36 +87,7 @@ export async function _listDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - createdAt: new Date(p["created_at"]), - finishedAt: - p["finished_at"] === null ? null : new Date(p["finished_at"]), - model: p["model"], - fineTunedModel: p["fine_tuned_model"], - organizationId: p["organization_id"], - status: p["status"], - hyperparameters: { nEpochs: p.hyperparameters["n_epochs"] }, - trainingFile: p["training_file"], - validationFile: p["validation_file"], - resultFiles: p["result_files"], - trainedTokens: p["trained_tokens"], - error: - p.error === null - ? null - : { - message: p.error["message"], - code: p.error["code"], - param: p.error["param"], - }, - }; - }), - hasMore: result.body["has_more"], - }; + return listPaginatedFineTuningJobsResponseDeserializer(result.body); } export async function list( @@ -174,32 +116,7 @@ export async function _retrieveDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - finishedAt: - result.body["finished_at"] === null - ? null - : new Date(result.body["finished_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparameters: { nEpochs: result.body.hyperparameters["n_epochs"] }, - trainingFile: result.body["training_file"], - validationFile: result.body["validation_file"], - resultFiles: result.body["result_files"], - trainedTokens: result.body["trained_tokens"], - error: - result.body.error === null - ? null - : { - message: result.body.error["message"], - code: result.body.error["code"], - param: result.body.error["param"], - }, - }; + return fineTuningJobDeserializer(result.body); } export async function retrieve( @@ -232,18 +149,7 @@ export async function _listEventsDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; + return listFineTuningJobEventsResponseDeserializer(result.body); } export async function listEvents( @@ -273,32 +179,7 @@ export async function _cancelDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - finishedAt: - result.body["finished_at"] === null - ? null - : new Date(result.body["finished_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparameters: { nEpochs: result.body.hyperparameters["n_epochs"] }, - trainingFile: result.body["training_file"], - validationFile: result.body["validation_file"], - resultFiles: result.body["result_files"], - trainedTokens: result.body["trained_tokens"], - error: - result.body.error === null - ? null - : { - message: result.body.error["message"], - code: result.body.error["code"], - param: result.body.error["param"], - }, - }; + return fineTuningJobDeserializer(result.body); } export async function cancel( diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/images/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/images/index.ts index c8a4dee2d2..edb0ad1832 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/images/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/images/index.ts @@ -1,25 +1,28 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + OpenAIContext as Client, + ImagesCreateEditOptionalParams, + ImagesCreateOptionalParams, + ImagesCreateVariationOptionalParams, +} from "../index.js"; import { CreateImageRequest, + createImageRequestSerializer, ImagesResponse, + imagesResponseDeserializer, CreateImageEditRequest, + createImageEditRequestSerializer, CreateImageVariationRequest, + createImageVariationRequestSerializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; -import { - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, - ImagesCreateVariationOptionalParams, -} from "../../models/options.js"; export function _createSend( context: Client, @@ -30,13 +33,7 @@ export function _createSend( .path("/images/generations") .post({ ...operationOptionsToRequestParameters(options), - body: { - prompt: image["prompt"], - n: image["n"], - size: image["size"], - response_format: image["responseFormat"], - user: image["user"], - }, + body: createImageRequestSerializer(image), }); } @@ -48,18 +45,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - created: new Date(result.body["created"]), - data: result.body["data"].map((p: any) => { - return { - url: p["url"], - b64Json: - typeof p["b64_json"] === "string" - ? stringToUint8Array(p["b64_json"], "base64") - : p["b64_json"], - }; - }), - }; + return imagesResponseDeserializer(result.body); } export async function create( @@ -81,18 +67,7 @@ export function _createEditSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - prompt: image["prompt"], - image: uint8ArrayToString(image["image"], "base64"), - mask: - image["mask"] !== undefined - ? uint8ArrayToString(image["mask"], "base64") - : undefined, - n: image["n"], - size: image["size"], - response_format: image["responseFormat"], - user: image["user"], - }, + body: createImageEditRequestSerializer(image), }); } @@ -104,18 +79,7 @@ export async function _createEditDeserialize( throw createRestError(result); } - return { - created: new Date(result.body["created"]), - data: result.body["data"].map((p: any) => { - return { - url: p["url"], - b64Json: - typeof p["b64_json"] === "string" - ? stringToUint8Array(p["b64_json"], "base64") - : p["b64_json"], - }; - }), - }; + return imagesResponseDeserializer(result.body); } export async function createEdit( @@ -137,13 +101,7 @@ export function _createVariationSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - image: uint8ArrayToString(image["image"], "base64"), - n: image["n"], - size: image["size"], - response_format: image["responseFormat"], - user: image["user"], - }, + body: createImageVariationRequestSerializer(image), }); } @@ -155,18 +113,7 @@ export async function _createVariationDeserialize( throw createRestError(result); } - return { - created: new Date(result.body["created"]), - data: result.body["data"].map((p: any) => { - return { - url: p["url"], - b64Json: - typeof p["b64_json"] === "string" - ? stringToUint8Array(p["b64_json"], "base64") - : p["b64_json"], - }; - }), - }; + return imagesResponseDeserializer(result.body); } export async function createVariation( diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/index.ts index 1541bfeba2..2f0d3bb507 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/index.ts @@ -6,3 +6,33 @@ export { OpenAIContext, OpenAIClientOptionalParams, } from "./openAIContext.js"; +export { + AudioTranscriptionsCreateOptionalParams, + AudioTranslationsCreateOptionalParams, + ChatCompletionsCreateOptionalParams, + FineTuningJobsCreateOptionalParams, + FineTuningJobsListOptionalParams, + FineTuningJobsRetrieveOptionalParams, + FineTuningJobsListEventsOptionalParams, + FineTuningJobsCancelOptionalParams, + CompletionsCreateOptionalParams, + EditsCreateOptionalParams, + EmbeddingsCreateOptionalParams, + FilesListOptionalParams, + FilesCreateOptionalParams, + FilesRetrieveOptionalParams, + FilesDeleteOptionalParams, + FilesDownloadOptionalParams, + FineTunesCreateOptionalParams, + FineTunesListOptionalParams, + FineTunesRetrieveOptionalParams, + FineTunesListEventsOptionalParams, + FineTunesCancelOptionalParams, + ModelsListOptionalParams, + ModelsRetrieveOptionalParams, + ModelsDeleteOptionalParams, + ImagesCreateOptionalParams, + ImagesCreateEditOptionalParams, + ImagesCreateVariationOptionalParams, + ModerationsCreateOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/models/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/models/index.ts index 1dbe82ea8c..1192f91414 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/models/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/models/index.ts @@ -1,23 +1,26 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + OpenAIContext as Client, + ModelsDeleteOptionalParams, + ModelsListOptionalParams, + ModelsRetrieveOptionalParams, +} from "../index.js"; import { ListModelsResponse, + listModelsResponseDeserializer, Model, + modelDeserializer, DeleteModelResponse, + deleteModelResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { - ModelsListOptionalParams, - ModelsRetrieveOptionalParams, - ModelsDeleteOptionalParams, -} from "../../models/options.js"; export function _listSend( context: Client, @@ -36,17 +39,7 @@ export async function _listDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - created: new Date(p["created"]), - ownedBy: p["owned_by"], - }; - }), - }; + return listModelsResponseDeserializer(result.body); } export async function list( @@ -75,12 +68,7 @@ export async function _retrieveDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - created: new Date(result.body["created"]), - ownedBy: result.body["owned_by"], - }; + return modelDeserializer(result.body); } export async function retrieve( @@ -110,11 +98,7 @@ export async function _$deleteDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - deleted: result.body["deleted"], - }; + return deleteModelResponseDeserializer(result.body); } /** diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/moderations/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/moderations/index.ts index 48788fbcad..b8bbbdc014 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/moderations/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/moderations/index.ts @@ -1,18 +1,22 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + OpenAIContext as Client, + ModerationsCreateOptionalParams, +} from "../index.js"; import { CreateModerationRequest, + createModerationRequestSerializer, CreateModerationResponse, + createModerationResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { ModerationsCreateOptionalParams } from "../../models/options.js"; export function _createSend( context: Client, @@ -23,7 +27,7 @@ export function _createSend( .path("/moderations") .post({ ...operationOptionsToRequestParameters(options), - body: { input: content["input"], model: content["model"] }, + body: createModerationRequestSerializer(content), }); } @@ -35,41 +39,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - model: result.body["model"], - results: result.body["results"].map((p: any) => { - return { - flagged: p["flagged"], - categories: { - hate: p.categories["hate"], - "hate/threatening": p.categories["hate/threatening"], - harassment: p.categories["harassment"], - "harassment/threatening": p.categories["harassment/threatening"], - selfHarm: p.categories["self-harm"], - "selfHarm/intent": p.categories["self-harm/intent"], - "selfHarm/instructive": p.categories["self-harm/instructive"], - sexual: p.categories["sexual"], - "sexual/minors": p.categories["sexual/minors"], - violence: p.categories["violence"], - "violence/graphic": p.categories["violence/graphic"], - }, - categoryScores: { - hate: p.category_scores["hate"], - "hate/threatening": p.category_scores["hate/threatening"], - harassment: p.category_scores["harassment"], - "harassment/threatening": p.category_scores["harassment/threatening"], - selfHarm: p.category_scores["self-harm"], - "selfHarm/intent": p.category_scores["self-harm/intent"], - "selfHarm/instructive": p.category_scores["self-harm/instructive"], - sexual: p.category_scores["sexual"], - "sexual/minors": p.category_scores["sexual/minors"], - violence: p.category_scores["violence"], - "violence/graphic": p.category_scores["violence/graphic"], - }, - }; - }), - }; + return createModerationResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts index d5d867077d..c3fd4009de 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { KeyCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; -import { isKeyCredential } from "@azure/core-auth"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { KeyCredential, isKeyCredential } from "@azure/core-auth"; +/** The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details. */ export interface OpenAIContext extends Client {} /** Optional parameters for the client. */ diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/transcriptions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/transcriptions/index.ts index 1f8b191982..8bcb7743fa 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/transcriptions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/transcriptions/index.ts @@ -2,12 +2,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../../api/openAIContext.js"; +import { create } from "../../../api/audio/transcriptions/index.js"; +import { AudioTranscriptionsCreateOptionalParams } from "../../../api/options.js"; import { CreateTranscriptionRequest, CreateTranscriptionResponse, } from "../../../models/models.js"; -import { create } from "../../../api/audio/transcriptions/index.js"; -import { AudioTranscriptionsCreateOptionalParams } from "../../../models/options.js"; /** Interface representing a AudioTranscriptions operations. */ export interface AudioTranscriptionsOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/translations/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/translations/index.ts index c19293a689..33b7b2498e 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/translations/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/translations/index.ts @@ -2,12 +2,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../../api/openAIContext.js"; +import { create } from "../../../api/audio/translations/index.js"; +import { AudioTranslationsCreateOptionalParams } from "../../../api/options.js"; import { CreateTranslationRequest, CreateTranslationResponse, } from "../../../models/models.js"; -import { create } from "../../../api/audio/translations/index.js"; -import { AudioTranslationsCreateOptionalParams } from "../../../models/options.js"; /** Interface representing a AudioTranslations operations. */ export interface AudioTranslationsOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/completions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/completions/index.ts index e497c94b5b..65541432b4 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/completions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/completions/index.ts @@ -2,12 +2,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../../api/openAIContext.js"; +import { create } from "../../../api/chat/completions/index.js"; +import { ChatCompletionsCreateOptionalParams } from "../../../api/options.js"; import { CreateChatCompletionRequest, CreateChatCompletionResponse, } from "../../../models/models.js"; -import { create } from "../../../api/chat/completions/index.js"; -import { ChatCompletionsCreateOptionalParams } from "../../../models/options.js"; /** Interface representing a ChatCompletions operations. */ export interface ChatCompletionsOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/completions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/completions/index.ts index ab138f6377..55c2aa082d 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/completions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/completions/index.ts @@ -2,12 +2,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; +import { create } from "../../api/completions/index.js"; +import { CompletionsCreateOptionalParams } from "../../api/options.js"; import { CreateCompletionRequest, CreateCompletionResponse, } from "../../models/models.js"; -import { create } from "../../api/completions/index.js"; -import { CompletionsCreateOptionalParams } from "../../models/options.js"; /** Interface representing a Completions operations. */ export interface CompletionsOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/edits/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/edits/index.ts index 04b344d185..e56d78ba9f 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/edits/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/edits/index.ts @@ -2,9 +2,9 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { CreateEditRequest, CreateEditResponse } from "../../models/models.js"; import { create } from "../../api/edits/index.js"; -import { EditsCreateOptionalParams } from "../../models/options.js"; +import { EditsCreateOptionalParams } from "../../api/options.js"; +import { CreateEditRequest, CreateEditResponse } from "../../models/models.js"; /** Interface representing a Edits operations. */ export interface EditsOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/embeddings/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/embeddings/index.ts index cdfdd4e495..6c35f0a9d8 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/embeddings/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/embeddings/index.ts @@ -2,12 +2,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; +import { create } from "../../api/embeddings/index.js"; +import { EmbeddingsCreateOptionalParams } from "../../api/options.js"; import { CreateEmbeddingRequest, CreateEmbeddingResponse, } from "../../models/models.js"; -import { create } from "../../api/embeddings/index.js"; -import { EmbeddingsCreateOptionalParams } from "../../models/options.js"; /** Interface representing a Embeddings operations. */ export interface EmbeddingsOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts index 3e9ec06b49..d7996abe49 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts @@ -2,12 +2,6 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { - OpenAIFile, - ListFilesResponse, - CreateFileRequest, - DeleteFileResponse, -} from "../../models/models.js"; import { list, create, @@ -21,7 +15,13 @@ import { FilesRetrieveOptionalParams, FilesDeleteOptionalParams, FilesDownloadOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; +import { + ListFilesResponse, + CreateFileRequest, + OpenAIFile, + DeleteFileResponse, +} from "../../models/models.js"; /** Interface representing a Files operations. */ export interface FilesOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts index ee2d184dae..17c0cc5071 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts @@ -2,12 +2,6 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { - CreateFineTuneRequest, - FineTune, - ListFineTunesResponse, - ListFineTuneEventsResponse, -} from "../../models/models.js"; import { create, list, @@ -21,7 +15,13 @@ import { FineTunesRetrieveOptionalParams, FineTunesListEventsOptionalParams, FineTunesCancelOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; +import { + CreateFineTuneRequest, + FineTune, + ListFineTunesResponse, + ListFineTuneEventsResponse, +} from "../../models/models.js"; /** Interface representing a FineTunes operations. */ export interface FineTunesOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts index 695001d171..f31081a07b 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts @@ -2,12 +2,6 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../../api/openAIContext.js"; -import { - CreateFineTuningJobRequest, - FineTuningJob, - ListPaginatedFineTuningJobsResponse, - ListFineTuningJobEventsResponse, -} from "../../../models/models.js"; import { create, list, @@ -21,7 +15,13 @@ import { FineTuningJobsRetrieveOptionalParams, FineTuningJobsListEventsOptionalParams, FineTuningJobsCancelOptionalParams, -} from "../../../models/options.js"; +} from "../../../api/options.js"; +import { + CreateFineTuningJobRequest, + FineTuningJob, + ListPaginatedFineTuningJobsResponse, + ListFineTuningJobEventsResponse, +} from "../../../models/models.js"; /** Interface representing a FineTuningJobs operations. */ export interface FineTuningJobsOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts index d6b6e2da67..fc1d3b2aa9 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts @@ -2,18 +2,18 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; +import { create, createEdit, createVariation } from "../../api/images/index.js"; +import { + ImagesCreateOptionalParams, + ImagesCreateEditOptionalParams, + ImagesCreateVariationOptionalParams, +} from "../../api/options.js"; import { CreateImageRequest, ImagesResponse, CreateImageEditRequest, CreateImageVariationRequest, } from "../../models/models.js"; -import { create, createEdit, createVariation } from "../../api/images/index.js"; -import { - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, - ImagesCreateVariationOptionalParams, -} from "../../models/options.js"; /** Interface representing a Images operations. */ export interface ImagesOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts index afceb8df16..c0556a1b74 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts @@ -2,17 +2,17 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { - ListModelsResponse, - Model, - DeleteModelResponse, -} from "../../models/models.js"; import { list, retrieve, $delete } from "../../api/models/index.js"; import { ModelsListOptionalParams, ModelsRetrieveOptionalParams, ModelsDeleteOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; +import { + ListModelsResponse, + Model, + DeleteModelResponse, +} from "../../models/models.js"; /** Interface representing a Models operations. */ export interface ModelsOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/moderations/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/moderations/index.ts index e7c1250473..f89bec51a9 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/moderations/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/moderations/index.ts @@ -2,12 +2,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; +import { create } from "../../api/moderations/index.js"; +import { ModerationsCreateOptionalParams } from "../../api/options.js"; import { CreateModerationRequest, CreateModerationResponse, } from "../../models/models.js"; -import { create } from "../../api/moderations/index.js"; -import { ModerationsCreateOptionalParams } from "../../models/options.js"; /** Interface representing a Moderations operations. */ export interface ModerationsOperations { diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/index.ts index 268ea380e9..f313205ae6 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/index.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -export { OpenAIClient, OpenAIClientOptionalParams } from "./openAIClient.js"; +export { OpenAIClient } from "./openAIClient.js"; export { CreateModerationRequest, CreateModerationResponse, @@ -31,6 +31,8 @@ export { CreateEditResponse, CompletionUsage, CreateCompletionRequest, + Prompt, + Stop, CreateCompletionResponse, CreateFineTuningJobRequest, FineTuningJob, @@ -42,14 +44,16 @@ export { ChatCompletionFunctions, ChatCompletionFunctionParameters, ChatCompletionFunctionCallOption, + Stop_1, CreateChatCompletionResponse, ChatCompletionResponseMessage, CreateTranslationRequest, CreateTranslationResponse, CreateTranscriptionRequest, CreateTranscriptionResponse, - Prompt, - Stop, +} from "./models/index.js"; +export { + OpenAIClientOptionalParams, AudioTranscriptionsCreateOptionalParams, AudioTranslationsCreateOptionalParams, ChatCompletionsCreateOptionalParams, @@ -78,7 +82,7 @@ export { ImagesCreateEditOptionalParams, ImagesCreateVariationOptionalParams, ModerationsCreateOptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; export { AudioOperations, ChatOperations, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/index.ts index 25ef6dc7b8..c6775fe0ff 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/index.ts @@ -30,6 +30,8 @@ export { CreateEditResponse, CompletionUsage, CreateCompletionRequest, + Prompt, + Stop, CreateCompletionResponse, CreateFineTuningJobRequest, FineTuningJob, @@ -41,42 +43,11 @@ export { ChatCompletionFunctions, ChatCompletionFunctionParameters, ChatCompletionFunctionCallOption, + Stop_1, CreateChatCompletionResponse, ChatCompletionResponseMessage, CreateTranslationRequest, CreateTranslationResponse, CreateTranscriptionRequest, CreateTranscriptionResponse, - Prompt, - Stop, } from "./models.js"; -export { - AudioTranscriptionsCreateOptionalParams, - AudioTranslationsCreateOptionalParams, - ChatCompletionsCreateOptionalParams, - FineTuningJobsCreateOptionalParams, - FineTuningJobsListOptionalParams, - FineTuningJobsRetrieveOptionalParams, - FineTuningJobsListEventsOptionalParams, - FineTuningJobsCancelOptionalParams, - CompletionsCreateOptionalParams, - EditsCreateOptionalParams, - EmbeddingsCreateOptionalParams, - FilesListOptionalParams, - FilesCreateOptionalParams, - FilesRetrieveOptionalParams, - FilesDeleteOptionalParams, - FilesDownloadOptionalParams, - FineTunesCreateOptionalParams, - FineTunesListOptionalParams, - FineTunesRetrieveOptionalParams, - FineTunesListEventsOptionalParams, - FineTunesCancelOptionalParams, - ModelsListOptionalParams, - ModelsRetrieveOptionalParams, - ModelsDeleteOptionalParams, - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, - ImagesCreateVariationOptionalParams, - ModerationsCreateOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts index 8db42d6190..c19c8565ed 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { serializeRecord } from "../helpers/serializerHelpers.js"; -import { uint8ArrayToString } from "@azure/core-util"; +import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; +/** model interface CreateModerationRequest */ export interface CreateModerationRequest { /** The input text to classify */ input: string | string[]; @@ -14,18 +14,34 @@ export interface CreateModerationRequest { * `text-moderation-stable`, we will provide advanced notice before updating the model. Accuracy * of `text-moderation-stable` may be slightly lower than for `text-moderation-latest`. */ - model?: string | "text-moderation-latest" | "text-moderation-stable"; + model?: "text-moderation-latest" | "text-moderation-stable"; } export function createModerationRequestSerializer( item: CreateModerationRequest, -): Record { +): any { return { - input: item["input"], + input: _createModerationRequestInputSerializer(item["input"]), model: item["model"], }; } +/** Alias for _CreateModerationRequestInput */ +export type _CreateModerationRequestInput = string | string[]; + +export function _createModerationRequestInputSerializer( + item: _CreateModerationRequestInput, +): any { + return item; +} + +export function _createModerationRequestInputDeserializer( + item: any, +): _CreateModerationRequestInput { + return item; +} + +/** model interface CreateModerationResponse */ export interface CreateModerationResponse { /** The unique identifier for the moderation request. */ id: string; @@ -39,22 +55,22 @@ export interface CreateModerationResponse { "hate/threatening": boolean; harassment: boolean; "harassment/threatening": boolean; - selfHarm: boolean; - "selfHarm/intent": boolean; - "selfHarm/instructive": boolean; + "self-harm": boolean; + "self-harm/intent": boolean; + "self-harm/instructive": boolean; sexual: boolean; "sexual/minors": boolean; violence: boolean; "violence/graphic": boolean; }; - categoryScores: { + category_scores: { hate: number; "hate/threatening": number; harassment: number; "harassment/threatening": number; - selfHarm: number; - "selfHarm/intent": number; - "selfHarm/instructive": number; + "self-harm": number; + "self-harm/intent": number; + "self-harm/instructive": number; sexual: number; "sexual/minors": number; violence: number; @@ -63,10 +79,192 @@ export interface CreateModerationResponse { }[]; } +export function createModerationResponseDeserializer( + item: any, +): CreateModerationResponse { + return { + id: item["id"], + model: item["model"], + results: createModerationResponseResultArrayDeserializer(item["results"]), + }; +} + +/** model interface _CreateModerationResponseResult */ +export interface _CreateModerationResponseResult { + /** Whether the content violates [OpenAI's usage policies](/policies/usage-policies). */ + flagged: boolean; + /** A list of the categories, and whether they are flagged or not. */ + categories: { + hate: boolean; + "hate/threatening": boolean; + harassment: boolean; + "harassment/threatening": boolean; + "self-harm": boolean; + "self-harm/intent": boolean; + "self-harm/instructive": boolean; + sexual: boolean; + "sexual/minors": boolean; + violence: boolean; + "violence/graphic": boolean; + }; + /** A list of the categories along with their scores as predicted by model. */ + category_scores: { + hate: number; + "hate/threatening": number; + harassment: number; + "harassment/threatening": number; + "self-harm": number; + "self-harm/intent": number; + "self-harm/instructive": number; + sexual: number; + "sexual/minors": number; + violence: number; + "violence/graphic": number; + }; +} + +export function _createModerationResponseResultDeserializer( + item: any, +): _CreateModerationResponseResult { + return { + flagged: item["flagged"], + categories: _createModerationResponseResultCategoriesDeserializer( + item["categories"], + ), + category_scores: _createModerationResponseResultCategoryScoresDeserializer( + item["category_scores"], + ), + }; +} + +/** model interface _CreateModerationResponseResultCategories */ +export interface _CreateModerationResponseResultCategories { + /** + * Content that expresses, incites, or promotes hate based on race, gender, ethnicity, + * religion, nationality, sexual orientation, disability status, or caste. Hateful content + * aimed at non-protected groups (e.g., chess players) is harrassment. + */ + hate: boolean; + /** + * Hateful content that also includes violence or serious harm towards the targeted group + * based on race, gender, ethnicity, religion, nationality, sexual orientation, disability + * status, or caste. + */ + "hate/threatening": boolean; + /** Content that expresses, incites, or promotes harassing language towards any target. */ + harassment: boolean; + /** Harassment content that also includes violence or serious harm towards any target. */ + "harassment/threatening": boolean; + /** + * Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, + * and eating disorders. + */ + "self-harm": boolean; + /** + * Content where the speaker expresses that they are engaging or intend to engage in acts of + * self-harm, such as suicide, cutting, and eating disorders. + */ + "self-harm/intent": boolean; + /** + * Content that encourages performing acts of self-harm, such as suicide, cutting, and eating + * disorders, or that gives instructions or advice on how to commit such acts. + */ + "self-harm/instructive": boolean; + /** + * Content meant to arouse sexual excitement, such as the description of sexual activity, or + * that promotes sexual services (excluding sex education and wellness). + */ + sexual: boolean; + /** Sexual content that includes an individual who is under 18 years old. */ + "sexual/minors": boolean; + /** Content that depicts death, violence, or physical injury. */ + violence: boolean; + /** Content that depicts death, violence, or physical injury in graphic detail. */ + "violence/graphic": boolean; +} + +export function _createModerationResponseResultCategoriesDeserializer( + item: any, +): _CreateModerationResponseResultCategories { + return { + hate: item["hate"], + "hate/threatening": item["hate/threatening"], + harassment: item["harassment"], + "harassment/threatening": item["harassment/threatening"], + "self-harm": item["self-harm"], + "self-harm/intent": item["self-harm/intent"], + "self-harm/instructive": item["self-harm/instructive"], + sexual: item["sexual"], + "sexual/minors": item["sexual/minors"], + violence: item["violence"], + "violence/graphic": item["violence/graphic"], + }; +} + +/** model interface _CreateModerationResponseResultCategoryScores */ +export interface _CreateModerationResponseResultCategoryScores { + /** The score for the category 'hate'. */ + hate: number; + /** The score for the category 'hate/threatening'. */ + "hate/threatening": number; + /** The score for the category 'harassment'. */ + harassment: number; + /** The score for the category 'harassment/threatening'. */ + "harassment/threatening": number; + /** The score for the category 'self-harm'. */ + "self-harm": number; + /** The score for the category 'self-harm/intent'. */ + "self-harm/intent": number; + /** The score for the category 'self-harm/instructive'. */ + "self-harm/instructive": number; + /** The score for the category 'sexual'. */ + sexual: number; + /** The score for the category 'sexual/minors'. */ + "sexual/minors": number; + /** The score for the category 'violence'. */ + violence: number; + /** The score for the category 'violence/graphic'. */ + "violence/graphic": number; +} + +export function _createModerationResponseResultCategoryScoresDeserializer( + item: any, +): _CreateModerationResponseResultCategoryScores { + return { + hate: item["hate"], + "hate/threatening": item["hate/threatening"], + harassment: item["harassment"], + "harassment/threatening": item["harassment/threatening"], + "self-harm": item["self-harm"], + "self-harm/intent": item["self-harm/intent"], + "self-harm/instructive": item["self-harm/instructive"], + sexual: item["sexual"], + "sexual/minors": item["sexual/minors"], + violence: item["violence"], + "violence/graphic": item["violence/graphic"], + }; +} + +export function createModerationResponseResultArrayDeserializer( + result: Array<_CreateModerationResponseResult>, +): any[] { + return result.map((item) => { + return _createModerationResponseResultDeserializer(item); + }); +} + +/** model interface ErrorResponse */ export interface ErrorResponse { error: ErrorModel; } +export function errorResponseDeserializer(item: any): ErrorResponse { + return { + error: errorDeserializer(item["error"]), + }; +} + +/** model interface ErrorModel */ export interface ErrorModel { type: string; message: string; @@ -74,43 +272,77 @@ export interface ErrorModel { code: string | null; } +export function errorDeserializer(item: any): ErrorModel { + return { + type: item["type"], + message: item["message"], + param: item["param"], + code: item["code"], + }; +} + +/** model interface CreateImageRequest */ export interface CreateImageRequest { /** A text description of the desired image(s). The maximum length is 1000 characters. */ prompt: string; /** The number of images to generate. Must be between 1 and 10. */ n?: number | null; /** The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. */ - size?: "256x256" | "512x512" | "1024x1024"; + size?: ("256x256" | "512x512" | "1024x1024") | null; /** The format in which the generated images are returned. Must be one of `url` or `b64_json`. */ - responseFormat?: "url" | "b64_json"; + response_format?: ("url" | "b64_json") | null; user?: string; } -export function createImageRequestSerializer( - item: CreateImageRequest, -): Record { +export function createImageRequestSerializer(item: CreateImageRequest): any { return { prompt: item["prompt"], n: item["n"], size: item["size"], - response_format: item["responseFormat"], + response_format: item["response_format"], user: item["user"], }; } +/** model interface ImagesResponse */ export interface ImagesResponse { created: Date; data: Image[]; } +export function imagesResponseDeserializer(item: any): ImagesResponse { + return { + created: new Date(item["created"]), + data: imageArrayDeserializer(item["data"]), + }; +} + /** Represents the url or the content of an image generated by the OpenAI API. */ export interface Image { /** The URL of the generated image, if `response_format` is `url` (default). */ url?: string; /** The base64-encoded JSON of the generated image, if `response_format` is `b64_json`. */ - b64Json?: Uint8Array; + b64_json?: Uint8Array; +} + +export function imageDeserializer(item: any): Image { + return { + url: item["url"], + b64_json: !item["b64_json"] + ? item["b64_json"] + : typeof item["b64_json"] === "string" + ? stringToUint8Array(item["b64_json"], "base64") + : item["b64_json"], + }; } +export function imageArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return imageDeserializer(item); + }); +} + +/** model interface CreateImageEditRequest */ export interface CreateImageEditRequest { /** A text description of the desired image(s). The maximum length is 1000 characters. */ prompt: string; @@ -128,29 +360,29 @@ export interface CreateImageEditRequest { /** The number of images to generate. Must be between 1 and 10. */ n?: number | null; /** The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. */ - size?: "256x256" | "512x512" | "1024x1024"; + size?: ("256x256" | "512x512" | "1024x1024") | null; /** The format in which the generated images are returned. Must be one of `url` or `b64_json`. */ - responseFormat?: "url" | "b64_json"; + response_format?: ("url" | "b64_json") | null; user?: string; } export function createImageEditRequestSerializer( item: CreateImageEditRequest, -): Record { +): any { return { prompt: item["prompt"], image: uint8ArrayToString(item["image"], "base64"), - mask: - item["mask"] !== undefined - ? uint8ArrayToString(item["mask"], "base64") - : undefined, + mask: !item["mask"] + ? item["mask"] + : uint8ArrayToString(item["mask"], "base64"), n: item["n"], size: item["size"], - response_format: item["responseFormat"], + response_format: item["response_format"], user: item["user"], }; } +/** model interface CreateImageVariationRequest */ export interface CreateImageVariationRequest { /** * The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, @@ -160,29 +392,37 @@ export interface CreateImageVariationRequest { /** The number of images to generate. Must be between 1 and 10. */ n?: number | null; /** The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. */ - size?: "256x256" | "512x512" | "1024x1024"; + size?: ("256x256" | "512x512" | "1024x1024") | null; /** The format in which the generated images are returned. Must be one of `url` or `b64_json`. */ - responseFormat?: "url" | "b64_json"; + response_format?: ("url" | "b64_json") | null; user?: string; } export function createImageVariationRequestSerializer( item: CreateImageVariationRequest, -): Record { +): any { return { image: uint8ArrayToString(item["image"], "base64"), n: item["n"], size: item["size"], - response_format: item["responseFormat"], + response_format: item["response_format"], user: item["user"], }; } +/** model interface ListModelsResponse */ export interface ListModelsResponse { object: string; data: Model[]; } +export function listModelsResponseDeserializer(item: any): ListModelsResponse { + return { + object: item["object"], + data: modelArrayDeserializer(item["data"]), + }; +} + /** Describes an OpenAI model offering that can be used with the API. */ export interface Model { /** The model identifier, which can be referenced in the API endpoints. */ @@ -192,15 +432,42 @@ export interface Model { /** The Unix timestamp (in seconds) when the model was created. */ created: Date; /** The organization that owns the model. */ - ownedBy: string; + owned_by: string; +} + +export function modelDeserializer(item: any): Model { + return { + id: item["id"], + object: item["object"], + created: new Date(item["created"]), + owned_by: item["owned_by"], + }; } +export function modelArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return modelDeserializer(item); + }); +} + +/** model interface DeleteModelResponse */ export interface DeleteModelResponse { id: string; object: string; deleted: boolean; } +export function deleteModelResponseDeserializer( + item: any, +): DeleteModelResponse { + return { + id: item["id"], + object: item["object"], + deleted: item["deleted"], + }; +} + +/** model interface CreateFineTuneRequest */ export interface CreateFineTuneRequest { /** * The ID of an uploaded file that contains training data. @@ -214,7 +481,7 @@ export interface CreateFineTuneRequest { * See the [fine-tuning guide](/docs/guides/legacy-fine-tuning/creating-training-data) for more * details. */ - trainingFile: string; + training_file: string; /** * The ID of an uploaded file that contains validation data. * @@ -230,18 +497,18 @@ export interface CreateFineTuneRequest { * See the [fine-tuning guide](/docs/guides/legacy-fine-tuning/creating-training-data) for more * details. */ - validationFile?: string | null; + validation_file?: string | null; /** * The name of the base model to fine-tune. You can select one of "ada", "babbage", "curie", * "davinci", or a fine-tuned model created after 2022-04-21 and before 2023-08-22. To learn more * about these models, see the [Models](/docs/models) documentation. */ - model?: string | "ada" | "babbage" | "curie" | "davinci"; + model?: ("ada" | "babbage" | "curie" | "davinci") | null; /** * The number of epochs to train the model for. An epoch refers to one full cycle through the * training dataset. */ - nEpochs?: number | null; + n_epochs?: number | null; /** * The batch size to use for training. The batch size is the number of training examples used to * train a single forward and backward pass. @@ -250,7 +517,7 @@ export interface CreateFineTuneRequest { * in the training set, capped at 256 - in general, we've found that larger batch sizes tend to * work better for larger datasets. */ - batchSize?: number | null; + batch_size?: number | null; /** * The learning rate multiplier to use for training. The fine-tuning learning rate is the original * learning rate used for pretraining multiplied by this value. @@ -260,7 +527,7 @@ export interface CreateFineTuneRequest { * recommend experimenting with values in the range 0.02 to 0.2 to see what produces the best * results. */ - learningRateMultiplier?: number | null; + learning_rate_multiplier?: number | null; /** * The weight to use for loss on the prompt tokens. This controls how much the model tries to * learn to generate the prompt (as compared to the completion which always has a weight of 1.0), @@ -269,7 +536,7 @@ export interface CreateFineTuneRequest { * If prompts are extremely long (relative to completions), it may make sense to reduce this * weight so as to avoid over-prioritizing learning the prompt. */ - promptLossRate?: number | null; + prompt_loss_rate?: number | null; /** * If set, we calculate classification-specific metrics such as accuracy and F-1 score using the * validation set at the end of every epoch. These metrics can be viewed in the @@ -279,20 +546,20 @@ export interface CreateFineTuneRequest { * you must specify `classification_n_classes` for multiclass classification or * `classification_positive_class` for binary classification. */ - computeClassificationMetrics?: boolean | null; + compute_classification_metrics?: boolean | null; /** * The number of classes in a classification task. * * This parameter is required for multiclass classification. */ - classificationNClasses?: number | null; + classification_n_classes?: number | null; /** * The positive class in binary classification. * * This parameter is needed to generate precision, recall, and F1 metrics when doing binary * classification. */ - classificationPositiveClass?: string | null; + classification_positive_class?: string | null; /** * If this is provided, we calculate F-beta scores at the specified beta values. The F-beta score * is a generalization of F-1 score. This is only used for binary classification. @@ -301,7 +568,7 @@ export interface CreateFineTuneRequest { * beta score puts more weight on recall and less on precision. A smaller beta score puts more * weight on precision and less on recall. */ - classificationBetas?: number[] | null; + classification_betas?: number[] | null; /** * A string of up to 18 characters that will be added to your fine-tuned model name. * @@ -313,19 +580,23 @@ export interface CreateFineTuneRequest { export function createFineTuneRequestSerializer( item: CreateFineTuneRequest, -): Record { +): any { return { - training_file: item["trainingFile"], - validation_file: item["validationFile"], + training_file: item["training_file"], + validation_file: item["validation_file"], model: item["model"], - n_epochs: item["nEpochs"], - batch_size: item["batchSize"], - learning_rate_multiplier: item["learningRateMultiplier"], - prompt_loss_rate: item["promptLossRate"], - compute_classification_metrics: item["computeClassificationMetrics"], - classification_n_classes: item["classificationNClasses"], - classification_positive_class: item["classificationPositiveClass"], - classification_betas: item["classificationBetas"], + n_epochs: item["n_epochs"], + batch_size: item["batch_size"], + learning_rate_multiplier: item["learning_rate_multiplier"], + prompt_loss_rate: item["prompt_loss_rate"], + compute_classification_metrics: item["compute_classification_metrics"], + classification_n_classes: item["classification_n_classes"], + classification_positive_class: item["classification_positive_class"], + classification_betas: !item["classification_betas"] + ? item["classification_betas"] + : item["classification_betas"].map((p: any) => { + return p; + }), suffix: item["suffix"], }; } @@ -337,15 +608,15 @@ export interface FineTune { /** The object type, which is always "fine-tune". */ object: "fine-tune"; /** The Unix timestamp (in seconds) for when the fine-tuning job was created. */ - createdAt: Date; + created_at: Date; /** The Unix timestamp (in seconds) for when the fine-tuning job was last updated. */ - updatedAt: Date; + updated_at: Date; /** The base model that is being fine-tuned. */ model: string; /** The name of the fine-tuned model that is being created. */ - fineTunedModel: string | null; + fine_tuned_model: string | null; /** The organization that owns the fine-tuning job. */ - organizationId: string; + organization_id: string; /** * The current status of the fine-tuning job, which can be either `created`, `running`, * `succeeded`, `failed`, or `cancelled`. @@ -356,24 +627,82 @@ export interface FineTune { * [fine-tuning guide](/docs/guides/legacy-fine-tuning/hyperparameters) for more details. */ hyperparams: { - nEpochs: number; - batchSize: number; - promptLossWeight: number; - learningRateMultiplier: number; - computeClassificationMetrics?: boolean; - classificationPositiveClass?: string; - classificationNClasses?: number; + n_epochs: number; + batch_size: number; + prompt_loss_weight: number; + learning_rate_multiplier: number; + compute_classification_metrics?: boolean; + classification_positive_class?: string; + classification_n_classes?: number; }; /** The list of files used for training. */ - trainingFiles: OpenAIFile[]; + training_files: OpenAIFile[]; /** The list of files used for validation. */ - validationFiles: OpenAIFile[]; + validation_files: OpenAIFile[]; /** The compiled results files for the fine-tuning job. */ - resultFiles: OpenAIFile[]; + result_files: OpenAIFile[]; /** The list of events that have been observed in the lifecycle of the FineTune job. */ events?: FineTuneEvent[]; } +export function fineTuneDeserializer(item: any): FineTune { + return { + id: item["id"], + object: item["object"], + created_at: new Date(item["created_at"]), + updated_at: new Date(item["updated_at"]), + model: item["model"], + fine_tuned_model: item["fine_tuned_model"], + organization_id: item["organization_id"], + status: item["status"], + hyperparams: _fineTuneHyperparamsDeserializer(item["hyperparams"]), + training_files: openAIFileArrayDeserializer(item["training_files"]), + validation_files: openAIFileArrayDeserializer(item["validation_files"]), + result_files: openAIFileArrayDeserializer(item["result_files"]), + events: !item["events"] + ? item["events"] + : fineTuneEventArrayDeserializer(item["events"]), + }; +} + +/** model interface _FineTuneHyperparams */ +export interface _FineTuneHyperparams { + /** + * The number of epochs to train the model for. An epoch refers to one full cycle through the + * training dataset. + */ + n_epochs: number; + /** + * The batch size to use for training. The batch size is the number of training examples used to + * train a single forward and backward pass. + */ + batch_size: number; + /** The weight to use for loss on the prompt tokens. */ + prompt_loss_weight: number; + /** The learning rate multiplier to use for training. */ + learning_rate_multiplier: number; + /** The classification metrics to compute using the validation dataset at the end of every epoch. */ + compute_classification_metrics?: boolean; + /** The positive class to use for computing classification metrics. */ + classification_positive_class?: string; + /** The number of classes to use for computing classification metrics. */ + classification_n_classes?: number; +} + +export function _fineTuneHyperparamsDeserializer( + item: any, +): _FineTuneHyperparams { + return { + n_epochs: item["n_epochs"], + batch_size: item["batch_size"], + prompt_loss_weight: item["prompt_loss_weight"], + learning_rate_multiplier: item["learning_rate_multiplier"], + compute_classification_metrics: item["compute_classification_metrics"], + classification_positive_class: item["classification_positive_class"], + classification_n_classes: item["classification_n_classes"], + }; +} + /** The `File` object represents a document that has been uploaded to OpenAI. */ export interface OpenAIFile { /** The file identifier, which can be referenced in the API endpoints. */ @@ -403,31 +732,103 @@ export interface OpenAIFile { * Additional details about the status of the file. If the file is in the `error` state, this will * include a message describing the error. */ - statusDetails?: string | null; + status_details?: string | null; +} + +export function openAIFileDeserializer(item: any): OpenAIFile { + return { + id: item["id"], + object: item["object"], + bytes: item["bytes"], + createdAt: new Date(item["createdAt"]), + filename: item["filename"], + purpose: item["purpose"], + status: item["status"], + status_details: item["status_details"], + }; +} + +export function openAIFileArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return openAIFileDeserializer(item); + }); } +/** model interface FineTuneEvent */ export interface FineTuneEvent { object: string; - createdAt: Date; + created_at: Date; level: string; message: string; } +export function fineTuneEventDeserializer(item: any): FineTuneEvent { + return { + object: item["object"], + created_at: new Date(item["created_at"]), + level: item["level"], + message: item["message"], + }; +} + +export function fineTuneEventArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return fineTuneEventDeserializer(item); + }); +} + +/** model interface ListFineTunesResponse */ export interface ListFineTunesResponse { object: string; data: FineTune[]; } +export function listFineTunesResponseDeserializer( + item: any, +): ListFineTunesResponse { + return { + object: item["object"], + data: fineTuneArrayDeserializer(item["data"]), + }; +} + +export function fineTuneArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return fineTuneDeserializer(item); + }); +} + +/** model interface ListFineTuneEventsResponse */ export interface ListFineTuneEventsResponse { object: string; data: FineTuneEvent[]; } +export function listFineTuneEventsResponseDeserializer( + item: any, +): ListFineTuneEventsResponse { + return { + object: item["object"], + data: fineTuneEventArrayDeserializer(item["data"]), + }; +} + +/** model interface ListFilesResponse */ export interface ListFilesResponse { object: string; data: OpenAIFile[]; } +export function listFilesResponseDeserializer(item: any): ListFilesResponse { + return { + object: item["object"], + data: openAIFileArrayDeserializer(item["data"]), + }; +} + +/** model interface CreateFileRequest */ export interface CreateFileRequest { /** * Name of the [JSON Lines](https://jsonlines.readthedocs.io/en/latest/) file to be uploaded. @@ -443,24 +844,32 @@ export interface CreateFileRequest { purpose: string; } -export function createFileRequestSerializer( - item: CreateFileRequest, -): Record { +export function createFileRequestSerializer(item: CreateFileRequest): any { return { file: uint8ArrayToString(item["file"], "base64"), purpose: item["purpose"], }; } +/** model interface DeleteFileResponse */ export interface DeleteFileResponse { id: string; object: string; deleted: boolean; } +export function deleteFileResponseDeserializer(item: any): DeleteFileResponse { + return { + id: item["id"], + object: item["object"], + deleted: item["deleted"], + }; +} + +/** model interface CreateEmbeddingRequest */ export interface CreateEmbeddingRequest { /** ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them. */ - model: string | "text-embedding-ada-002"; + model: "text-embedding-ada-002"; /** * Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a * single request, pass an array of strings or array of token arrays. Each input must not exceed @@ -474,14 +883,34 @@ export interface CreateEmbeddingRequest { export function createEmbeddingRequestSerializer( item: CreateEmbeddingRequest, -): Record { +): any { return { model: item["model"], - input: item["input"], + input: _createEmbeddingRequestInputSerializer(item["input"]), user: item["user"], }; } +/** Alias for _CreateEmbeddingRequestInput */ +export type _CreateEmbeddingRequestInput = + | string + | string[] + | number[] + | number[][]; + +export function _createEmbeddingRequestInputSerializer( + item: _CreateEmbeddingRequestInput, +): any { + return item; +} + +export function _createEmbeddingRequestInputDeserializer( + item: any, +): _CreateEmbeddingRequestInput { + return item; +} + +/** model interface CreateEmbeddingResponse */ export interface CreateEmbeddingResponse { /** The object type, which is always "embedding". */ object: "embedding"; @@ -490,7 +919,21 @@ export interface CreateEmbeddingResponse { /** The list of embeddings generated by the model. */ data: Embedding[]; /** The usage information for the request. */ - usage: { promptTokens: number; totalTokens: number }; + usage: { + prompt_tokens: number; + total_tokens: number; + }; +} + +export function createEmbeddingResponseDeserializer( + item: any, +): CreateEmbeddingResponse { + return { + object: item["object"], + model: item["model"], + data: embeddingArrayDeserializer(item["data"]), + usage: _createEmbeddingResponseUsageDeserializer(item["usage"]), + }; } /** Represents an embedding vector returned by embedding endpoint. */ @@ -506,12 +949,46 @@ export interface Embedding { embedding: number[]; } +export function embeddingDeserializer(item: any): Embedding { + return { + index: item["index"], + object: item["object"], + embedding: item["embedding"].map((p: any) => { + return p; + }), + }; +} + +export function embeddingArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return embeddingDeserializer(item); + }); +} + +/** model interface _CreateEmbeddingResponseUsage */ +export interface _CreateEmbeddingResponseUsage { + /** The number of tokens used by the prompt. */ + prompt_tokens: number; + /** The total number of tokens used by the request. */ + total_tokens: number; +} + +export function _createEmbeddingResponseUsageDeserializer( + item: any, +): _CreateEmbeddingResponseUsage { + return { + prompt_tokens: item["prompt_tokens"], + total_tokens: item["total_tokens"], + }; +} + +/** model interface CreateEditRequest */ export interface CreateEditRequest { /** * ID of the model to use. You can use the `text-davinci-edit-001` or `code-davinci-edit-001` * model with this endpoint. */ - model: string | "text-davinci-edit-001" | "code-davinci-edit-001"; + model: "text-davinci-edit-001" | "code-davinci-edit-001"; /** The input text to use as a starting point for the edit. */ input?: string | null; /** The instruction that tells the model how to edit the prompt. */ @@ -532,42 +1009,95 @@ export interface CreateEditRequest { * * We generally recommend altering this or `temperature` but not both. */ - topP?: number | null; + top_p?: number | null; } -export function createEditRequestSerializer( - item: CreateEditRequest, -): Record { +export function createEditRequestSerializer(item: CreateEditRequest): any { return { model: item["model"], input: item["input"], instruction: item["instruction"], n: item["n"], temperature: item["temperature"], - top_p: item["topP"], + top_p: item["top_p"], }; } +/** model interface CreateEditResponse */ export interface CreateEditResponse { /** The object type, which is always `edit`. */ object: "edit"; /** The Unix timestamp (in seconds) of when the edit was created. */ created: Date; /** description: A list of edit choices. Can be more than one if `n` is greater than 1. */ - choices: { text: string; index: number; finishReason: "stop" | "length" }[]; + choices: { + text: string; + index: number; + finish_reason: "stop" | "length"; + }[]; usage: CompletionUsage; } +export function createEditResponseDeserializer(item: any): CreateEditResponse { + return { + object: item["object"], + created: new Date(item["created"]), + choices: createEditResponseChoiceArrayDeserializer(item["choices"]), + usage: completionUsageDeserializer(item["usage"]), + }; +} + +/** model interface _CreateEditResponseChoice */ +export interface _CreateEditResponseChoice { + /** The edited result. */ + text: string; + /** The index of the choice in the list of choices. */ + index: number; + /** + * The reason the model stopped generating tokens. This will be `stop` if the model hit a + * natural stop point or a provided stop sequence, or `length` if the maximum number of tokens + * specified in the request was reached. + */ + finish_reason: "stop" | "length"; +} + +export function _createEditResponseChoiceDeserializer( + item: any, +): _CreateEditResponseChoice { + return { + text: item["text"], + index: item["index"], + finish_reason: item["finish_reason"], + }; +} + +export function createEditResponseChoiceArrayDeserializer( + result: Array<_CreateEditResponseChoice>, +): any[] { + return result.map((item) => { + return _createEditResponseChoiceDeserializer(item); + }); +} + /** Usage statistics for the completion request. */ export interface CompletionUsage { /** Number of tokens in the prompt. */ - promptTokens: number; + prompt_tokens: number; /** Number of tokens in the generated completion */ - completionTokens: number; + completion_tokens: number; /** Total number of tokens used in the request (prompt + completion). */ - totalTokens: number; + total_tokens: number; +} + +export function completionUsageDeserializer(item: any): CompletionUsage { + return { + prompt_tokens: item["prompt_tokens"], + completion_tokens: item["completion_tokens"], + total_tokens: item["total_tokens"], + }; } +/** model interface CreateCompletionRequest */ export interface CreateCompletionRequest { /** * ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to @@ -575,7 +1105,6 @@ export interface CreateCompletionRequest { * descriptions of them. */ model: - | string | "babbage-002" | "davinci-002" | "text-davinci-003" @@ -592,7 +1121,7 @@ export interface CreateCompletionRequest { * Note that <|endoftext|> is the document separator that the model sees during training, so if a * prompt is not specified the model will generate as if from the beginning of a new document. */ - prompt: Prompt; + prompt: Prompt | null; /** The suffix that comes after a completion of inserted text. */ suffix?: string | null; /** @@ -609,7 +1138,7 @@ export interface CreateCompletionRequest { * * We generally recommend altering this or `temperature` but not both. */ - topP?: number | null; + top_p?: number | null; /** * How many completions to generate for each prompt. * **Note:** Because this parameter generates many completions, it can quickly consume your token @@ -623,16 +1152,16 @@ export interface CreateCompletionRequest { * [Example Python code](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb) * for counting tokens. */ - maxTokens?: number | null; + max_tokens?: number | null; /** Up to 4 sequences where the API will stop generating further tokens. */ - stop?: Stop; + stop?: Stop | null; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear * in the text so far, increasing the model's likelihood to talk about new topics. * * [See more information about frequency and presence penalties.](/docs/guides/gpt/parameter-details) */ - presencePenalty?: number | null; + presence_penalty?: number | null; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing * frequency in the text so far, decreasing the model's likelihood to repeat the same line @@ -640,7 +1169,7 @@ export interface CreateCompletionRequest { * * [See more information about frequency and presence penalties.](/docs/guides/gpt/parameter-details) */ - frequencyPenalty?: number | null; + frequency_penalty?: number | null; /** * Modify the likelihood of specified tokens appearing in the completion. * Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an @@ -649,7 +1178,7 @@ export interface CreateCompletionRequest { * between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 * should result in a ban or exclusive selection of the relevant token. */ - logitBias?: Record | null; + logit_bias?: Record | null; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect * abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). @@ -683,34 +1212,54 @@ export interface CreateCompletionRequest { * **Note:** Because this parameter generates many completions, it can quickly consume your token * quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. */ - bestOf?: number | null; + best_of?: number | null; } export function createCompletionRequestSerializer( item: CreateCompletionRequest, -): Record { +): any { return { model: item["model"], prompt: item["prompt"], suffix: item["suffix"], temperature: item["temperature"], - top_p: item["topP"], + top_p: item["top_p"], n: item["n"], - max_tokens: item["maxTokens"], + max_tokens: item["max_tokens"], stop: item["stop"], - presence_penalty: item["presencePenalty"], - frequency_penalty: item["frequencyPenalty"], - logit_bias: !item.logitBias - ? item.logitBias - : (serializeRecord(item.logitBias as any) as any), + presence_penalty: item["presence_penalty"], + frequency_penalty: item["frequency_penalty"], + logit_bias: item["logit_bias"], user: item["user"], stream: item["stream"], logprobs: item["logprobs"], echo: item["echo"], - best_of: item["bestOf"], + best_of: item["best_of"], }; } +/** Alias for Prompt */ +export type Prompt = string | string[] | number[] | number[][]; + +export function promptSerializer(item: Prompt): any { + return item; +} + +export function promptDeserializer(item: any): Prompt { + return item; +} + +/** Alias for Stop */ +export type Stop = string | string[]; + +export function stopSerializer(item: Stop): any { + return item; +} + +export function stopDeserializer(item: any): Stop { + return item; +} + /** * Represents a completion response from the API. Note: both the streamed and non-streamed response * objects share the same shape (unlike the chat endpoint). @@ -730,15 +1279,97 @@ export interface CreateCompletionResponse { text: string; logprobs: { tokens: string[]; - tokenLogprobs: number[]; - topLogprobs: Record[]; - textOffset: number[]; + token_logprobs: number[]; + top_logprobs: Record[]; + text_offset: number[]; } | null; - finishReason: "stop" | "length" | "content_filter"; + finish_reason: "stop" | "length" | "content_filter"; }[]; usage?: CompletionUsage; } +export function createCompletionResponseDeserializer( + item: any, +): CreateCompletionResponse { + return { + id: item["id"], + object: item["object"], + created: new Date(item["created"]), + model: item["model"], + choices: createCompletionResponseChoiceArrayDeserializer(item["choices"]), + usage: !item["usage"] + ? item["usage"] + : completionUsageDeserializer(item["usage"]), + }; +} + +/** model interface _CreateCompletionResponseChoice */ +export interface _CreateCompletionResponseChoice { + index: number; + text: string; + logprobs: { + tokens: string[]; + token_logprobs: number[]; + top_logprobs: Record[]; + text_offset: number[]; + } | null; + /** + * The reason the model stopped generating tokens. This will be `stop` if the model hit a + * natural stop point or a provided stop sequence, or `content_filter` if content was omitted + * due to a flag from our content filters, `length` if the maximum number of tokens specified + * in the request was reached, or `content_filter` if content was omitted due to a flag from our + * content filters. + */ + finish_reason: "stop" | "length" | "content_filter"; +} + +export function _createCompletionResponseChoiceDeserializer( + item: any, +): _CreateCompletionResponseChoice { + return { + index: item["index"], + text: item["text"], + logprobs: item["logprobs"], + finish_reason: item["finish_reason"], + }; +} + +/** model interface _CreateCompletionResponseChoiceLogprobs */ +export interface _CreateCompletionResponseChoiceLogprobs { + tokens: string[]; + token_logprobs: number[]; + top_logprobs: Record[]; + text_offset: number[]; +} + +export function _createCompletionResponseChoiceLogprobsDeserializer( + item: any, +): _CreateCompletionResponseChoiceLogprobs { + return { + tokens: item["tokens"].map((p: any) => { + return p; + }), + token_logprobs: item["token_logprobs"].map((p: any) => { + return p; + }), + top_logprobs: item["top_logprobs"].map((p: any) => { + return p; + }), + text_offset: item["text_offset"].map((p: any) => { + return p; + }), + }; +} + +export function createCompletionResponseChoiceArrayDeserializer( + result: Array<_CreateCompletionResponseChoice>, +): any[] { + return result.map((item) => { + return _createCompletionResponseChoiceDeserializer(item); + }); +} + +/** model interface CreateFineTuningJobRequest */ export interface CreateFineTuningJobRequest { /** * The ID of an uploaded file that contains training data. @@ -750,7 +1381,7 @@ export interface CreateFineTuningJobRequest { * * See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. */ - trainingFile: string; + training_file: string; /** * The ID of an uploaded file that contains validation data. * @@ -763,14 +1394,16 @@ export interface CreateFineTuningJobRequest { * * See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. */ - validationFile?: string | null; + validation_file?: string | null; /** * The name of the model to fine-tune. You can select one of the * [supported models](/docs/guides/fine-tuning/what-models-can-be-fine-tuned). */ - model: string | "babbage-002" | "davinci-002" | "gpt-3.5-turbo"; + model: "babbage-002" | "davinci-002" | "gpt-3.5-turbo"; /** The hyperparameters used for the fine-tuning job. */ - hyperparameters?: { nEpochs?: "auto" | number }; + hyperparameters?: { + n_epochs?: "auto" | number; + }; /** * A string of up to 18 characters that will be added to your fine-tuned model name. * @@ -782,39 +1415,78 @@ export interface CreateFineTuningJobRequest { export function createFineTuningJobRequestSerializer( item: CreateFineTuningJobRequest, -): Record { +): any { return { - training_file: item["trainingFile"], - validation_file: item["validationFile"], + training_file: item["training_file"], + validation_file: item["validation_file"], model: item["model"], - hyperparameters: !item.hyperparameters - ? undefined - : { n_epochs: item.hyperparameters?.["nEpochs"] }, + hyperparameters: !item["hyperparameters"] + ? item["hyperparameters"] + : _createFineTuningJobRequestHyperparametersSerializer( + item["hyperparameters"], + ), suffix: item["suffix"], }; } +/** model interface _CreateFineTuningJobRequestHyperparameters */ +export interface _CreateFineTuningJobRequestHyperparameters { + /** + * The number of epochs to train the model for. An epoch refers to one full cycle through the + * training dataset. + */ + n_epochs?: "auto" | number; +} + +export function _createFineTuningJobRequestHyperparametersSerializer( + item: _CreateFineTuningJobRequestHyperparameters, +): any { + return { + n_epochs: !item["n_epochs"] + ? item["n_epochs"] + : _createFineTuningJobRequestHyperparametersNEpochsSerializer( + item["n_epochs"], + ), + }; +} + +/** Alias for _CreateFineTuningJobRequestHyperparametersNEpochs */ +export type _CreateFineTuningJobRequestHyperparametersNEpochs = "auto" | number; + +export function _createFineTuningJobRequestHyperparametersNEpochsSerializer( + item: _CreateFineTuningJobRequestHyperparametersNEpochs, +): any { + return item; +} + +export function _createFineTuningJobRequestHyperparametersNEpochsDeserializer( + item: any, +): _CreateFineTuningJobRequestHyperparametersNEpochs { + return item; +} + +/** model interface FineTuningJob */ export interface FineTuningJob { /** The object identifier, which can be referenced in the API endpoints. */ id: string; /** The object type, which is always "fine_tuning.job". */ object: "fine_tuning.job"; /** The Unix timestamp (in seconds) for when the fine-tuning job was created. */ - createdAt: Date; + created_at: Date; /** * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be * null if the fine-tuning job is still running. */ - finishedAt: Date | null; + finished_at: Date | null; /** The base model that is being fine-tuned. */ model: string; /** * The name of the fine-tuned model that is being created. The value will be null if the * fine-tuning job is still running. */ - fineTunedModel: string | null; + fine_tuned_model: string | null; /** The organization that owns the fine-tuning job. */ - organizationId: string; + organization_id: string; /** * The current status of the fine-tuning job, which can be either `created`, `pending`, `running`, * `succeeded`, `failed`, or `cancelled`. @@ -830,60 +1502,201 @@ export interface FineTuningJob { * The hyperparameters used for the fine-tuning job. See the * [fine-tuning guide](/docs/guides/fine-tuning) for more details. */ - hyperparameters: { nEpochs?: "auto" | number }; + hyperparameters: { + n_epochs?: "auto" | number; + }; /** * The file ID used for training. You can retrieve the training data with the * [Files API](/docs/api-reference/files/retrieve-contents). */ - trainingFile: string; + training_file: string; /** * The file ID used for validation. You can retrieve the validation results with the * [Files API](/docs/api-reference/files/retrieve-contents). */ - validationFile: string | null; + validation_file: string | null; /** * The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the * [Files API](/docs/api-reference/files/retrieve-contents). */ - resultFiles: string[]; + result_files: string[]; /** * The total number of billable tokens processed by this fine tuning job. The value will be null * if the fine-tuning job is still running. */ - trainedTokens: number | null; + trained_tokens: number | null; /** * For fine-tuning jobs that have `failed`, this will contain more information on the cause of the * failure. */ - error: { message?: string; code?: string; param?: string | null } | null; + error: { + message?: string; + code?: string; + param?: string | null; + } | null; } +export function fineTuningJobDeserializer(item: any): FineTuningJob { + return { + id: item["id"], + object: item["object"], + created_at: new Date(item["created_at"]), + finished_at: !item["finished_at"] + ? item["finished_at"] + : !item["finished_at"] + ? item["finished_at"] + : new Date(item["finished_at"]), + model: item["model"], + fine_tuned_model: item["fine_tuned_model"], + organization_id: item["organization_id"], + status: item["status"], + hyperparameters: _fineTuningJobHyperparametersDeserializer( + item["hyperparameters"], + ), + training_file: item["training_file"], + validation_file: item["validation_file"], + result_files: item["result_files"].map((p: any) => { + return p; + }), + trained_tokens: item["trained_tokens"], + error: item["error"], + }; +} + +/** model interface _FineTuningJobHyperparameters */ +export interface _FineTuningJobHyperparameters { + /** + * The number of epochs to train the model for. An epoch refers to one full cycle through the + * training dataset. + * + * "Auto" decides the optimal number of epochs based on the size of the dataset. If setting the + * number manually, we support any number between 1 and 50 epochs. + */ + n_epochs?: "auto" | number; +} + +export function _fineTuningJobHyperparametersDeserializer( + item: any, +): _FineTuningJobHyperparameters { + return { + n_epochs: !item["n_epochs"] + ? item["n_epochs"] + : _fineTuningJobHyperparametersNEpochsDeserializer(item["n_epochs"]), + }; +} + +/** Alias for _FineTuningJobHyperparametersNEpochs */ +export type _FineTuningJobHyperparametersNEpochs = "auto" | number; + +export function _fineTuningJobHyperparametersNEpochsSerializer( + item: _FineTuningJobHyperparametersNEpochs, +): any { + return item; +} + +export function _fineTuningJobHyperparametersNEpochsDeserializer( + item: any, +): _FineTuningJobHyperparametersNEpochs { + return item; +} + +/** model interface _FineTuningJobError */ +export interface _FineTuningJobError { + /** A human-readable error message. */ + message?: string; + /** A machine-readable error code. */ + code?: string; + /** + * The parameter that was invalid, usually `training_file` or `validation_file`. This field + * will be null if the failure was not parameter-specific. + */ + param?: string | null; +} + +export function _fineTuningJobErrorDeserializer( + item: any, +): _FineTuningJobError { + return { + message: item["message"], + code: item["code"], + param: item["param"], + }; +} + +/** model interface ListPaginatedFineTuningJobsResponse */ export interface ListPaginatedFineTuningJobsResponse { object: string; data: FineTuningJob[]; - hasMore: boolean; + has_more: boolean; } +export function listPaginatedFineTuningJobsResponseDeserializer( + item: any, +): ListPaginatedFineTuningJobsResponse { + return { + object: item["object"], + data: fineTuningJobArrayDeserializer(item["data"]), + has_more: item["has_more"], + }; +} + +export function fineTuningJobArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return fineTuningJobDeserializer(item); + }); +} + +/** model interface ListFineTuningJobEventsResponse */ export interface ListFineTuningJobEventsResponse { object: string; data: FineTuningJobEvent[]; } +export function listFineTuningJobEventsResponseDeserializer( + item: any, +): ListFineTuningJobEventsResponse { + return { + object: item["object"], + data: fineTuningJobEventArrayDeserializer(item["data"]), + }; +} + +/** model interface FineTuningJobEvent */ export interface FineTuningJobEvent { id: string; object: string; - createdAt: Date; + created_at: Date; level: "info" | "warn" | "error"; message: string; } +export function fineTuningJobEventDeserializer(item: any): FineTuningJobEvent { + return { + id: item["id"], + object: item["object"], + created_at: new Date(item["created_at"]), + level: item["level"], + message: item["message"], + }; +} + +export function fineTuningJobEventArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return fineTuningJobEventDeserializer(item); + }); +} + +/** model interface CreateChatCompletionRequest */ export interface CreateChatCompletionRequest { /** * ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) * table for details on which models work with the Chat API. */ model: - | string | "gpt4" | "gpt-4-0314" | "gpt-4-0613" @@ -909,7 +1722,7 @@ export interface CreateChatCompletionRequest { * model to call that function. `none` is the default when no functions are present. `auto` is the * default if functions are present. */ - functionCall?: "none" | "auto" | ChatCompletionFunctionCallOption; + function_call?: "none" | "auto" | ChatCompletionFunctionCallOption; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output * more random, while lower values like 0.2 will make it more focused and deterministic. @@ -924,7 +1737,7 @@ export interface CreateChatCompletionRequest { * * We generally recommend altering this or `temperature` but not both. */ - topP?: number | null; + top_p?: number | null; /** * How many completions to generate for each prompt. * **Note:** Because this parameter generates many completions, it can quickly consume your token @@ -938,16 +1751,16 @@ export interface CreateChatCompletionRequest { * [Example Python code](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb) * for counting tokens. */ - maxTokens?: number | null; + max_tokens?: number | null; /** Up to 4 sequences where the API will stop generating further tokens. */ - stop?: Stop; + stop?: Stop_1 | null; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear * in the text so far, increasing the model's likelihood to talk about new topics. * * [See more information about frequency and presence penalties.](/docs/guides/gpt/parameter-details) */ - presencePenalty?: number | null; + presence_penalty?: number | null; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing * frequency in the text so far, decreasing the model's likelihood to repeat the same line @@ -955,7 +1768,7 @@ export interface CreateChatCompletionRequest { * * [See more information about frequency and presence penalties.](/docs/guides/gpt/parameter-details) */ - frequencyPenalty?: number | null; + frequency_penalty?: number | null; /** * Modify the likelihood of specified tokens appearing in the completion. * Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an @@ -964,7 +1777,7 @@ export interface CreateChatCompletionRequest { * between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 * should result in a ban or exclusive selection of the relevant token. */ - logitBias?: Record | null; + logit_bias?: Record | null; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect * abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). @@ -981,30 +1794,32 @@ export interface CreateChatCompletionRequest { export function createChatCompletionRequestSerializer( item: CreateChatCompletionRequest, -): Record { +): any { return { model: item["model"], - messages: item["messages"].map(chatCompletionRequestMessageSerializer), - functions: - item["functions"] === undefined - ? item["functions"] - : item["functions"].map(chatCompletionFunctionsSerializer), - function_call: item["functionCall"], + messages: chatCompletionRequestMessageArraySerializer(item["messages"]), + functions: !item["functions"] + ? item["functions"] + : chatCompletionFunctionsArraySerializer(item["functions"]), + function_call: !item["function_call"] + ? item["function_call"] + : _createChatCompletionRequestFunctionCall1Serializer( + item["function_call"], + ), temperature: item["temperature"], - top_p: item["topP"], + top_p: item["top_p"], n: item["n"], - max_tokens: item["maxTokens"], + max_tokens: item["max_tokens"], stop: item["stop"], - presence_penalty: item["presencePenalty"], - frequency_penalty: item["frequencyPenalty"], - logit_bias: !item.logitBias - ? item.logitBias - : (serializeRecord(item.logitBias as any) as any), + presence_penalty: item["presence_penalty"], + frequency_penalty: item["frequency_penalty"], + logit_bias: item["logit_bias"], user: item["user"], stream: item["stream"], }; } +/** model interface ChatCompletionRequestMessage */ export interface ChatCompletionRequestMessage { /** The role of the messages author. One of `system`, `user`, `assistant`, or `function`. */ role: "system" | "user" | "assistant" | "function"; @@ -1020,25 +1835,54 @@ export interface ChatCompletionRequestMessage { */ name?: string; /** The name and arguments of a function that should be called, as generated by the model. */ - functionCall?: { name: string; arguments: string }; + function_call?: { + name: string; + arguments: string; + }; } export function chatCompletionRequestMessageSerializer( item: ChatCompletionRequestMessage, -): Record { +): any { return { role: item["role"], content: item["content"], name: item["name"], - function_call: !item.functionCall - ? undefined - : { - name: item.functionCall?.["name"], - arguments: item.functionCall?.["arguments"], - }, + function_call: !item["function_call"] + ? item["function_call"] + : _chatCompletionRequestMessageFunctionCallSerializer( + item["function_call"], + ), }; } +/** model interface _ChatCompletionRequestMessageFunctionCall */ +export interface _ChatCompletionRequestMessageFunctionCall { + /** The name of the function to call. */ + name: string; + /** + * The arguments to call the function with, as generated by the model in JSON format. Note that + * the model does not always generate valid JSON, and may hallucinate parameters not defined by + * your function schema. Validate the arguments in your code before calling your function. + */ + arguments: string; +} + +export function _chatCompletionRequestMessageFunctionCallSerializer( + item: _ChatCompletionRequestMessageFunctionCall, +): any { + return { name: item["name"], arguments: item["arguments"] }; +} + +export function chatCompletionRequestMessageArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return chatCompletionRequestMessageSerializer(item); + }); +} + +/** model interface ChatCompletionFunctions */ export interface ChatCompletionFunctions { /** * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and @@ -1062,24 +1906,50 @@ export interface ChatCompletionFunctions { export function chatCompletionFunctionsSerializer( item: ChatCompletionFunctions, -): Record { +): any { return { name: item["name"], description: item["description"], - parameters: serializeRecord(item.parameters as any) as any, + parameters: chatCompletionFunctionParametersSerializer(item["parameters"]), }; } +/** model interface ChatCompletionFunctionParameters */ export interface ChatCompletionFunctionParameters extends Record {} export function chatCompletionFunctionParametersSerializer( item: ChatCompletionFunctionParameters, -): Record { - return { - ...item, - }; +): any { + return { ...item }; +} + +export function chatCompletionFunctionsArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return chatCompletionFunctionsSerializer(item); + }); } +/** Alias for _CreateChatCompletionRequestFunctionCall1 */ +export type _CreateChatCompletionRequestFunctionCall1 = + | "none" + | "auto" + | ChatCompletionFunctionCallOption; + +export function _createChatCompletionRequestFunctionCall1Serializer( + item: _CreateChatCompletionRequestFunctionCall1, +): any { + return item; +} + +export function _createChatCompletionRequestFunctionCall1Deserializer( + item: any, +): _CreateChatCompletionRequestFunctionCall1 { + return item; +} + +/** model interface ChatCompletionFunctionCallOption */ export interface ChatCompletionFunctionCallOption { /** The name of the function to call. */ name: string; @@ -1087,12 +1957,13 @@ export interface ChatCompletionFunctionCallOption { export function chatCompletionFunctionCallOptionSerializer( item: ChatCompletionFunctionCallOption, -): Record { - return { - name: item["name"], - }; +): any { + return { name: item["name"] }; } +/** Alias for Stop */ +export type Stop_1 = string | string[]; + /** Represents a chat completion response returned by model, based on the provided input. */ export interface CreateChatCompletionResponse { /** A unique identifier for the chat completion. */ @@ -1107,20 +1978,109 @@ export interface CreateChatCompletionResponse { choices: { index: number; message: ChatCompletionResponseMessage; - finishReason: "stop" | "length" | "function_call" | "content_filter"; + finish_reason: "stop" | "length" | "function_call" | "content_filter"; }[]; usage?: CompletionUsage; } +export function createChatCompletionResponseDeserializer( + item: any, +): CreateChatCompletionResponse { + return { + id: item["id"], + object: item["object"], + created: new Date(item["created"]), + model: item["model"], + choices: createChatCompletionResponseChoiceArrayDeserializer( + item["choices"], + ), + usage: !item["usage"] + ? item["usage"] + : completionUsageDeserializer(item["usage"]), + }; +} + +/** model interface _CreateChatCompletionResponseChoice */ +export interface _CreateChatCompletionResponseChoice { + /** The index of the choice in the list of choices. */ + index: number; + message: ChatCompletionResponseMessage; + /** + * The reason the model stopped generating tokens. This will be `stop` if the model hit a + * natural stop point or a provided stop sequence, `length` if the maximum number of tokens + * specified in the request was reached, `content_filter` if the content was omitted due to + * a flag from our content filters, or `function_call` if the model called a function. + */ + finish_reason: "stop" | "length" | "function_call" | "content_filter"; +} + +export function _createChatCompletionResponseChoiceDeserializer( + item: any, +): _CreateChatCompletionResponseChoice { + return { + index: item["index"], + message: chatCompletionResponseMessageDeserializer(item["message"]), + finish_reason: item["finish_reason"], + }; +} + +/** model interface ChatCompletionResponseMessage */ export interface ChatCompletionResponseMessage { /** The role of the author of this message. */ role: "system" | "user" | "assistant" | "function"; /** The contents of the message. */ content: string | null; /** The name and arguments of a function that should be called, as generated by the model. */ - functionCall?: { name: string; arguments: string }; + function_call?: { + name: string; + arguments: string; + }; } +export function chatCompletionResponseMessageDeserializer( + item: any, +): ChatCompletionResponseMessage { + return { + role: item["role"], + content: item["content"], + function_call: !item["function_call"] + ? item["function_call"] + : _chatCompletionResponseMessageFunctionCallDeserializer( + item["function_call"], + ), + }; +} + +/** model interface _ChatCompletionResponseMessageFunctionCall */ +export interface _ChatCompletionResponseMessageFunctionCall { + /** The name of the function to call. */ + name: string; + /** + * The arguments to call the function with, as generated by the model in JSON format. Note that + * the model does not always generate valid JSON, and may hallucinate parameters not defined by + * your function schema. Validate the arguments in your code before calling your function. + */ + arguments: string; +} + +export function _chatCompletionResponseMessageFunctionCallDeserializer( + item: any, +): _ChatCompletionResponseMessageFunctionCall { + return { + name: item["name"], + arguments: item["arguments"], + }; +} + +export function createChatCompletionResponseChoiceArrayDeserializer( + result: Array<_CreateChatCompletionResponseChoice>, +): any[] { + return result.map((item) => { + return _createChatCompletionResponseChoiceDeserializer(item); + }); +} + +/** model interface CreateTranslationRequest */ export interface CreateTranslationRequest { /** * The audio file object (not file name) to translate, in one of these formats: flac, mp3, mp4, @@ -1128,7 +2088,7 @@ export interface CreateTranslationRequest { */ file: Uint8Array; /** ID of the model to use. Only `whisper-1` is currently available. */ - model: string | "whisper-1"; + model: "whisper-1"; /** * An optional text to guide the model's style or continue a previous audio segment. The * [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. @@ -1138,7 +2098,7 @@ export interface CreateTranslationRequest { * The format of the transcript output, in one of these options: json, text, srt, verbose_json, or * vtt. */ - responseFormat?: "json" | "text" | "srt" | "verbose_json" | "vtt"; + response_format?: "json" | "text" | "srt" | "verbose_json" | "vtt"; /** * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more * random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, @@ -1150,20 +2110,30 @@ export interface CreateTranslationRequest { export function createTranslationRequestSerializer( item: CreateTranslationRequest, -): Record { +): any { return { file: uint8ArrayToString(item["file"], "base64"), model: item["model"], prompt: item["prompt"], - response_format: item["responseFormat"], + response_format: item["response_format"], temperature: item["temperature"], }; } +/** model interface CreateTranslationResponse */ export interface CreateTranslationResponse { text: string; } +export function createTranslationResponseDeserializer( + item: any, +): CreateTranslationResponse { + return { + text: item["text"], + }; +} + +/** model interface CreateTranscriptionRequest */ export interface CreateTranscriptionRequest { /** * The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, @@ -1171,7 +2141,7 @@ export interface CreateTranscriptionRequest { */ file: Uint8Array; /** ID of the model to use. Only `whisper-1` is currently available. */ - model: string | "whisper-1"; + model: "whisper-1"; /** * An optional text to guide the model's style or continue a previous audio segment. The * [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. @@ -1181,7 +2151,7 @@ export interface CreateTranscriptionRequest { * The format of the transcript output, in one of these options: json, text, srt, verbose_json, or * vtt. */ - responseFormat?: "json" | "text" | "srt" | "verbose_json" | "vtt"; + response_format?: "json" | "text" | "srt" | "verbose_json" | "vtt"; /** * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more * random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, @@ -1199,22 +2169,26 @@ export interface CreateTranscriptionRequest { export function createTranscriptionRequestSerializer( item: CreateTranscriptionRequest, -): Record { +): any { return { file: uint8ArrayToString(item["file"], "base64"), model: item["model"], prompt: item["prompt"], - response_format: item["responseFormat"], + response_format: item["response_format"], temperature: item["temperature"], language: item["language"], }; } +/** model interface CreateTranscriptionResponse */ export interface CreateTranscriptionResponse { text: string; } -/** Alias for Prompt */ -export type Prompt = string | string[] | number[] | number[][]; -/** Alias for Stop */ -export type Stop = string | string[]; +export function createTranscriptionResponseDeserializer( + item: any, +): CreateTranscriptionResponse { + return { + text: item["text"], + }; +} diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/openAIClient.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/openAIClient.ts index 14efc1209c..2b85b3f2f6 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/openAIClient.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/openAIClient.ts @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { KeyCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; import { getAudioOperations, AudioOperations } from "./classic/audio/index.js"; import { getChatOperations, ChatOperations } from "./classic/chat/index.js"; import { @@ -40,6 +38,8 @@ import { OpenAIContext, OpenAIClientOptionalParams, } from "./api/index.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { KeyCredential } from "@azure/core-auth"; export { OpenAIClientOptionalParams } from "./api/openAIContext.js"; diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md b/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md index 0151f3c5c9..53d43edb8f 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md @@ -120,7 +120,7 @@ export type AzureChatExtensionConfigurationUnion = AzureSearchChatExtensionConfi // @public export interface AzureChatExtensionDataSourceResponseCitation { - chunkId?: string; + chunk_id?: string; content: string; filepath?: string; title?: string; @@ -129,7 +129,7 @@ export interface AzureChatExtensionDataSourceResponseCitation { // @public export interface AzureChatExtensionRetrievedDocument { - chunkId?: string; + chunk_id?: string; content: string; dataSourceIndex: number; filepath?: string; @@ -368,7 +368,7 @@ export interface ChatCompletionsOptions { temperature?: number; toolChoice?: ChatCompletionsToolSelectionPreset | ChatCompletionsNamedToolSelectionUnion; tools?: ChatCompletionsToolDefinitionUnion[]; - topLogprobs?: number | null; + top_logprobs?: number | null; topP?: number; user?: string; } @@ -512,7 +512,7 @@ export interface ChatTokenLogProbabilityResult { bytes: number[] | null; logprob: number; token: string; - topLogprobs: ChatTokenLogProbabilityInfo[] | null; + top_logprobs: ChatTokenLogProbabilityInfo[] | null; } // @public @@ -990,9 +990,6 @@ export interface PineconeFieldMappingOptions { urlField?: string; } -// @public -export type ServiceApiVersions = "2022-12-01" | "2023-05-15" | "2023-06-01-preview" | "2023-07-01-preview" | "2024-02-01" | "2024-02-15-preview" | "2024-03-01-preview" | "2024-04-01-preview" | "2024-05-01-preview" | "2024-06-01"; - // @public export interface SpeechGenerationOptions { input: string; diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/index.ts index a2165d4899..1c4edce4d8 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/index.ts @@ -17,3 +17,14 @@ export { generateSpeechFromText, getEmbeddings, } from "./operations.js"; +export { + GetAudioTranscriptionAsPlainTextOptionalParams, + GetAudioTranscriptionAsResponseObjectOptionalParams, + GetAudioTranslationAsPlainTextOptionalParams, + GetAudioTranslationAsResponseObjectOptionalParams, + GetCompletionsOptionalParams, + GetChatCompletionsOptionalParams, + GetImageGenerationsOptionalParams, + GenerateSpeechFromTextOptionalParams, + GetEmbeddingsOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts index 242756bd71..53d95cbb55 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential, KeyCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { KeyCredential, TokenCredential } from "@azure/core-auth"; export interface OpenAIContext extends Client {} diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts index 10f1bbe49b..76da673e8d 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts @@ -2,49 +2,51 @@ // Licensed under the MIT License. import { - chatRequestMessageUnionSerializer, - functionDefinitionSerializer, - azureChatExtensionConfigurationUnionSerializer, - azureChatEnhancementConfigurationSerializer, - chatCompletionsResponseFormatUnionSerializer, + OpenAIContext as Client, + GenerateSpeechFromTextOptionalParams, + GetAudioTranscriptionAsPlainTextOptionalParams, + GetAudioTranscriptionAsResponseObjectOptionalParams, + GetAudioTranslationAsPlainTextOptionalParams, + GetAudioTranslationAsResponseObjectOptionalParams, + GetChatCompletionsOptionalParams, + GetCompletionsOptionalParams, + GetEmbeddingsOptionalParams, + GetImageGenerationsOptionalParams, +} from "./index.js"; +import { AudioTranscriptionOptions, + audioTranscriptionOptionsSerializer, AudioTranscription, - AudioTaskLabel, + audioTranscriptionDeserializer, AudioTranslationOptions, + audioTranslationOptionsSerializer, AudioTranslation, + audioTranslationDeserializer, CompletionsOptions, + completionsOptionsSerializer, Completions, - ContentFilterSeverity, - CompletionsFinishReason, + completionsDeserializer, ChatCompletionsOptions, - ChatRole, + chatCompletionsOptionsSerializer, ChatCompletions, + chatCompletionsDeserializer, ImageGenerationOptions, + imageGenerationOptionsSerializer, ImageGenerations, + imageGenerationsDeserializer, SpeechGenerationOptions, + speechGenerationOptionsSerializer, EmbeddingsOptions, + embeddingsOptionsSerializer, Embeddings, + embeddingsDeserializer, } from "../models/models.js"; -import { OpenAIContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { serializeRecord } from "../helpers/serializerHelpers.js"; -import { uint8ArrayToString } from "@azure/core-util"; -import { - GetAudioTranscriptionAsPlainTextOptionalParams, - GetAudioTranscriptionAsResponseObjectOptionalParams, - GetAudioTranslationAsPlainTextOptionalParams, - GetAudioTranslationAsResponseObjectOptionalParams, - GetCompletionsOptionalParams, - GetChatCompletionsOptionalParams, - GetImageGenerationsOptionalParams, - GenerateSpeechFromTextOptionalParams, - GetEmbeddingsOptionalParams, -} from "../models/options.js"; export function _getAudioTranscriptionAsPlainTextSend( context: Client, @@ -59,16 +61,7 @@ export function _getAudioTranscriptionAsPlainTextSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - language: body["language"], - prompt: body["prompt"], - temperature: body["temperature"], - timestamp_granularities: body["timestampGranularities"], - model: body["model"], - }, + body: audioTranscriptionOptionsSerializer(body), }); } @@ -117,16 +110,7 @@ export function _getAudioTranscriptionAsResponseObjectSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - language: body["language"], - prompt: body["prompt"], - temperature: body["temperature"], - timestamp_granularities: body["timestampGranularities"], - model: body["model"], - }, + body: audioTranscriptionOptionsSerializer(body), }); } @@ -138,35 +122,7 @@ export async function _getAudioTranscriptionAsResponseObjectDeserialize( throw createRestError(result); } - return { - text: result.body["text"], - task: result.body["task"] as AudioTaskLabel, - language: result.body["language"], - duration: result.body["duration"], - segments: - result.body["segments"] === undefined - ? result.body["segments"] - : result.body["segments"].map((p: any) => { - return { - id: p["id"], - start: p["start"], - end: p["end"], - text: p["text"], - temperature: p["temperature"], - avgLogprob: p["avg_logprob"], - compressionRatio: p["compression_ratio"], - noSpeechProb: p["no_speech_prob"], - tokens: p["tokens"], - seek: p["seek"], - }; - }), - words: - result.body["words"] === undefined - ? result.body["words"] - : result.body["words"].map((p: any) => { - return { word: p["word"], start: p["start"], end: p["end"] }; - }), - }; + return audioTranscriptionDeserializer(result.body); } /** @@ -203,14 +159,7 @@ export function _getAudioTranslationAsPlainTextSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - prompt: body["prompt"], - temperature: body["temperature"], - model: body["model"], - }, + body: audioTranslationOptionsSerializer(body), }); } @@ -256,14 +205,7 @@ export function _getAudioTranslationAsResponseObjectSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - prompt: body["prompt"], - temperature: body["temperature"], - model: body["model"], - }, + body: audioTranslationOptionsSerializer(body), }); } @@ -275,29 +217,7 @@ export async function _getAudioTranslationAsResponseObjectDeserialize( throw createRestError(result); } - return { - text: result.body["text"], - task: result.body["task"] as AudioTaskLabel, - language: result.body["language"], - duration: result.body["duration"], - segments: - result.body["segments"] === undefined - ? result.body["segments"] - : result.body["segments"].map((p: any) => { - return { - id: p["id"], - start: p["start"], - end: p["end"], - text: p["text"], - temperature: p["temperature"], - avgLogprob: p["avg_logprob"], - compressionRatio: p["compression_ratio"], - noSpeechProb: p["no_speech_prob"], - tokens: p["tokens"], - seek: p["seek"], - }; - }), - }; + return audioTranslationDeserializer(result.body); } /** Gets English language transcribed text and associated metadata from provided spoken audio data. */ @@ -328,26 +248,7 @@ export function _getCompletionsSend( .path("/deployments/{deploymentId}/completions", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - body: { - prompt: body["prompt"], - max_tokens: body["maxTokens"], - temperature: body["temperature"], - top_p: body["topP"], - logit_bias: !body.logitBias - ? body.logitBias - : (serializeRecord(body.logitBias as any) as any), - user: body["user"], - n: body["n"], - logprobs: body["logprobs"], - suffix: body["suffix"], - echo: body["echo"], - stop: body["stop"], - presence_penalty: body["presencePenalty"], - frequency_penalty: body["frequencyPenalty"], - best_of: body["bestOf"], - stream: body["stream"], - model: body["model"], - }, + body: completionsOptionsSerializer(body), }); } @@ -359,203 +260,7 @@ export async function _getCompletionsDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - created: new Date(result.body["created"]), - promptFilterResults: - result.body["prompt_filter_results"] === undefined - ? result.body["prompt_filter_results"] - : result.body["prompt_filter_results"].map((p: any) => { - return { - promptIndex: p["prompt_index"], - contentFilterResults: { - sexual: !p.content_filter_results.sexual - ? undefined - : { - filtered: p.content_filter_results.sexual?.["filtered"], - severity: p.content_filter_results.sexual?.[ - "severity" - ] as ContentFilterSeverity, - }, - violence: !p.content_filter_results.violence - ? undefined - : { - filtered: p.content_filter_results.violence?.["filtered"], - severity: p.content_filter_results.violence?.[ - "severity" - ] as ContentFilterSeverity, - }, - hate: !p.content_filter_results.hate - ? undefined - : { - filtered: p.content_filter_results.hate?.["filtered"], - severity: p.content_filter_results.hate?.[ - "severity" - ] as ContentFilterSeverity, - }, - selfHarm: !p.content_filter_results.self_harm - ? undefined - : { - filtered: - p.content_filter_results.self_harm?.["filtered"], - severity: p.content_filter_results.self_harm?.[ - "severity" - ] as ContentFilterSeverity, - }, - profanity: !p.content_filter_results.profanity - ? undefined - : { - filtered: - p.content_filter_results.profanity?.["filtered"], - detected: - p.content_filter_results.profanity?.["detected"], - }, - customBlocklists: !p.content_filter_results.custom_blocklists - ? undefined - : { - filtered: - p.content_filter_results.custom_blocklists?.[ - "filtered" - ], - details: p.content_filter_results.custom_blocklists?.[ - "details" - ].map((p: any) => { - return { filtered: p["filtered"], id: p["id"] }; - }), - }, - error: !p.content_filter_results.error - ? undefined - : p.content_filter_results.error, - jailbreak: !p.content_filter_results.jailbreak - ? undefined - : { - filtered: - p.content_filter_results.jailbreak?.["filtered"], - detected: - p.content_filter_results.jailbreak?.["detected"], - }, - indirectAttack: !p.content_filter_results.indirect_attack - ? undefined - : { - filtered: - p.content_filter_results.indirect_attack?.["filtered"], - detected: - p.content_filter_results.indirect_attack?.["detected"], - }, - }, - }; - }), - choices: result.body["choices"].map((p: any) => { - return { - text: p["text"], - index: p["index"], - contentFilterResults: !p.content_filter_results - ? undefined - : { - sexual: !p.content_filter_results?.sexual - ? undefined - : { - filtered: p.content_filter_results?.sexual?.["filtered"], - severity: p.content_filter_results?.sexual?.[ - "severity" - ] as ContentFilterSeverity, - }, - violence: !p.content_filter_results?.violence - ? undefined - : { - filtered: p.content_filter_results?.violence?.["filtered"], - severity: p.content_filter_results?.violence?.[ - "severity" - ] as ContentFilterSeverity, - }, - hate: !p.content_filter_results?.hate - ? undefined - : { - filtered: p.content_filter_results?.hate?.["filtered"], - severity: p.content_filter_results?.hate?.[ - "severity" - ] as ContentFilterSeverity, - }, - selfHarm: !p.content_filter_results?.self_harm - ? undefined - : { - filtered: p.content_filter_results?.self_harm?.["filtered"], - severity: p.content_filter_results?.self_harm?.[ - "severity" - ] as ContentFilterSeverity, - }, - profanity: !p.content_filter_results?.profanity - ? undefined - : { - filtered: p.content_filter_results?.profanity?.["filtered"], - detected: p.content_filter_results?.profanity?.["detected"], - }, - customBlocklists: !p.content_filter_results?.custom_blocklists - ? undefined - : { - filtered: - p.content_filter_results?.custom_blocklists?.["filtered"], - details: p.content_filter_results?.custom_blocklists?.[ - "details" - ].map((p: any) => { - return { filtered: p["filtered"], id: p["id"] }; - }), - }, - error: !p.content_filter_results?.error - ? undefined - : p.content_filter_results?.error, - protectedMaterialText: !p.content_filter_results - ?.protected_material_text - ? undefined - : { - filtered: - p.content_filter_results?.protected_material_text?.[ - "filtered" - ], - detected: - p.content_filter_results?.protected_material_text?.[ - "detected" - ], - }, - protectedMaterialCode: !p.content_filter_results - ?.protected_material_code - ? undefined - : { - filtered: - p.content_filter_results?.protected_material_code?.[ - "filtered" - ], - detected: - p.content_filter_results?.protected_material_code?.[ - "detected" - ], - url: p.content_filter_results?.protected_material_code?.[ - "URL" - ], - license: - p.content_filter_results?.protected_material_code?.[ - "license" - ], - }, - }, - logprobs: - p.logprobs === null - ? null - : { - tokens: p.logprobs["tokens"], - tokenLogprobs: p.logprobs["token_logprobs"], - topLogprobs: p.logprobs["top_logprobs"], - textOffset: p.logprobs["text_offset"], - }, - finishReason: p["finish_reason"] as CompletionsFinishReason, - }; - }), - usage: { - completionTokens: result.body.usage["completion_tokens"], - promptTokens: result.body.usage["prompt_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; + return completionsDeserializer(result.body); } /** @@ -588,46 +293,7 @@ export function _getChatCompletionsSend( .path("/deployments/{deploymentId}/chat/completions", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - body: { - messages: body["messages"].map((p) => - chatRequestMessageUnionSerializer(p), - ), - functions: - body["functions"] === undefined - ? body["functions"] - : body["functions"].map(functionDefinitionSerializer), - function_call: body["functionCall"] as any, - max_tokens: body["maxTokens"], - temperature: body["temperature"], - top_p: body["topP"], - logit_bias: !body.logitBias - ? body.logitBias - : (serializeRecord(body.logitBias as any) as any), - user: body["user"], - n: body["n"], - stop: body["stop"], - presence_penalty: body["presencePenalty"], - frequency_penalty: body["frequencyPenalty"], - stream: body["stream"], - model: body["model"], - data_sources: - body["dataSources"] === undefined - ? body["dataSources"] - : body["dataSources"].map((p) => - azureChatExtensionConfigurationUnionSerializer(p), - ), - enhancements: !body.enhancements - ? body.enhancements - : azureChatEnhancementConfigurationSerializer(body.enhancements), - seed: body["seed"], - logprobs: body["logprobs"], - top_logprobs: body["topLogprobs"], - response_format: !body.responseFormat - ? body.responseFormat - : chatCompletionsResponseFormatUnionSerializer(body.responseFormat), - tools: body["tools"], - tool_choice: body["toolChoice"] as any, - }, + body: chatCompletionsOptionsSerializer(body), }); } @@ -639,354 +305,7 @@ export async function _getChatCompletionsDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - created: new Date(result.body["created"]), - choices: result.body["choices"].map((p: any) => { - return { - message: !p.message - ? undefined - : { - role: p.message?.["role"] as ChatRole, - content: p.message?.["content"], - toolCalls: - p.message?.["tool_calls"] === undefined - ? p.message?.["tool_calls"] - : p.message?.["tool_calls"], - functionCall: !p.message?.function_call - ? undefined - : { - name: p.message?.function_call?.["name"], - arguments: p.message?.function_call?.["arguments"], - }, - context: !p.message?.context - ? undefined - : { - citations: - p.message?.context?.["citations"] === undefined - ? p.message?.context?.["citations"] - : p.message?.context?.["citations"].map((p: any) => { - return { - content: p["content"], - title: p["title"], - url: p["url"], - filepath: p["filepath"], - chunkId: p["chunk_id"], - }; - }), - intent: p.message?.context?.["intent"], - allRetrievedDocuments: - p.message?.context?.["all_retrieved_documents"] === - undefined - ? p.message?.context?.["all_retrieved_documents"] - : p.message?.context?.["all_retrieved_documents"].map( - (p: any) => { - return { - content: p["content"], - title: p["title"], - url: p["url"], - filepath: p["filepath"], - chunkId: p["chunk_id"], - searchQueries: p["search_queries"], - dataSourceIndex: p["data_source_index"], - originalSearchScore: p["original_search_score"], - rerankScore: p["rerank_score"], - filterReason: p["filter_reason"], - }; - }, - ), - }, - }, - logprobs: - p.logprobs === null - ? null - : { - content: - p.logprobs["content"] === null - ? p.logprobs["content"] - : p.logprobs["content"].map((p: any) => { - return { - token: p["token"], - logprob: p["logprob"], - bytes: p["bytes"], - topLogprobs: - p["top_logprobs"] === null - ? p["top_logprobs"] - : p["top_logprobs"].map((p: any) => { - return { - token: p["token"], - logprob: p["logprob"], - bytes: p["bytes"], - }; - }), - }; - }), - }, - index: p["index"], - finishReason: p["finish_reason"] as CompletionsFinishReason, - finishDetails: !p.finish_details - ? undefined - : { type: p.finish_details?.["type"] }, - delta: !p.delta - ? undefined - : { - role: p.delta?.["role"] as ChatRole, - content: p.delta?.["content"], - toolCalls: - p.delta?.["tool_calls"] === undefined - ? p.delta?.["tool_calls"] - : p.delta?.["tool_calls"], - functionCall: !p.delta?.function_call - ? undefined - : { - name: p.delta?.function_call?.["name"], - arguments: p.delta?.function_call?.["arguments"], - }, - context: !p.delta?.context - ? undefined - : { - citations: - p.delta?.context?.["citations"] === undefined - ? p.delta?.context?.["citations"] - : p.delta?.context?.["citations"].map((p: any) => { - return { - content: p["content"], - title: p["title"], - url: p["url"], - filepath: p["filepath"], - chunkId: p["chunk_id"], - }; - }), - intent: p.delta?.context?.["intent"], - allRetrievedDocuments: - p.delta?.context?.["all_retrieved_documents"] === - undefined - ? p.delta?.context?.["all_retrieved_documents"] - : p.delta?.context?.["all_retrieved_documents"].map( - (p: any) => { - return { - content: p["content"], - title: p["title"], - url: p["url"], - filepath: p["filepath"], - chunkId: p["chunk_id"], - searchQueries: p["search_queries"], - dataSourceIndex: p["data_source_index"], - originalSearchScore: p["original_search_score"], - rerankScore: p["rerank_score"], - filterReason: p["filter_reason"], - }; - }, - ), - }, - }, - contentFilterResults: !p.content_filter_results - ? undefined - : { - sexual: !p.content_filter_results?.sexual - ? undefined - : { - filtered: p.content_filter_results?.sexual?.["filtered"], - severity: p.content_filter_results?.sexual?.[ - "severity" - ] as ContentFilterSeverity, - }, - violence: !p.content_filter_results?.violence - ? undefined - : { - filtered: p.content_filter_results?.violence?.["filtered"], - severity: p.content_filter_results?.violence?.[ - "severity" - ] as ContentFilterSeverity, - }, - hate: !p.content_filter_results?.hate - ? undefined - : { - filtered: p.content_filter_results?.hate?.["filtered"], - severity: p.content_filter_results?.hate?.[ - "severity" - ] as ContentFilterSeverity, - }, - selfHarm: !p.content_filter_results?.self_harm - ? undefined - : { - filtered: p.content_filter_results?.self_harm?.["filtered"], - severity: p.content_filter_results?.self_harm?.[ - "severity" - ] as ContentFilterSeverity, - }, - profanity: !p.content_filter_results?.profanity - ? undefined - : { - filtered: p.content_filter_results?.profanity?.["filtered"], - detected: p.content_filter_results?.profanity?.["detected"], - }, - customBlocklists: !p.content_filter_results?.custom_blocklists - ? undefined - : { - filtered: - p.content_filter_results?.custom_blocklists?.["filtered"], - details: p.content_filter_results?.custom_blocklists?.[ - "details" - ].map((p: any) => { - return { filtered: p["filtered"], id: p["id"] }; - }), - }, - error: !p.content_filter_results?.error - ? undefined - : p.content_filter_results?.error, - protectedMaterialText: !p.content_filter_results - ?.protected_material_text - ? undefined - : { - filtered: - p.content_filter_results?.protected_material_text?.[ - "filtered" - ], - detected: - p.content_filter_results?.protected_material_text?.[ - "detected" - ], - }, - protectedMaterialCode: !p.content_filter_results - ?.protected_material_code - ? undefined - : { - filtered: - p.content_filter_results?.protected_material_code?.[ - "filtered" - ], - detected: - p.content_filter_results?.protected_material_code?.[ - "detected" - ], - url: p.content_filter_results?.protected_material_code?.[ - "URL" - ], - license: - p.content_filter_results?.protected_material_code?.[ - "license" - ], - }, - }, - enhancements: !p.enhancements - ? undefined - : { - grounding: !p.enhancements?.grounding - ? undefined - : { - lines: p.enhancements?.grounding?.["lines"].map( - (p: any) => { - return { - text: p["text"], - spans: p["spans"].map((p: any) => { - return { - text: p["text"], - offset: p["offset"], - length: p["length"], - polygon: p["polygon"].map((p: any) => { - return { x: p["x"], y: p["y"] }; - }), - }; - }), - }; - }, - ), - }, - }, - }; - }), - model: result.body["model"], - promptFilterResults: - result.body["prompt_filter_results"] === undefined - ? result.body["prompt_filter_results"] - : result.body["prompt_filter_results"].map((p: any) => { - return { - promptIndex: p["prompt_index"], - contentFilterResults: { - sexual: !p.content_filter_results.sexual - ? undefined - : { - filtered: p.content_filter_results.sexual?.["filtered"], - severity: p.content_filter_results.sexual?.[ - "severity" - ] as ContentFilterSeverity, - }, - violence: !p.content_filter_results.violence - ? undefined - : { - filtered: p.content_filter_results.violence?.["filtered"], - severity: p.content_filter_results.violence?.[ - "severity" - ] as ContentFilterSeverity, - }, - hate: !p.content_filter_results.hate - ? undefined - : { - filtered: p.content_filter_results.hate?.["filtered"], - severity: p.content_filter_results.hate?.[ - "severity" - ] as ContentFilterSeverity, - }, - selfHarm: !p.content_filter_results.self_harm - ? undefined - : { - filtered: - p.content_filter_results.self_harm?.["filtered"], - severity: p.content_filter_results.self_harm?.[ - "severity" - ] as ContentFilterSeverity, - }, - profanity: !p.content_filter_results.profanity - ? undefined - : { - filtered: - p.content_filter_results.profanity?.["filtered"], - detected: - p.content_filter_results.profanity?.["detected"], - }, - customBlocklists: !p.content_filter_results.custom_blocklists - ? undefined - : { - filtered: - p.content_filter_results.custom_blocklists?.[ - "filtered" - ], - details: p.content_filter_results.custom_blocklists?.[ - "details" - ].map((p: any) => { - return { filtered: p["filtered"], id: p["id"] }; - }), - }, - error: !p.content_filter_results.error - ? undefined - : p.content_filter_results.error, - jailbreak: !p.content_filter_results.jailbreak - ? undefined - : { - filtered: - p.content_filter_results.jailbreak?.["filtered"], - detected: - p.content_filter_results.jailbreak?.["detected"], - }, - indirectAttack: !p.content_filter_results.indirect_attack - ? undefined - : { - filtered: - p.content_filter_results.indirect_attack?.["filtered"], - detected: - p.content_filter_results.indirect_attack?.["detected"], - }, - }, - }; - }), - systemFingerprint: result.body["system_fingerprint"], - usage: { - completionTokens: result.body.usage["completion_tokens"], - promptTokens: result.body.usage["prompt_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; + return chatCompletionsDeserializer(result.body); } /** @@ -1019,16 +338,7 @@ export function _getImageGenerationsSend( .path("/deployments/{deploymentId}/images/generations", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - body: { - model: body["model"], - prompt: body["prompt"], - n: body["n"], - size: body["size"], - response_format: body["responseFormat"], - quality: body["quality"], - style: body["style"], - user: body["user"], - }, + body: imageGenerationOptionsSerializer(body), }); } @@ -1040,111 +350,7 @@ export async function _getImageGenerationsDeserialize( throw createRestError(result); } - return { - created: new Date(result.body["created"]), - data: result.body["data"].map((p: any) => { - return { - url: p["url"], - base64Data: p["b64_json"], - contentFilterResults: !p.content_filter_results - ? undefined - : { - sexual: !p.content_filter_results?.sexual - ? undefined - : { - filtered: p.content_filter_results?.sexual?.["filtered"], - severity: p.content_filter_results?.sexual?.[ - "severity" - ] as ContentFilterSeverity, - }, - violence: !p.content_filter_results?.violence - ? undefined - : { - filtered: p.content_filter_results?.violence?.["filtered"], - severity: p.content_filter_results?.violence?.[ - "severity" - ] as ContentFilterSeverity, - }, - hate: !p.content_filter_results?.hate - ? undefined - : { - filtered: p.content_filter_results?.hate?.["filtered"], - severity: p.content_filter_results?.hate?.[ - "severity" - ] as ContentFilterSeverity, - }, - selfHarm: !p.content_filter_results?.self_harm - ? undefined - : { - filtered: p.content_filter_results?.self_harm?.["filtered"], - severity: p.content_filter_results?.self_harm?.[ - "severity" - ] as ContentFilterSeverity, - }, - }, - revisedPrompt: p["revised_prompt"], - promptFilterResults: !p.prompt_filter_results - ? undefined - : { - sexual: !p.prompt_filter_results?.sexual - ? undefined - : { - filtered: p.prompt_filter_results?.sexual?.["filtered"], - severity: p.prompt_filter_results?.sexual?.[ - "severity" - ] as ContentFilterSeverity, - }, - violence: !p.prompt_filter_results?.violence - ? undefined - : { - filtered: p.prompt_filter_results?.violence?.["filtered"], - severity: p.prompt_filter_results?.violence?.[ - "severity" - ] as ContentFilterSeverity, - }, - hate: !p.prompt_filter_results?.hate - ? undefined - : { - filtered: p.prompt_filter_results?.hate?.["filtered"], - severity: p.prompt_filter_results?.hate?.[ - "severity" - ] as ContentFilterSeverity, - }, - selfHarm: !p.prompt_filter_results?.self_harm - ? undefined - : { - filtered: p.prompt_filter_results?.self_harm?.["filtered"], - severity: p.prompt_filter_results?.self_harm?.[ - "severity" - ] as ContentFilterSeverity, - }, - profanity: !p.prompt_filter_results?.profanity - ? undefined - : { - filtered: p.prompt_filter_results?.profanity?.["filtered"], - detected: p.prompt_filter_results?.profanity?.["detected"], - }, - jailbreak: !p.prompt_filter_results?.jailbreak - ? undefined - : { - filtered: p.prompt_filter_results?.jailbreak?.["filtered"], - detected: p.prompt_filter_results?.jailbreak?.["detected"], - }, - customBlocklists: !p.prompt_filter_results?.custom_blocklists - ? undefined - : { - filtered: - p.prompt_filter_results?.custom_blocklists?.["filtered"], - details: p.prompt_filter_results?.custom_blocklists?.[ - "details" - ].map((p: any) => { - return { filtered: p["filtered"], id: p["id"] }; - }), - }, - }, - }; - }), - }; + return imageGenerationsDeserializer(result.body); } /** Creates an image given a prompt. */ @@ -1173,13 +379,7 @@ export function _generateSpeechFromTextSend( .path("/deployments/{deploymentId}/audio/speech", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - body: { - input: body["input"], - voice: body["voice"], - response_format: body["responseFormat"], - speed: body["speed"], - model: body["model"], - }, + body: speechGenerationOptionsSerializer(body), }); } @@ -1191,7 +391,7 @@ export async function _generateSpeechFromTextDeserialize( throw createRestError(result); } - return result.body as any; + return result.body; } /** Generates text-to-speech audio from the input text. */ @@ -1220,14 +420,7 @@ export function _getEmbeddingsSend( .path("/deployments/{deploymentId}/embeddings", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - body: { - user: body["user"], - model: body["model"], - input: body["input"], - encoding_format: body["encodingFormat"], - dimensions: body["dimensions"], - input_type: body["inputType"], - }, + body: embeddingsOptionsSerializer(body), }); } @@ -1239,15 +432,7 @@ export async function _getEmbeddingsDeserialize( throw createRestError(result); } - return { - data: result.body["data"].map((p: any) => { - return { embedding: p["embedding"], index: p["index"] }; - }), - usage: { - promptTokens: result.body.usage["prompt_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; + return embeddingsDeserializer(result.body); } /** Return the embeddings for a given prompt. */ diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/index.ts index 9d426f2967..39d5026083 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/index.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -export { OpenAIClient, OpenAIClientOptionalParams } from "./openAIClient.js"; +export { OpenAIClient } from "./openAIClient.js"; export { AudioTranscriptionOptions, AudioTranscriptionFormat, @@ -31,27 +31,34 @@ export { CompletionsUsage, ChatCompletionsOptions, ChatRequestMessage, + ChatRequestMessageUnion, + ChatRole, ChatRequestSystemMessage, ChatRequestUserMessage, ChatMessageContentItem, + ChatMessageContentItemUnion, ChatMessageTextContentItem, ChatMessageImageContentItem, ChatMessageImageUrl, ChatMessageImageDetailLevel, ChatRequestAssistantMessage, ChatCompletionsToolCall, + ChatCompletionsToolCallUnion, ChatCompletionsFunctionToolCall, FunctionCall, ChatRequestToolMessage, ChatRequestFunctionMessage, - ChatRole, FunctionDefinition, FunctionCallPreset, FunctionName, AzureChatExtensionConfiguration, + AzureChatExtensionConfigurationUnion, + AzureChatExtensionType, AzureSearchChatExtensionConfiguration, AzureSearchChatExtensionParameters, OnYourDataAuthenticationOptions, + OnYourDataAuthenticationOptionsUnion, + OnYourDataAuthenticationType, OnYourDataApiKeyAuthenticationOptions, OnYourDataConnectionStringAuthenticationOptions, OnYourDataKeyAndKeyIdAuthenticationOptions, @@ -59,19 +66,20 @@ export { OnYourDataAccessTokenAuthenticationOptions, OnYourDataSystemAssignedManagedIdentityAuthenticationOptions, OnYourDataUserAssignedManagedIdentityAuthenticationOptions, - OnYourDataAuthenticationType, OnYourDataContextProperty, AzureSearchIndexFieldMappingOptions, AzureSearchQueryType, OnYourDataVectorizationSource, + OnYourDataVectorizationSourceUnion, + OnYourDataVectorizationSourceType, OnYourDataEndpointVectorizationSource, OnYourDataVectorSearchAuthenticationOptions, + OnYourDataVectorSearchAuthenticationOptionsUnion, + OnYourDataVectorSearchAuthenticationType, OnYourDataVectorSearchApiKeyAuthenticationOptions, OnYourDataVectorSearchAccessTokenAuthenticationOptions, - OnYourDataVectorSearchAuthenticationType, OnYourDataDeploymentNameVectorizationSource, OnYourDataModelIdVectorizationSource, - OnYourDataVectorizationSourceType, AzureMachineLearningIndexChatExtensionConfiguration, AzureMachineLearningIndexChatExtensionParameters, AzureCosmosDBChatExtensionConfiguration, @@ -84,17 +92,19 @@ export { PineconeChatExtensionConfiguration, PineconeChatExtensionParameters, PineconeFieldMappingOptions, - AzureChatExtensionType, AzureChatEnhancementConfiguration, AzureChatGroundingEnhancementConfiguration, AzureChatOCREnhancementConfiguration, ChatCompletionsResponseFormat, + ChatCompletionsResponseFormatUnion, ChatCompletionsTextResponseFormat, ChatCompletionsJsonResponseFormat, ChatCompletionsToolDefinition, + ChatCompletionsToolDefinitionUnion, ChatCompletionsFunctionToolDefinition, ChatCompletionsToolSelectionPreset, ChatCompletionsNamedToolSelection, + ChatCompletionsNamedToolSelectionUnion, ChatCompletionsNamedFunctionToolSelection, ChatCompletionsFunctionToolSelection, ChatCompletions, @@ -108,6 +118,7 @@ export { ChatTokenLogProbabilityResult, ChatTokenLogProbabilityInfo, ChatFinishDetails, + ChatFinishDetailsUnion, StopFinishDetails, MaxTokensFinishDetails, AzureChatEnhancements, @@ -132,18 +143,9 @@ export { Embeddings, EmbeddingItem, EmbeddingsUsage, - ServiceApiVersions, - ChatRequestMessageUnion, - ChatMessageContentItemUnion, - ChatCompletionsToolCallUnion, - AzureChatExtensionConfigurationUnion, - OnYourDataAuthenticationOptionsUnion, - OnYourDataVectorizationSourceUnion, - OnYourDataVectorSearchAuthenticationOptionsUnion, - ChatCompletionsResponseFormatUnion, - ChatCompletionsToolDefinitionUnion, - ChatCompletionsNamedToolSelectionUnion, - ChatFinishDetailsUnion, +} from "./models/index.js"; +export { + OpenAIClientOptionalParams, GetAudioTranscriptionAsPlainTextOptionalParams, GetAudioTranscriptionAsResponseObjectOptionalParams, GetAudioTranslationAsPlainTextOptionalParams, @@ -153,4 +155,4 @@ export { GetImageGenerationsOptionalParams, GenerateSpeechFromTextOptionalParams, GetEmbeddingsOptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/index.ts index 26b921d70b..342178fda2 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/index.ts @@ -30,27 +30,34 @@ export { CompletionsUsage, ChatCompletionsOptions, ChatRequestMessage, + ChatRequestMessageUnion, + ChatRole, ChatRequestSystemMessage, ChatRequestUserMessage, ChatMessageContentItem, + ChatMessageContentItemUnion, ChatMessageTextContentItem, ChatMessageImageContentItem, ChatMessageImageUrl, ChatMessageImageDetailLevel, ChatRequestAssistantMessage, ChatCompletionsToolCall, + ChatCompletionsToolCallUnion, ChatCompletionsFunctionToolCall, FunctionCall, ChatRequestToolMessage, ChatRequestFunctionMessage, - ChatRole, FunctionDefinition, FunctionCallPreset, FunctionName, AzureChatExtensionConfiguration, + AzureChatExtensionConfigurationUnion, + AzureChatExtensionType, AzureSearchChatExtensionConfiguration, AzureSearchChatExtensionParameters, OnYourDataAuthenticationOptions, + OnYourDataAuthenticationOptionsUnion, + OnYourDataAuthenticationType, OnYourDataApiKeyAuthenticationOptions, OnYourDataConnectionStringAuthenticationOptions, OnYourDataKeyAndKeyIdAuthenticationOptions, @@ -58,19 +65,20 @@ export { OnYourDataAccessTokenAuthenticationOptions, OnYourDataSystemAssignedManagedIdentityAuthenticationOptions, OnYourDataUserAssignedManagedIdentityAuthenticationOptions, - OnYourDataAuthenticationType, OnYourDataContextProperty, AzureSearchIndexFieldMappingOptions, AzureSearchQueryType, OnYourDataVectorizationSource, + OnYourDataVectorizationSourceUnion, + OnYourDataVectorizationSourceType, OnYourDataEndpointVectorizationSource, OnYourDataVectorSearchAuthenticationOptions, + OnYourDataVectorSearchAuthenticationOptionsUnion, + OnYourDataVectorSearchAuthenticationType, OnYourDataVectorSearchApiKeyAuthenticationOptions, OnYourDataVectorSearchAccessTokenAuthenticationOptions, - OnYourDataVectorSearchAuthenticationType, OnYourDataDeploymentNameVectorizationSource, OnYourDataModelIdVectorizationSource, - OnYourDataVectorizationSourceType, AzureMachineLearningIndexChatExtensionConfiguration, AzureMachineLearningIndexChatExtensionParameters, AzureCosmosDBChatExtensionConfiguration, @@ -83,17 +91,19 @@ export { PineconeChatExtensionConfiguration, PineconeChatExtensionParameters, PineconeFieldMappingOptions, - AzureChatExtensionType, AzureChatEnhancementConfiguration, AzureChatGroundingEnhancementConfiguration, AzureChatOCREnhancementConfiguration, ChatCompletionsResponseFormat, + ChatCompletionsResponseFormatUnion, ChatCompletionsTextResponseFormat, ChatCompletionsJsonResponseFormat, ChatCompletionsToolDefinition, + ChatCompletionsToolDefinitionUnion, ChatCompletionsFunctionToolDefinition, ChatCompletionsToolSelectionPreset, ChatCompletionsNamedToolSelection, + ChatCompletionsNamedToolSelectionUnion, ChatCompletionsNamedFunctionToolSelection, ChatCompletionsFunctionToolSelection, ChatCompletions, @@ -107,6 +117,7 @@ export { ChatTokenLogProbabilityResult, ChatTokenLogProbabilityInfo, ChatFinishDetails, + ChatFinishDetailsUnion, StopFinishDetails, MaxTokensFinishDetails, AzureChatEnhancements, @@ -131,27 +142,4 @@ export { Embeddings, EmbeddingItem, EmbeddingsUsage, - ServiceApiVersions, - ChatRequestMessageUnion, - ChatMessageContentItemUnion, - ChatCompletionsToolCallUnion, - AzureChatExtensionConfigurationUnion, - OnYourDataAuthenticationOptionsUnion, - OnYourDataVectorizationSourceUnion, - OnYourDataVectorSearchAuthenticationOptionsUnion, - ChatCompletionsResponseFormatUnion, - ChatCompletionsToolDefinitionUnion, - ChatCompletionsNamedToolSelectionUnion, - ChatFinishDetailsUnion, } from "./models.js"; -export { - GetAudioTranscriptionAsPlainTextOptionalParams, - GetAudioTranscriptionAsResponseObjectOptionalParams, - GetAudioTranslationAsPlainTextOptionalParams, - GetAudioTranslationAsResponseObjectOptionalParams, - GetCompletionsOptionalParams, - GetChatCompletionsOptionalParams, - GetImageGenerationsOptionalParams, - GenerateSpeechFromTextOptionalParams, - GetEmbeddingsOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts index 4043260ae4..9e11b915ca 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts @@ -1,9 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { serializeRecord } from "../helpers/serializerHelpers.js"; -import { ErrorModel } from "@azure-rest/core-client"; import { uint8ArrayToString } from "@azure/core-util"; +import { ErrorModel } from "@azure-rest/core-client"; /** The configuration information for an audio transcription request. */ export interface AudioTranscriptionOptions { @@ -46,7 +45,7 @@ export interface AudioTranscriptionOptions { export function audioTranscriptionOptionsSerializer( item: AudioTranscriptionOptions, -): Record { +): any { return { file: uint8ArrayToString(item["file"], "base64"), filename: item["filename"], @@ -54,7 +53,11 @@ export function audioTranscriptionOptionsSerializer( language: item["language"], prompt: item["prompt"], temperature: item["temperature"], - timestamp_granularities: item["timestampGranularities"], + timestamp_granularities: !item["timestampGranularities"] + ? item["timestampGranularities"] + : item["timestampGranularities"].map((p: any) => { + return p; + }), model: item["model"], }; } @@ -88,6 +91,21 @@ export interface AudioTranscription { words?: AudioTranscriptionWord[]; } +export function audioTranscriptionDeserializer(item: any): AudioTranscription { + return { + text: item["text"], + task: item["task"], + language: item["language"], + duration: item["duration"], + segments: !item["segments"] + ? item["segments"] + : audioTranscriptionSegmentArrayDeserializer(item["segments"]), + words: !item["words"] + ? item["words"] + : audioTranscriptionWordArrayDeserializer(item["words"]), + }; +} + /** Defines the possible descriptors for available audio operation responses. */ export type AudioTaskLabel = "transcribe" | "translate"; @@ -125,6 +143,33 @@ export interface AudioTranscriptionSegment { seek: number; } +export function audioTranscriptionSegmentDeserializer( + item: any, +): AudioTranscriptionSegment { + return { + id: item["id"], + start: item["start"], + end: item["end"], + text: item["text"], + temperature: item["temperature"], + avgLogprob: item["avg_logprob"], + compressionRatio: item["compression_ratio"], + noSpeechProb: item["no_speech_prob"], + tokens: item["tokens"].map((p: any) => { + return p; + }), + seek: item["seek"], + }; +} + +export function audioTranscriptionSegmentArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return audioTranscriptionSegmentDeserializer(item); + }); +} + /** Extended information about a single transcribed word, as provided on responses when the 'word' timestamp granularity is provided. */ export interface AudioTranscriptionWord { /** The textual content of the word. */ @@ -135,6 +180,24 @@ export interface AudioTranscriptionWord { end: number; } +export function audioTranscriptionWordDeserializer( + item: any, +): AudioTranscriptionWord { + return { + word: item["word"], + start: item["start"], + end: item["end"], + }; +} + +export function audioTranscriptionWordArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return audioTranscriptionWordDeserializer(item); + }); +} + /** The configuration information for an audio translation request. */ export interface AudioTranslationOptions { /** @@ -163,7 +226,7 @@ export interface AudioTranslationOptions { export function audioTranslationOptionsSerializer( item: AudioTranslationOptions, -): Record { +): any { return { file: uint8ArrayToString(item["file"], "base64"), filename: item["filename"], @@ -199,6 +262,18 @@ export interface AudioTranslation { segments?: AudioTranslationSegment[]; } +export function audioTranslationDeserializer(item: any): AudioTranslation { + return { + text: item["text"], + task: item["task"], + language: item["language"], + duration: item["duration"], + segments: !item["segments"] + ? item["segments"] + : audioTranslationSegmentArrayDeserializer(item["segments"]), + }; +} + /** * Extended information about a single segment of translated audio data. * Segments generally represent roughly 5-10 seconds of speech. Segment boundaries typically occur between words but not @@ -233,6 +308,33 @@ export interface AudioTranslationSegment { seek: number; } +export function audioTranslationSegmentDeserializer( + item: any, +): AudioTranslationSegment { + return { + id: item["id"], + start: item["start"], + end: item["end"], + text: item["text"], + temperature: item["temperature"], + avgLogprob: item["avg_logprob"], + compressionRatio: item["compression_ratio"], + noSpeechProb: item["no_speech_prob"], + tokens: item["tokens"].map((p: any) => { + return p; + }), + seek: item["seek"], + }; +} + +export function audioTranslationSegmentArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return audioTranslationSegmentDeserializer(item); + }); +} + /** * The configuration information for a completions request. * Completions support a wide variety of tasks and generate text that continues from or "completes" @@ -327,23 +429,25 @@ export interface CompletionsOptions { model?: string; } -export function completionsOptionsSerializer( - item: CompletionsOptions, -): Record { +export function completionsOptionsSerializer(item: CompletionsOptions): any { return { - prompt: item["prompt"], + prompt: item["prompt"].map((p: any) => { + return p; + }), max_tokens: item["maxTokens"], temperature: item["temperature"], top_p: item["topP"], - logit_bias: !item.logitBias - ? item.logitBias - : (serializeRecord(item.logitBias as any) as any), + logit_bias: item["logitBias"], user: item["user"], n: item["n"], logprobs: item["logprobs"], suffix: item["suffix"], echo: item["echo"], - stop: item["stop"], + stop: !item["stop"] + ? item["stop"] + : item["stop"].map((p: any) => { + return p; + }), presence_penalty: item["presencePenalty"], frequency_penalty: item["frequencyPenalty"], best_of: item["bestOf"], @@ -380,6 +484,20 @@ export interface Completions { usage: CompletionsUsage; } +export function completionsDeserializer(item: any): Completions { + return { + id: item["id"], + created: new Date(item["created"]), + promptFilterResults: !item["prompt_filter_results"] + ? item["prompt_filter_results"] + : contentFilterResultsForPromptArrayDeserializer( + item["prompt_filter_results"], + ), + choices: choiceArrayDeserializer(item["choices"]), + usage: completionsUsageDeserializer(item["usage"]), + }; +} + /** Content filtering results for a single prompt in the request. */ export interface ContentFilterResultsForPrompt { /** The index of this prompt in the set of prompt results */ @@ -388,6 +506,17 @@ export interface ContentFilterResultsForPrompt { contentFilterResults: ContentFilterResultDetailsForPrompt; } +export function contentFilterResultsForPromptDeserializer( + item: any, +): ContentFilterResultsForPrompt { + return { + promptIndex: item["prompt_index"], + contentFilterResults: contentFilterResultDetailsForPromptDeserializer( + item["content_filter_results"], + ), + }; +} + /** Information about content filtering evaluated against input data to Azure OpenAI. */ export interface ContentFilterResultDetailsForPrompt { /** @@ -430,6 +559,38 @@ export interface ContentFilterResultDetailsForPrompt { indirectAttack?: ContentFilterDetectionResult; } +export function contentFilterResultDetailsForPromptDeserializer( + item: any, +): ContentFilterResultDetailsForPrompt { + return { + sexual: !item["sexual"] + ? item["sexual"] + : contentFilterResultDeserializer(item["sexual"]), + violence: !item["violence"] + ? item["violence"] + : contentFilterResultDeserializer(item["violence"]), + hate: !item["hate"] + ? item["hate"] + : contentFilterResultDeserializer(item["hate"]), + selfHarm: !item["self_harm"] + ? item["self_harm"] + : contentFilterResultDeserializer(item["self_harm"]), + profanity: !item["profanity"] + ? item["profanity"] + : contentFilterDetectionResultDeserializer(item["profanity"]), + customBlocklists: !item["custom_blocklists"] + ? item["custom_blocklists"] + : contentFilterDetailedResultsDeserializer(item["custom_blocklists"]), + error: !item["error"] ? item["error"] : item["error"], + jailbreak: !item["jailbreak"] + ? item["jailbreak"] + : contentFilterDetectionResultDeserializer(item["jailbreak"]), + indirectAttack: !item["indirect_attack"] + ? item["indirect_attack"] + : contentFilterDetectionResultDeserializer(item["indirect_attack"]), + }; +} + /** Information about filtered content severity level and if it has been filtered or not. */ export interface ContentFilterResult { /** A value indicating whether or not the content has been filtered. */ @@ -438,6 +599,15 @@ export interface ContentFilterResult { severity: ContentFilterSeverity; } +export function contentFilterResultDeserializer( + item: any, +): ContentFilterResult { + return { + filtered: item["filtered"], + severity: item["severity"], + }; +} + /** Ratings for the intensity and risk level of harmful content. */ export type ContentFilterSeverity = "safe" | "low" | "medium" | "high"; @@ -449,6 +619,15 @@ export interface ContentFilterDetectionResult { detected: boolean; } +export function contentFilterDetectionResultDeserializer( + item: any, +): ContentFilterDetectionResult { + return { + filtered: item["filtered"], + detected: item["detected"], + }; +} + /** Represents a structured collection of result details for content filtering. */ export interface ContentFilterDetailedResults { /** A value indicating whether or not the content has been filtered. */ @@ -457,6 +636,15 @@ export interface ContentFilterDetailedResults { details: ContentFilterBlocklistIdResult[]; } +export function contentFilterDetailedResultsDeserializer( + item: any, +): ContentFilterDetailedResults { + return { + filtered: item["filtered"], + details: contentFilterBlocklistIdResultArrayDeserializer(item["details"]), + }; +} + /** Represents the outcome of an evaluation against a custom blocklist as performed by content filtering. */ export interface ContentFilterBlocklistIdResult { /** A value indicating whether or not the content has been filtered. */ @@ -465,6 +653,31 @@ export interface ContentFilterBlocklistIdResult { id: string; } +export function contentFilterBlocklistIdResultDeserializer( + item: any, +): ContentFilterBlocklistIdResult { + return { + filtered: item["filtered"], + id: item["id"], + }; +} + +export function contentFilterBlocklistIdResultArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return contentFilterBlocklistIdResultDeserializer(item); + }); +} + +export function contentFilterResultsForPromptArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return contentFilterResultsForPromptDeserializer(item); + }); +} + /** * The representation of a single prompt completion as part of an overall completions request. * Generally, `n` choices are generated per provided prompt with a default value of 1. @@ -487,6 +700,20 @@ export interface Choice { finishReason: CompletionsFinishReason | null; } +export function choiceDeserializer(item: any): Choice { + return { + text: item["text"], + index: item["index"], + contentFilterResults: !item["content_filter_results"] + ? item["content_filter_results"] + : contentFilterResultsForChoiceDeserializer( + item["content_filter_results"], + ), + logprobs: item["logprobs"], + finishReason: item["finish_reason"], + }; +} + /** Information about content filtering evaluated against generated model output. */ export interface ContentFilterResultsForChoice { /** @@ -529,6 +756,42 @@ export interface ContentFilterResultsForChoice { protectedMaterialCode?: ContentFilterCitedDetectionResult; } +export function contentFilterResultsForChoiceDeserializer( + item: any, +): ContentFilterResultsForChoice { + return { + sexual: !item["sexual"] + ? item["sexual"] + : contentFilterResultDeserializer(item["sexual"]), + violence: !item["violence"] + ? item["violence"] + : contentFilterResultDeserializer(item["violence"]), + hate: !item["hate"] + ? item["hate"] + : contentFilterResultDeserializer(item["hate"]), + selfHarm: !item["self_harm"] + ? item["self_harm"] + : contentFilterResultDeserializer(item["self_harm"]), + profanity: !item["profanity"] + ? item["profanity"] + : contentFilterDetectionResultDeserializer(item["profanity"]), + customBlocklists: !item["custom_blocklists"] + ? item["custom_blocklists"] + : contentFilterDetailedResultsDeserializer(item["custom_blocklists"]), + error: !item["error"] ? item["error"] : item["error"], + protectedMaterialText: !item["protected_material_text"] + ? item["protected_material_text"] + : contentFilterDetectionResultDeserializer( + item["protected_material_text"], + ), + protectedMaterialCode: !item["protected_material_code"] + ? item["protected_material_code"] + : contentFilterCitedDetectionResultDeserializer( + item["protected_material_code"], + ), + }; +} + /** Represents the outcome of a detection operation against protected resources as performed by content filtering. */ export interface ContentFilterCitedDetectionResult { /** A value indicating whether or not the content has been filtered. */ @@ -541,6 +804,17 @@ export interface ContentFilterCitedDetectionResult { license: string; } +export function contentFilterCitedDetectionResultDeserializer( + item: any, +): ContentFilterCitedDetectionResult { + return { + filtered: item["filtered"], + detected: item["detected"], + url: item["URL"], + license: item["license"], + }; +} + /** Representation of a log probabilities model for a completions generation. */ export interface CompletionsLogProbabilityModel { /** The textual forms of tokens evaluated in this probability model. */ @@ -553,6 +827,25 @@ export interface CompletionsLogProbabilityModel { textOffset: number[]; } +export function completionsLogProbabilityModelDeserializer( + item: any, +): CompletionsLogProbabilityModel { + return { + tokens: item["tokens"].map((p: any) => { + return p; + }), + tokenLogprobs: item["token_logprobs"].map((p: any) => { + return !p ? p : p; + }), + topLogprobs: item["top_logprobs"].map((p: any) => { + return p; + }), + textOffset: item["text_offset"].map((p: any) => { + return p; + }), + }; +} + /** Representation of the manner in which a completions response concluded. */ export type CompletionsFinishReason = | "stop" @@ -561,6 +854,12 @@ export type CompletionsFinishReason = | "function_call" | "tool_calls"; +export function choiceArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return choiceDeserializer(item); + }); +} + /** * Representation of the token counts processed for a completions request. * Counts consider all tokens across prompts, choices, choice alternates, best_of generations, and @@ -575,6 +874,14 @@ export interface CompletionsUsage { totalTokens: number; } +export function completionsUsageDeserializer(item: any): CompletionsUsage { + return { + completionTokens: item["completion_tokens"], + promptTokens: item["prompt_tokens"], + totalTokens: item["total_tokens"], + }; +} + /** * The configuration information for a chat completions request. * Completions support a wide variety of tasks and generate text that continues from or "completes" @@ -676,7 +983,7 @@ export interface ChatCompletionsOptions { /** Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. This option is currently not available on the `gpt-4-vision-preview` model. */ logprobs?: boolean | null; /** An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. */ - topLogprobs?: number | null; + top_logprobs?: number | null; /** An object specifying the format that the model must output. Used to enable JSON mode. */ responseFormat?: ChatCompletionsResponseFormatUnion; /** The available tool definitions that the chat completions request can use, including caller-defined functions. */ @@ -689,56 +996,76 @@ export interface ChatCompletionsOptions { export function chatCompletionsOptionsSerializer( item: ChatCompletionsOptions, -): Record { - return { - messages: item["messages"].map((p) => chatRequestMessageUnionSerializer(p)), - functions: - item["functions"] === undefined - ? item["functions"] - : item["functions"].map(functionDefinitionSerializer), - function_call: item["functionCall"] as any, +): any { + return { + messages: chatRequestMessageUnionArraySerializer(item["messages"]), + functions: !item["functions"] + ? item["functions"] + : functionDefinitionArraySerializer(item["functions"]), + function_call: !item["functionCall"] + ? item["functionCall"] + : _chatCompletionsOptionsFunctionCallSerializer(item["functionCall"]), max_tokens: item["maxTokens"], temperature: item["temperature"], top_p: item["topP"], - logit_bias: !item.logitBias - ? item.logitBias - : (serializeRecord(item.logitBias as any) as any), + logit_bias: item["logitBias"], user: item["user"], n: item["n"], - stop: item["stop"], + stop: !item["stop"] + ? item["stop"] + : item["stop"].map((p: any) => { + return p; + }), presence_penalty: item["presencePenalty"], frequency_penalty: item["frequencyPenalty"], stream: item["stream"], model: item["model"], - data_sources: - item["dataSources"] === undefined - ? item["dataSources"] - : item["dataSources"].map((p) => - azureChatExtensionConfigurationUnionSerializer(p), - ), - enhancements: !item.enhancements - ? item.enhancements - : azureChatEnhancementConfigurationSerializer(item.enhancements), + data_sources: !item["dataSources"] + ? item["dataSources"] + : azureChatExtensionConfigurationUnionArraySerializer( + item["dataSources"], + ), + enhancements: !item["enhancements"] + ? item["enhancements"] + : azureChatEnhancementConfigurationSerializer(item["enhancements"]), seed: item["seed"], logprobs: item["logprobs"], - top_logprobs: item["topLogprobs"], - response_format: !item.responseFormat - ? item.responseFormat - : chatCompletionsResponseFormatUnionSerializer(item.responseFormat), - tools: item["tools"], - tool_choice: item["toolChoice"] as any, + top_logprobs: item["top_logprobs"], + response_format: !item["responseFormat"] + ? item["responseFormat"] + : chatCompletionsResponseFormatUnionSerializer(item["responseFormat"]), + tools: !item["tools"] + ? item["tools"] + : chatCompletionsToolDefinitionUnionArraySerializer(item["tools"]), + tool_choice: !item["toolChoice"] + ? item["toolChoice"] + : _chatCompletionsOptionsToolChoiceSerializer(item["toolChoice"]), }; } /** An abstract representation of a chat message as provided in a request. */ export interface ChatRequestMessage { - /** the discriminator possible values: system, user, assistant, tool, function */ + /** The chat role associated with this message. */ + /** The discriminator possible values: system, user, assistant, tool, function */ role: ChatRole; } +export function chatRequestMessageSerializer(item: ChatRequestMessage): any { + return { role: item["role"] }; +} + +/** Alias for ChatRequestMessageUnion */ +export type ChatRequestMessageUnion = + | ChatRequestSystemMessage + | ChatRequestUserMessage + | ChatRequestAssistantMessage + | ChatRequestToolMessage + | ChatRequestFunctionMessage + | ChatRequestMessage; + export function chatRequestMessageUnionSerializer( item: ChatRequestMessageUnion, -) { +): any { switch (item.role) { case "system": return chatRequestSystemMessageSerializer( @@ -766,13 +1093,8 @@ export function chatRequestMessageUnionSerializer( } } -export function chatRequestMessageSerializer( - item: ChatRequestMessageUnion, -): Record { - return { - ...chatRequestMessageUnionSerializer(item), - }; -} +/** A description of the intended purpose of a message within a chat completions interaction. */ +export type ChatRole = "system" | "assistant" | "user" | "function" | "tool"; /** * A request chat message containing system instructions that influence how the model will generate a chat completions @@ -789,12 +1111,8 @@ export interface ChatRequestSystemMessage extends ChatRequestMessage { export function chatRequestSystemMessageSerializer( item: ChatRequestSystemMessage, -): Record { - return { - role: item["role"], - content: item["content"], - name: item["name"], - }; +): any { + return { role: item["role"], content: item["content"], name: item["name"] }; } /** A request chat message representing user input to the assistant. */ @@ -809,23 +1127,53 @@ export interface ChatRequestUserMessage extends ChatRequestMessage { export function chatRequestUserMessageSerializer( item: ChatRequestUserMessage, -): Record { +): any { return { role: item["role"], - content: item["content"] as any, + content: _chatRequestUserMessageContentSerializer(item["content"]), name: item["name"], }; } +/** Alias for _ChatRequestUserMessageContent */ +export type _ChatRequestUserMessageContent = + | string + | ChatMessageContentItemUnion[]; + +export function _chatRequestUserMessageContentSerializer( + item: _ChatRequestUserMessageContent, +): any { + return item; +} + +export function _chatRequestUserMessageContentDeserializer( + item: any, +): _ChatRequestUserMessageContent { + return item; +} + /** An abstract representation of a structured content item within a chat message. */ export interface ChatMessageContentItem { - /** the discriminator possible values: text, image_url */ + /** The discriminated object type. */ + /** The discriminator possible values: text, image_url */ type: string; } +export function chatMessageContentItemSerializer( + item: ChatMessageContentItem, +): any { + return { type: item["type"] }; +} + +/** Alias for ChatMessageContentItemUnion */ +export type ChatMessageContentItemUnion = + | ChatMessageTextContentItem + | ChatMessageImageContentItem + | ChatMessageContentItem; + export function chatMessageContentItemUnionSerializer( item: ChatMessageContentItemUnion, -) { +): any { switch (item.type) { case "text": return chatMessageTextContentItemSerializer( @@ -842,14 +1190,6 @@ export function chatMessageContentItemUnionSerializer( } } -export function chatMessageContentItemSerializer( - item: ChatMessageContentItemUnion, -): Record { - return { - ...chatMessageContentItemUnionSerializer(item), - }; -} - /** A structured chat content item containing plain text. */ export interface ChatMessageTextContentItem extends ChatMessageContentItem { /** The discriminated object type: always 'text' for this type. */ @@ -860,11 +1200,8 @@ export interface ChatMessageTextContentItem extends ChatMessageContentItem { export function chatMessageTextContentItemSerializer( item: ChatMessageTextContentItem, -): Record { - return { - type: item["type"], - text: item["text"], - }; +): any { + return { type: item["type"], text: item["text"] }; } /** A structured chat content item containing an image reference. */ @@ -877,10 +1214,10 @@ export interface ChatMessageImageContentItem extends ChatMessageContentItem { export function chatMessageImageContentItemSerializer( item: ChatMessageImageContentItem, -): Record { +): any { return { type: item["type"], - image_url: chatMessageImageUrlSerializer(item.imageUrl), + image_url: chatMessageImageUrlSerializer(item["imageUrl"]), }; } @@ -895,18 +1232,21 @@ export interface ChatMessageImageUrl { detail?: ChatMessageImageDetailLevel; } -export function chatMessageImageUrlSerializer( - item: ChatMessageImageUrl, -): Record { - return { - url: item["url"], - detail: item["detail"], - }; +export function chatMessageImageUrlSerializer(item: ChatMessageImageUrl): any { + return { url: item["url"], detail: item["detail"] }; } /** A representation of the possible image detail levels for image-based chat completions message content. */ export type ChatMessageImageDetailLevel = "auto" | "low" | "high"; +export function chatMessageContentItemUnionArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return chatMessageContentItemUnionSerializer(item); + }); +} + /** A request chat message representing response or action from the assistant. */ export interface ChatRequestAssistantMessage extends ChatRequestMessage { /** The chat role associated with this message, which is always 'assistant' for assistant messages. */ @@ -929,15 +1269,17 @@ export interface ChatRequestAssistantMessage extends ChatRequestMessage { export function chatRequestAssistantMessageSerializer( item: ChatRequestAssistantMessage, -): Record { +): any { return { role: item["role"], content: item["content"], name: item["name"], - tool_calls: item["toolCalls"], - function_call: !item.functionCall - ? item.functionCall - : functionCallSerializer(item.functionCall), + tool_calls: !item["toolCalls"] + ? item["toolCalls"] + : chatCompletionsToolCallUnionArraySerializer(item["toolCalls"]), + function_call: !item["functionCall"] + ? item["functionCall"] + : functionCallSerializer(item["functionCall"]), }; } @@ -946,15 +1288,36 @@ export function chatRequestAssistantMessageSerializer( * chat completion. */ export interface ChatCompletionsToolCall { - /** the discriminator possible values: function */ + /** The object type. */ + /** The discriminator possible values: function */ type: string; /** The ID of the tool call. */ id: string; } +export function chatCompletionsToolCallSerializer( + item: ChatCompletionsToolCall, +): any { + return { type: item["type"], id: item["id"] }; +} + +export function chatCompletionsToolCallDeserializer( + item: any, +): ChatCompletionsToolCall { + return { + type: item["type"], + id: item["id"], + }; +} + +/** Alias for ChatCompletionsToolCallUnion */ +export type ChatCompletionsToolCallUnion = + | ChatCompletionsFunctionToolCall + | ChatCompletionsToolCall; + export function chatCompletionsToolCallUnionSerializer( item: ChatCompletionsToolCallUnion, -) { +): any { switch (item.type) { case "function": return chatCompletionsFunctionToolCallSerializer( @@ -966,13 +1329,18 @@ export function chatCompletionsToolCallUnionSerializer( } } -export function chatCompletionsToolCallSerializer( - item: ChatCompletionsToolCallUnion, -): Record { - return { - type: item["type"], - id: item["id"], - }; +export function chatCompletionsToolCallUnionDeserializer( + item: any, +): ChatCompletionsToolCallUnion { + switch (item.type) { + case "function": + return chatCompletionsFunctionToolCallDeserializer( + item as ChatCompletionsFunctionToolCall, + ); + + default: + return chatCompletionsToolCallDeserializer(item); + } } /** @@ -989,11 +1357,21 @@ export interface ChatCompletionsFunctionToolCall export function chatCompletionsFunctionToolCallSerializer( item: ChatCompletionsFunctionToolCall, -): Record { +): any { + return { + type: item["type"], + id: item["id"], + function: functionCallSerializer(item["function"]), + }; +} + +export function chatCompletionsFunctionToolCallDeserializer( + item: any, +): ChatCompletionsFunctionToolCall { return { type: item["type"], id: item["id"], - function: functionCallSerializer(item.function), + function: functionCallDeserializer(item["function"]), }; } @@ -1010,15 +1388,33 @@ export interface FunctionCall { arguments: string; } -export function functionCallSerializer( - item: FunctionCall, -): Record { +export function functionCallSerializer(item: FunctionCall): any { + return { name: item["name"], arguments: item["arguments"] }; +} + +export function functionCallDeserializer(item: any): FunctionCall { return { name: item["name"], arguments: item["arguments"], }; } +export function chatCompletionsToolCallUnionArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return chatCompletionsToolCallUnionSerializer(item); + }); +} + +export function chatCompletionsToolCallUnionArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return chatCompletionsToolCallUnionDeserializer(item); + }); +} + /** A request chat message representing requested output from a configured tool. */ export interface ChatRequestToolMessage extends ChatRequestMessage { /** The chat role associated with this message, which is always 'tool' for tool messages. */ @@ -1031,7 +1427,7 @@ export interface ChatRequestToolMessage extends ChatRequestMessage { export function chatRequestToolMessageSerializer( item: ChatRequestToolMessage, -): Record { +): any { return { role: item["role"], content: item["content"], @@ -1051,16 +1447,17 @@ export interface ChatRequestFunctionMessage extends ChatRequestMessage { export function chatRequestFunctionMessageSerializer( item: ChatRequestFunctionMessage, -): Record { - return { - role: item["role"], - name: item["name"], - content: item["content"], - }; +): any { + return { role: item["role"], name: item["name"], content: item["content"] }; } -/** A description of the intended purpose of a message within a chat completions interaction. */ -export type ChatRole = "system" | "assistant" | "user" | "function" | "tool"; +export function chatRequestMessageUnionArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return chatRequestMessageUnionSerializer(item); + }); +} /** The definition of a caller-specified function that chat completions may invoke in response to matching user input. */ export interface FunctionDefinition { @@ -1075,9 +1472,7 @@ export interface FunctionDefinition { parameters?: any; } -export function functionDefinitionSerializer( - item: FunctionDefinition, -): Record { +export function functionDefinitionSerializer(item: FunctionDefinition): any { return { name: item["name"], description: item["description"], @@ -1085,6 +1480,31 @@ export function functionDefinitionSerializer( }; } +export function functionDefinitionArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return functionDefinitionSerializer(item); + }); +} + +/** Alias for _ChatCompletionsOptionsFunctionCall */ +export type _ChatCompletionsOptionsFunctionCall = + | FunctionCallPreset + | FunctionName; + +export function _chatCompletionsOptionsFunctionCallSerializer( + item: _ChatCompletionsOptionsFunctionCall, +): any { + return item; +} + +export function _chatCompletionsOptionsFunctionCallDeserializer( + item: any, +): _ChatCompletionsOptionsFunctionCall { + return item; +} + /** * The collection of predefined behaviors for handling request-provided function information in a chat completions * operation. @@ -1100,12 +1520,8 @@ export interface FunctionName { name: string; } -export function functionNameSerializer( - item: FunctionName, -): Record { - return { - name: item["name"], - }; +export function functionNameSerializer(item: FunctionName): any { + return { name: item["name"] }; } /** @@ -1114,13 +1530,32 @@ export function functionNameSerializer( * The use of this configuration is compatible only with Azure OpenAI. */ export interface AzureChatExtensionConfiguration { - /** the discriminator possible values: azure_search, azure_ml_index, azure_cosmos_db, elasticsearch, pinecone */ + /** + * The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + * Azure chat extensions are only compatible with Azure OpenAI. + */ + /** The discriminator possible values: azure_search, azure_ml_index, azure_cosmos_db, elasticsearch, pinecone */ type: AzureChatExtensionType; } +export function azureChatExtensionConfigurationSerializer( + item: AzureChatExtensionConfiguration, +): any { + return { type: item["type"] }; +} + +/** Alias for AzureChatExtensionConfigurationUnion */ +export type AzureChatExtensionConfigurationUnion = + | AzureSearchChatExtensionConfiguration + | AzureMachineLearningIndexChatExtensionConfiguration + | AzureCosmosDBChatExtensionConfiguration + | ElasticsearchChatExtensionConfiguration + | PineconeChatExtensionConfiguration + | AzureChatExtensionConfiguration; + export function azureChatExtensionConfigurationUnionSerializer( item: AzureChatExtensionConfigurationUnion, -) { +): any { switch (item.type) { case "azure_search": return azureSearchChatExtensionConfigurationSerializer( @@ -1152,13 +1587,17 @@ export function azureChatExtensionConfigurationUnionSerializer( } } -export function azureChatExtensionConfigurationSerializer( - item: AzureChatExtensionConfigurationUnion, -): Record { - return { - ...azureChatExtensionConfigurationUnionSerializer(item), - }; -} +/** + * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat + * completions request that should use Azure OpenAI chat extensions to augment the response behavior. + * The use of this configuration is compatible only with Azure OpenAI. + */ +export type AzureChatExtensionType = + | "azure_search" + | "azure_ml_index" + | "azure_cosmos_db" + | "elasticsearch" + | "pinecone"; /** * A specific representation of configurable options for Azure Search when using it as an Azure OpenAI chat @@ -1177,10 +1616,12 @@ export interface AzureSearchChatExtensionConfiguration export function azureSearchChatExtensionConfigurationSerializer( item: AzureSearchChatExtensionConfiguration, -): Record { +): any { return { type: item["type"], - parameters: azureSearchChatExtensionParametersSerializer(item.parameters), + parameters: azureSearchChatExtensionParametersSerializer( + item["parameters"], + ), }; } @@ -1232,41 +1673,65 @@ export interface AzureSearchChatExtensionParameters { export function azureSearchChatExtensionParametersSerializer( item: AzureSearchChatExtensionParameters, -): Record { +): any { return { - authentication: !item.authentication - ? item.authentication - : onYourDataAuthenticationOptionsUnionSerializer(item.authentication), + authentication: !item["authentication"] + ? item["authentication"] + : onYourDataAuthenticationOptionsUnionSerializer(item["authentication"]), top_n_documents: item["topNDocuments"], in_scope: item["inScope"], strictness: item["strictness"], role_information: item["roleInformation"], max_search_queries: item["maxSearchQueries"], allow_partial_result: item["allowPartialResult"], - include_contexts: item["includeContexts"], + include_contexts: !item["includeContexts"] + ? item["includeContexts"] + : item["includeContexts"].map((p: any) => { + return p; + }), endpoint: item["endpoint"], index_name: item["indexName"], - fields_mapping: !item.fieldsMapping - ? item.fieldsMapping - : azureSearchIndexFieldMappingOptionsSerializer(item.fieldsMapping), + fields_mapping: !item["fieldsMapping"] + ? item["fieldsMapping"] + : azureSearchIndexFieldMappingOptionsSerializer(item["fieldsMapping"]), query_type: item["queryType"], semantic_configuration: item["semanticConfiguration"], filter: item["filter"], - embedding_dependency: !item.embeddingDependency - ? item.embeddingDependency - : onYourDataVectorizationSourceUnionSerializer(item.embeddingDependency), + embedding_dependency: !item["embeddingDependency"] + ? item["embeddingDependency"] + : onYourDataVectorizationSourceUnionSerializer( + item["embeddingDependency"], + ), }; } /** The authentication options for Azure OpenAI On Your Data. */ export interface OnYourDataAuthenticationOptions { - /** the discriminator possible values: api_key, connection_string, key_and_key_id, encoded_api_key, access_token, system_assigned_managed_identity, user_assigned_managed_identity */ + /** The authentication type. */ + /** The discriminator possible values: api_key, connection_string, key_and_key_id, encoded_api_key, access_token, system_assigned_managed_identity, user_assigned_managed_identity */ type: OnYourDataAuthenticationType; } +export function onYourDataAuthenticationOptionsSerializer( + item: OnYourDataAuthenticationOptions, +): any { + return { type: item["type"] }; +} + +/** Alias for OnYourDataAuthenticationOptionsUnion */ +export type OnYourDataAuthenticationOptionsUnion = + | OnYourDataApiKeyAuthenticationOptions + | OnYourDataConnectionStringAuthenticationOptions + | OnYourDataKeyAndKeyIdAuthenticationOptions + | OnYourDataEncodedApiKeyAuthenticationOptions + | OnYourDataAccessTokenAuthenticationOptions + | OnYourDataSystemAssignedManagedIdentityAuthenticationOptions + | OnYourDataUserAssignedManagedIdentityAuthenticationOptions + | OnYourDataAuthenticationOptions; + export function onYourDataAuthenticationOptionsUnionSerializer( item: OnYourDataAuthenticationOptionsUnion, -) { +): any { switch (item.type) { case "api_key": return onYourDataApiKeyAuthenticationOptionsSerializer( @@ -1308,13 +1773,15 @@ export function onYourDataAuthenticationOptionsUnionSerializer( } } -export function onYourDataAuthenticationOptionsSerializer( - item: OnYourDataAuthenticationOptionsUnion, -): Record { - return { - ...onYourDataAuthenticationOptionsUnionSerializer(item), - }; -} +/** The authentication types supported with Azure OpenAI On Your Data. */ +export type OnYourDataAuthenticationType = + | "api_key" + | "connection_string" + | "key_and_key_id" + | "encoded_api_key" + | "access_token" + | "system_assigned_managed_identity" + | "user_assigned_managed_identity"; /** The authentication options for Azure OpenAI On Your Data when using an API key. */ export interface OnYourDataApiKeyAuthenticationOptions @@ -1327,11 +1794,8 @@ export interface OnYourDataApiKeyAuthenticationOptions export function onYourDataApiKeyAuthenticationOptionsSerializer( item: OnYourDataApiKeyAuthenticationOptions, -): Record { - return { - type: item["type"], - key: item["key"], - }; +): any { + return { type: item["type"], key: item["key"] }; } /** The authentication options for Azure OpenAI On Your Data when using a connection string. */ @@ -1345,11 +1809,8 @@ export interface OnYourDataConnectionStringAuthenticationOptions export function onYourDataConnectionStringAuthenticationOptionsSerializer( item: OnYourDataConnectionStringAuthenticationOptions, -): Record { - return { - type: item["type"], - connection_string: item["connectionString"], - }; +): any { + return { type: item["type"], connection_string: item["connectionString"] }; } /** The authentication options for Azure OpenAI On Your Data when using an Elasticsearch key and key ID pair. */ @@ -1365,12 +1826,8 @@ export interface OnYourDataKeyAndKeyIdAuthenticationOptions export function onYourDataKeyAndKeyIdAuthenticationOptionsSerializer( item: OnYourDataKeyAndKeyIdAuthenticationOptions, -): Record { - return { - type: item["type"], - key: item["key"], - key_id: item["keyId"], - }; +): any { + return { type: item["type"], key: item["key"], key_id: item["keyId"] }; } /** The authentication options for Azure OpenAI On Your Data when using an Elasticsearch encoded API key. */ @@ -1384,11 +1841,8 @@ export interface OnYourDataEncodedApiKeyAuthenticationOptions export function onYourDataEncodedApiKeyAuthenticationOptionsSerializer( item: OnYourDataEncodedApiKeyAuthenticationOptions, -): Record { - return { - type: item["type"], - encoded_api_key: item["encodedApiKey"], - }; +): any { + return { type: item["type"], encoded_api_key: item["encodedApiKey"] }; } /** The authentication options for Azure OpenAI On Your Data when using access token. */ @@ -1402,11 +1856,8 @@ export interface OnYourDataAccessTokenAuthenticationOptions export function onYourDataAccessTokenAuthenticationOptionsSerializer( item: OnYourDataAccessTokenAuthenticationOptions, -): Record { - return { - type: item["type"], - access_token: item["accessToken"], - }; +): any { + return { type: item["type"], access_token: item["accessToken"] }; } /** The authentication options for Azure OpenAI On Your Data when using a system-assigned managed identity. */ @@ -1418,10 +1869,8 @@ export interface OnYourDataSystemAssignedManagedIdentityAuthenticationOptions export function onYourDataSystemAssignedManagedIdentityAuthenticationOptionsSerializer( item: OnYourDataSystemAssignedManagedIdentityAuthenticationOptions, -): Record { - return { - type: item["type"], - }; +): any { + return { type: item["type"] }; } /** The authentication options for Azure OpenAI On Your Data when using a user-assigned managed identity. */ @@ -1435,22 +1884,13 @@ export interface OnYourDataUserAssignedManagedIdentityAuthenticationOptions export function onYourDataUserAssignedManagedIdentityAuthenticationOptionsSerializer( item: OnYourDataUserAssignedManagedIdentityAuthenticationOptions, -): Record { +): any { return { type: item["type"], managed_identity_resource_id: item["managedIdentityResourceId"], }; } -/** The authentication types supported with Azure OpenAI On Your Data. */ -export type OnYourDataAuthenticationType = - | "api_key" - | "connection_string" - | "key_and_key_id" - | "encoded_api_key" - | "access_token" - | "system_assigned_managed_identity" - | "user_assigned_managed_identity"; /** The context property. */ export type OnYourDataContextProperty = | "citations" @@ -1477,15 +1917,27 @@ export interface AzureSearchIndexFieldMappingOptions { export function azureSearchIndexFieldMappingOptionsSerializer( item: AzureSearchIndexFieldMappingOptions, -): Record { +): any { return { title_field: item["titleField"], url_field: item["urlField"], filepath_field: item["filepathField"], - content_fields: item["contentFields"], + content_fields: !item["contentFields"] + ? item["contentFields"] + : item["contentFields"].map((p: any) => { + return p; + }), content_fields_separator: item["contentFieldsSeparator"], - vector_fields: item["vectorFields"], - image_vector_fields: item["imageVectorFields"], + vector_fields: !item["vectorFields"] + ? item["vectorFields"] + : item["vectorFields"].map((p: any) => { + return p; + }), + image_vector_fields: !item["imageVectorFields"] + ? item["imageVectorFields"] + : item["imageVectorFields"].map((p: any) => { + return p; + }), }; } @@ -1499,13 +1951,27 @@ export type AzureSearchQueryType = /** An abstract representation of a vectorization source for Azure OpenAI On Your Data with vector search. */ export interface OnYourDataVectorizationSource { - /** the discriminator possible values: endpoint, deployment_name, model_id */ + /** The type of vectorization source to use. */ + /** The discriminator possible values: endpoint, deployment_name, model_id */ type: OnYourDataVectorizationSourceType; } +export function onYourDataVectorizationSourceSerializer( + item: OnYourDataVectorizationSource, +): any { + return { type: item["type"] }; +} + +/** Alias for OnYourDataVectorizationSourceUnion */ +export type OnYourDataVectorizationSourceUnion = + | OnYourDataEndpointVectorizationSource + | OnYourDataDeploymentNameVectorizationSource + | OnYourDataModelIdVectorizationSource + | OnYourDataVectorizationSource; + export function onYourDataVectorizationSourceUnionSerializer( item: OnYourDataVectorizationSourceUnion, -) { +): any { switch (item.type) { case "endpoint": return onYourDataEndpointVectorizationSourceSerializer( @@ -1527,13 +1993,14 @@ export function onYourDataVectorizationSourceUnionSerializer( } } -export function onYourDataVectorizationSourceSerializer( - item: OnYourDataVectorizationSourceUnion, -): Record { - return { - ...onYourDataVectorizationSourceUnionSerializer(item), - }; -} +/** + * Represents the available sources Azure OpenAI On Your Data can use to configure vectorization of data for use with + * vector search. + */ +export type OnYourDataVectorizationSourceType = + | "endpoint" + | "deployment_name" + | "model_id"; /** * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based @@ -1551,25 +2018,38 @@ export interface OnYourDataEndpointVectorizationSource export function onYourDataEndpointVectorizationSourceSerializer( item: OnYourDataEndpointVectorizationSource, -): Record { +): any { return { type: item["type"], endpoint: item["endpoint"], authentication: onYourDataVectorSearchAuthenticationOptionsUnionSerializer( - item.authentication, + item["authentication"], ), }; } /** The authentication options for Azure OpenAI On Your Data vector search. */ export interface OnYourDataVectorSearchAuthenticationOptions { - /** the discriminator possible values: api_key, access_token */ + /** The type of authentication to use. */ + /** The discriminator possible values: api_key, access_token */ type: OnYourDataVectorSearchAuthenticationType; } +export function onYourDataVectorSearchAuthenticationOptionsSerializer( + item: OnYourDataVectorSearchAuthenticationOptions, +): any { + return { type: item["type"] }; +} + +/** Alias for OnYourDataVectorSearchAuthenticationOptionsUnion */ +export type OnYourDataVectorSearchAuthenticationOptionsUnion = + | OnYourDataVectorSearchApiKeyAuthenticationOptions + | OnYourDataVectorSearchAccessTokenAuthenticationOptions + | OnYourDataVectorSearchAuthenticationOptions; + export function onYourDataVectorSearchAuthenticationOptionsUnionSerializer( item: OnYourDataVectorSearchAuthenticationOptionsUnion, -) { +): any { switch (item.type) { case "api_key": return onYourDataVectorSearchApiKeyAuthenticationOptionsSerializer( @@ -1586,13 +2066,10 @@ export function onYourDataVectorSearchAuthenticationOptionsUnionSerializer( } } -export function onYourDataVectorSearchAuthenticationOptionsSerializer( - item: OnYourDataVectorSearchAuthenticationOptionsUnion, -): Record { - return { - ...onYourDataVectorSearchAuthenticationOptionsUnionSerializer(item), - }; -} +/** The authentication types supported with Azure OpenAI On Your Data vector search. */ +export type OnYourDataVectorSearchAuthenticationType = + | "api_key" + | "access_token"; /** The authentication options for Azure OpenAI On Your Data when using an API key. */ export interface OnYourDataVectorSearchApiKeyAuthenticationOptions @@ -1605,11 +2082,8 @@ export interface OnYourDataVectorSearchApiKeyAuthenticationOptions export function onYourDataVectorSearchApiKeyAuthenticationOptionsSerializer( item: OnYourDataVectorSearchApiKeyAuthenticationOptions, -): Record { - return { - type: item["type"], - key: item["key"], - }; +): any { + return { type: item["type"], key: item["key"] }; } /** The authentication options for Azure OpenAI On Your Data vector search when using access token. */ @@ -1623,18 +2097,10 @@ export interface OnYourDataVectorSearchAccessTokenAuthenticationOptions export function onYourDataVectorSearchAccessTokenAuthenticationOptionsSerializer( item: OnYourDataVectorSearchAccessTokenAuthenticationOptions, -): Record { - return { - type: item["type"], - access_token: item["accessToken"], - }; +): any { + return { type: item["type"], access_token: item["accessToken"] }; } -/** The authentication types supported with Azure OpenAI On Your Data vector search. */ -export type OnYourDataVectorSearchAuthenticationType = - | "api_key" - | "access_token"; - /** * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based * on an internal embeddings model deployment name in the same Azure OpenAI resource. @@ -1651,7 +2117,7 @@ export interface OnYourDataDeploymentNameVectorizationSource export function onYourDataDeploymentNameVectorizationSourceSerializer( item: OnYourDataDeploymentNameVectorizationSource, -): Record { +): any { return { type: item["type"], deployment_name: item["deploymentName"], @@ -1673,22 +2139,10 @@ export interface OnYourDataModelIdVectorizationSource export function onYourDataModelIdVectorizationSourceSerializer( item: OnYourDataModelIdVectorizationSource, -): Record { - return { - type: item["type"], - model_id: item["modelId"], - }; +): any { + return { type: item["type"], model_id: item["modelId"] }; } -/** - * Represents the available sources Azure OpenAI On Your Data can use to configure vectorization of data for use with - * vector search. - */ -export type OnYourDataVectorizationSourceType = - | "endpoint" - | "deployment_name" - | "model_id"; - /** * A specific representation of configurable options for Azure Machine Learning vector index when using it as an Azure * OpenAI chat extension. @@ -1706,11 +2160,11 @@ export interface AzureMachineLearningIndexChatExtensionConfiguration export function azureMachineLearningIndexChatExtensionConfigurationSerializer( item: AzureMachineLearningIndexChatExtensionConfiguration, -): Record { +): any { return { type: item["type"], parameters: azureMachineLearningIndexChatExtensionParametersSerializer( - item.parameters, + item["parameters"], ), }; } @@ -1757,18 +2211,22 @@ export interface AzureMachineLearningIndexChatExtensionParameters { export function azureMachineLearningIndexChatExtensionParametersSerializer( item: AzureMachineLearningIndexChatExtensionParameters, -): Record { +): any { return { - authentication: !item.authentication - ? item.authentication - : onYourDataAuthenticationOptionsUnionSerializer(item.authentication), + authentication: !item["authentication"] + ? item["authentication"] + : onYourDataAuthenticationOptionsUnionSerializer(item["authentication"]), top_n_documents: item["topNDocuments"], in_scope: item["inScope"], strictness: item["strictness"], role_information: item["roleInformation"], max_search_queries: item["maxSearchQueries"], allow_partial_result: item["allowPartialResult"], - include_contexts: item["includeContexts"], + include_contexts: !item["includeContexts"] + ? item["includeContexts"] + : item["includeContexts"].map((p: any) => { + return p; + }), project_resource_id: item["projectResourceId"], name: item["name"], version: item["version"], @@ -1793,10 +2251,12 @@ export interface AzureCosmosDBChatExtensionConfiguration export function azureCosmosDBChatExtensionConfigurationSerializer( item: AzureCosmosDBChatExtensionConfiguration, -): Record { +): any { return { type: item["type"], - parameters: azureCosmosDBChatExtensionParametersSerializer(item.parameters), + parameters: azureCosmosDBChatExtensionParametersSerializer( + item["parameters"], + ), }; } @@ -1847,26 +2307,30 @@ export interface AzureCosmosDBChatExtensionParameters { export function azureCosmosDBChatExtensionParametersSerializer( item: AzureCosmosDBChatExtensionParameters, -): Record { +): any { return { - authentication: !item.authentication - ? item.authentication - : onYourDataAuthenticationOptionsUnionSerializer(item.authentication), + authentication: !item["authentication"] + ? item["authentication"] + : onYourDataAuthenticationOptionsUnionSerializer(item["authentication"]), top_n_documents: item["topNDocuments"], in_scope: item["inScope"], strictness: item["strictness"], role_information: item["roleInformation"], max_search_queries: item["maxSearchQueries"], allow_partial_result: item["allowPartialResult"], - include_contexts: item["includeContexts"], + include_contexts: !item["includeContexts"] + ? item["includeContexts"] + : item["includeContexts"].map((p: any) => { + return p; + }), database_name: item["databaseName"], container_name: item["containerName"], index_name: item["indexName"], fields_mapping: azureCosmosDBFieldMappingOptionsSerializer( - item.fieldsMapping, + item["fieldsMapping"], ), embedding_dependency: onYourDataVectorizationSourceUnionSerializer( - item.embeddingDependency, + item["embeddingDependency"], ), }; } @@ -1889,14 +2353,18 @@ export interface AzureCosmosDBFieldMappingOptions { export function azureCosmosDBFieldMappingOptionsSerializer( item: AzureCosmosDBFieldMappingOptions, -): Record { +): any { return { title_field: item["titleField"], url_field: item["urlField"], filepath_field: item["filepathField"], - content_fields: item["contentFields"], + content_fields: item["contentFields"].map((p: any) => { + return p; + }), content_fields_separator: item["contentFieldsSeparator"], - vector_fields: item["vectorFields"], + vector_fields: item["vectorFields"].map((p: any) => { + return p; + }), }; } @@ -1917,10 +2385,12 @@ export interface ElasticsearchChatExtensionConfiguration export function elasticsearchChatExtensionConfigurationSerializer( item: ElasticsearchChatExtensionConfiguration, -): Record { +): any { return { type: item["type"], - parameters: elasticsearchChatExtensionParametersSerializer(item.parameters), + parameters: elasticsearchChatExtensionParametersSerializer( + item["parameters"], + ), }; } @@ -1968,27 +2438,33 @@ export interface ElasticsearchChatExtensionParameters { export function elasticsearchChatExtensionParametersSerializer( item: ElasticsearchChatExtensionParameters, -): Record { +): any { return { - authentication: !item.authentication - ? item.authentication - : onYourDataAuthenticationOptionsUnionSerializer(item.authentication), + authentication: !item["authentication"] + ? item["authentication"] + : onYourDataAuthenticationOptionsUnionSerializer(item["authentication"]), top_n_documents: item["topNDocuments"], in_scope: item["inScope"], strictness: item["strictness"], role_information: item["roleInformation"], max_search_queries: item["maxSearchQueries"], allow_partial_result: item["allowPartialResult"], - include_contexts: item["includeContexts"], + include_contexts: !item["includeContexts"] + ? item["includeContexts"] + : item["includeContexts"].map((p: any) => { + return p; + }), endpoint: item["endpoint"], index_name: item["indexName"], - fields_mapping: !item.fieldsMapping - ? item.fieldsMapping - : elasticsearchIndexFieldMappingOptionsSerializer(item.fieldsMapping), + fields_mapping: !item["fieldsMapping"] + ? item["fieldsMapping"] + : elasticsearchIndexFieldMappingOptionsSerializer(item["fieldsMapping"]), query_type: item["queryType"], - embedding_dependency: !item.embeddingDependency - ? item.embeddingDependency - : onYourDataVectorizationSourceUnionSerializer(item.embeddingDependency), + embedding_dependency: !item["embeddingDependency"] + ? item["embeddingDependency"] + : onYourDataVectorizationSourceUnionSerializer( + item["embeddingDependency"], + ), }; } @@ -2010,14 +2486,22 @@ export interface ElasticsearchIndexFieldMappingOptions { export function elasticsearchIndexFieldMappingOptionsSerializer( item: ElasticsearchIndexFieldMappingOptions, -): Record { +): any { return { title_field: item["titleField"], url_field: item["urlField"], filepath_field: item["filepathField"], - content_fields: item["contentFields"], + content_fields: !item["contentFields"] + ? item["contentFields"] + : item["contentFields"].map((p: any) => { + return p; + }), content_fields_separator: item["contentFieldsSeparator"], - vector_fields: item["vectorFields"], + vector_fields: !item["vectorFields"] + ? item["vectorFields"] + : item["vectorFields"].map((p: any) => { + return p; + }), }; } @@ -2041,10 +2525,10 @@ export interface PineconeChatExtensionConfiguration export function pineconeChatExtensionConfigurationSerializer( item: PineconeChatExtensionConfiguration, -): Record { +): any { return { type: item["type"], - parameters: pineconeChatExtensionParametersSerializer(item.parameters), + parameters: pineconeChatExtensionParametersSerializer(item["parameters"]), }; } @@ -2090,23 +2574,29 @@ export interface PineconeChatExtensionParameters { export function pineconeChatExtensionParametersSerializer( item: PineconeChatExtensionParameters, -): Record { +): any { return { - authentication: !item.authentication - ? item.authentication - : onYourDataAuthenticationOptionsUnionSerializer(item.authentication), + authentication: !item["authentication"] + ? item["authentication"] + : onYourDataAuthenticationOptionsUnionSerializer(item["authentication"]), top_n_documents: item["topNDocuments"], in_scope: item["inScope"], strictness: item["strictness"], role_information: item["roleInformation"], max_search_queries: item["maxSearchQueries"], allow_partial_result: item["allowPartialResult"], - include_contexts: item["includeContexts"], + include_contexts: !item["includeContexts"] + ? item["includeContexts"] + : item["includeContexts"].map((p: any) => { + return p; + }), environment: item["environment"], index_name: item["indexName"], - fields_mapping: pineconeFieldMappingOptionsSerializer(item.fieldsMapping), + fields_mapping: pineconeFieldMappingOptionsSerializer( + item["fieldsMapping"], + ), embedding_dependency: onYourDataVectorizationSourceUnionSerializer( - item.embeddingDependency, + item["embeddingDependency"], ), }; } @@ -2127,27 +2617,25 @@ export interface PineconeFieldMappingOptions { export function pineconeFieldMappingOptionsSerializer( item: PineconeFieldMappingOptions, -): Record { +): any { return { title_field: item["titleField"], url_field: item["urlField"], filepath_field: item["filepathField"], - content_fields: item["contentFields"], + content_fields: item["contentFields"].map((p: any) => { + return p; + }), content_fields_separator: item["contentFieldsSeparator"], }; } -/** - * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat - * completions request that should use Azure OpenAI chat extensions to augment the response behavior. - * The use of this configuration is compatible only with Azure OpenAI. - */ -export type AzureChatExtensionType = - | "azure_search" - | "azure_ml_index" - | "azure_cosmos_db" - | "elasticsearch" - | "pinecone"; +export function azureChatExtensionConfigurationUnionArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return azureChatExtensionConfigurationUnionSerializer(item); + }); +} /** A representation of the available Azure OpenAI enhancement configurations. */ export interface AzureChatEnhancementConfiguration { @@ -2159,14 +2647,14 @@ export interface AzureChatEnhancementConfiguration { export function azureChatEnhancementConfigurationSerializer( item: AzureChatEnhancementConfiguration, -): Record { +): any { return { - grounding: !item.grounding - ? item.grounding - : azureChatGroundingEnhancementConfigurationSerializer(item.grounding), - ocr: !item.ocr - ? item.ocr - : azureChatOCREnhancementConfigurationSerializer(item.ocr), + grounding: !item["grounding"] + ? item["grounding"] + : azureChatGroundingEnhancementConfigurationSerializer(item["grounding"]), + ocr: !item["ocr"] + ? item["ocr"] + : azureChatOCREnhancementConfigurationSerializer(item["ocr"]), }; } @@ -2178,10 +2666,8 @@ export interface AzureChatGroundingEnhancementConfiguration { export function azureChatGroundingEnhancementConfigurationSerializer( item: AzureChatGroundingEnhancementConfiguration, -): Record { - return { - enabled: item["enabled"], - }; +): any { + return { enabled: item["enabled"] }; } /** A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. */ @@ -2192,10 +2678,8 @@ export interface AzureChatOCREnhancementConfiguration { export function azureChatOCREnhancementConfigurationSerializer( item: AzureChatOCREnhancementConfiguration, -): Record { - return { - enabled: item["enabled"], - }; +): any { + return { enabled: item["enabled"] }; } /** @@ -2203,13 +2687,26 @@ export function azureChatOCREnhancementConfigurationSerializer( * mode. */ export interface ChatCompletionsResponseFormat { - /** the discriminator possible values: text, json_object */ + /** The discriminated type for the response format. */ + /** The discriminator possible values: text, json_object */ type: string; } +export function chatCompletionsResponseFormatSerializer( + item: ChatCompletionsResponseFormat, +): any { + return { type: item["type"] }; +} + +/** Alias for ChatCompletionsResponseFormatUnion */ +export type ChatCompletionsResponseFormatUnion = + | ChatCompletionsTextResponseFormat + | ChatCompletionsJsonResponseFormat + | ChatCompletionsResponseFormat; + export function chatCompletionsResponseFormatUnionSerializer( item: ChatCompletionsResponseFormatUnion, -) { +): any { switch (item.type) { case "text": return chatCompletionsTextResponseFormatSerializer( @@ -2226,14 +2723,6 @@ export function chatCompletionsResponseFormatUnionSerializer( } } -export function chatCompletionsResponseFormatSerializer( - item: ChatCompletionsResponseFormatUnion, -): Record { - return { - type: item["type"], - }; -} - /** * The standard Chat Completions response format that can freely generate text and is not guaranteed to produce response * content that adheres to a specific schema. @@ -2246,10 +2735,8 @@ export interface ChatCompletionsTextResponseFormat export function chatCompletionsTextResponseFormatSerializer( item: ChatCompletionsTextResponseFormat, -): Record { - return { - type: item["type"], - }; +): any { + return { type: item["type"] }; } /** A response format for Chat Completions that restricts responses to emitting valid JSON objects. */ @@ -2261,21 +2748,31 @@ export interface ChatCompletionsJsonResponseFormat export function chatCompletionsJsonResponseFormatSerializer( item: ChatCompletionsJsonResponseFormat, -): Record { - return { - type: item["type"], - }; +): any { + return { type: item["type"] }; } /** An abstract representation of a tool that can be used by the model to improve a chat completions response. */ export interface ChatCompletionsToolDefinition { - /** the discriminator possible values: function */ + /** The object type. */ + /** The discriminator possible values: function */ type: string; } +export function chatCompletionsToolDefinitionSerializer( + item: ChatCompletionsToolDefinition, +): any { + return { type: item["type"] }; +} + +/** Alias for ChatCompletionsToolDefinitionUnion */ +export type ChatCompletionsToolDefinitionUnion = + | ChatCompletionsFunctionToolDefinition + | ChatCompletionsToolDefinition; + export function chatCompletionsToolDefinitionUnionSerializer( item: ChatCompletionsToolDefinitionUnion, -) { +): any { switch (item.type) { case "function": return chatCompletionsFunctionToolDefinitionSerializer( @@ -2287,14 +2784,6 @@ export function chatCompletionsToolDefinitionUnionSerializer( } } -export function chatCompletionsToolDefinitionSerializer( - item: ChatCompletionsToolDefinitionUnion, -): Record { - return { - type: item["type"], - }; -} - /** The definition information for a chat completions function tool that can call a function in response to a tool call. */ export interface ChatCompletionsFunctionToolDefinition extends ChatCompletionsToolDefinition { @@ -2306,25 +2795,62 @@ export interface ChatCompletionsFunctionToolDefinition export function chatCompletionsFunctionToolDefinitionSerializer( item: ChatCompletionsFunctionToolDefinition, -): Record { +): any { return { type: item["type"], - function: functionDefinitionSerializer(item.function), + function: functionDefinitionSerializer(item["function"]), }; } +export function chatCompletionsToolDefinitionUnionArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return chatCompletionsToolDefinitionUnionSerializer(item); + }); +} + +/** Alias for _ChatCompletionsOptionsToolChoice */ +export type _ChatCompletionsOptionsToolChoice = + | ChatCompletionsToolSelectionPreset + | ChatCompletionsNamedToolSelectionUnion; + +export function _chatCompletionsOptionsToolChoiceSerializer( + item: _ChatCompletionsOptionsToolChoice, +): any { + return item; +} + +export function _chatCompletionsOptionsToolChoiceDeserializer( + item: any, +): _ChatCompletionsOptionsToolChoice { + return item; +} + /** Represents a generic policy for how a chat completions tool may be selected. */ export type ChatCompletionsToolSelectionPreset = "auto" | "none"; /** An abstract representation of an explicit, named tool selection to use for a chat completions request. */ export interface ChatCompletionsNamedToolSelection { - /** the discriminator possible values: function */ + /** The object type. */ + /** The discriminator possible values: function */ type: string; } +export function chatCompletionsNamedToolSelectionSerializer( + item: ChatCompletionsNamedToolSelection, +): any { + return { type: item["type"] }; +} + +/** Alias for ChatCompletionsNamedToolSelectionUnion */ +export type ChatCompletionsNamedToolSelectionUnion = + | ChatCompletionsNamedFunctionToolSelection + | ChatCompletionsNamedToolSelection; + export function chatCompletionsNamedToolSelectionUnionSerializer( item: ChatCompletionsNamedToolSelectionUnion, -) { +): any { switch (item.type) { case "function": return chatCompletionsNamedFunctionToolSelectionSerializer( @@ -2336,14 +2862,6 @@ export function chatCompletionsNamedToolSelectionUnionSerializer( } } -export function chatCompletionsNamedToolSelectionSerializer( - item: ChatCompletionsNamedToolSelectionUnion, -): Record { - return { - type: item["type"], - }; -} - /** A tool selection of a specific, named function tool that will limit chat completions to using the named function. */ export interface ChatCompletionsNamedFunctionToolSelection extends ChatCompletionsNamedToolSelection { @@ -2355,10 +2873,10 @@ export interface ChatCompletionsNamedFunctionToolSelection export function chatCompletionsNamedFunctionToolSelectionSerializer( item: ChatCompletionsNamedFunctionToolSelection, -): Record { +): any { return { type: item["type"], - function: chatCompletionsFunctionToolSelectionSerializer(item.function), + function: chatCompletionsFunctionToolSelectionSerializer(item["function"]), }; } @@ -2370,10 +2888,8 @@ export interface ChatCompletionsFunctionToolSelection { export function chatCompletionsFunctionToolSelectionSerializer( item: ChatCompletionsFunctionToolSelection, -): Record { - return { - name: item["name"], - }; +): any { + return { name: item["name"] }; } /** @@ -2411,6 +2927,22 @@ export interface ChatCompletions { usage: CompletionsUsage; } +export function chatCompletionsDeserializer(item: any): ChatCompletions { + return { + id: item["id"], + created: new Date(item["created"]), + choices: chatChoiceArrayDeserializer(item["choices"]), + model: item["model"], + promptFilterResults: !item["prompt_filter_results"] + ? item["prompt_filter_results"] + : contentFilterResultsForPromptArrayDeserializer( + item["prompt_filter_results"], + ), + systemFingerprint: item["system_fingerprint"], + usage: completionsUsageDeserializer(item["usage"]), + }; +} + /** * The representation of a single prompt completion as part of an overall chat completions request. * Generally, `n` choices are generated per provided prompt with a default value of 1. @@ -2446,6 +2978,31 @@ export interface ChatChoice { enhancements?: AzureChatEnhancements; } +export function chatChoiceDeserializer(item: any): ChatChoice { + return { + message: !item["message"] + ? item["message"] + : chatResponseMessageDeserializer(item["message"]), + logprobs: item["logprobs"], + index: item["index"], + finishReason: item["finish_reason"], + finishDetails: !item["finish_details"] + ? item["finish_details"] + : chatFinishDetailsUnionDeserializer(item["finish_details"]), + delta: !item["delta"] + ? item["delta"] + : chatResponseMessageDeserializer(item["delta"]), + contentFilterResults: !item["content_filter_results"] + ? item["content_filter_results"] + : contentFilterResultsForChoiceDeserializer( + item["content_filter_results"], + ), + enhancements: !item["enhancements"] + ? item["enhancements"] + : azureChatEnhancementsDeserializer(item["enhancements"]), + }; +} + /** A representation of a chat message as received in a response. */ export interface ChatResponseMessage { /** The chat role associated with the message. */ @@ -2469,6 +3026,24 @@ export interface ChatResponseMessage { context?: AzureChatExtensionsMessageContext; } +export function chatResponseMessageDeserializer( + item: any, +): ChatResponseMessage { + return { + role: item["role"], + content: item["content"], + toolCalls: !item["tool_calls"] + ? item["tool_calls"] + : chatCompletionsToolCallUnionArrayDeserializer(item["tool_calls"]), + functionCall: !item["function_call"] + ? item["function_call"] + : functionCallDeserializer(item["function_call"]), + context: !item["context"] + ? item["context"] + : azureChatExtensionsMessageContextDeserializer(item["context"]), + }; +} + /** * A representation of the additional context information available when Azure OpenAI chat extensions are involved * in the generation of a corresponding chat completions response. This context information is only populated when @@ -2488,6 +3063,24 @@ export interface AzureChatExtensionsMessageContext { allRetrievedDocuments?: AzureChatExtensionRetrievedDocument[]; } +export function azureChatExtensionsMessageContextDeserializer( + item: any, +): AzureChatExtensionsMessageContext { + return { + citations: !item["citations"] + ? item["citations"] + : azureChatExtensionDataSourceResponseCitationArrayDeserializer( + item["citations"], + ), + intent: item["intent"], + allRetrievedDocuments: !item["all_retrieved_documents"] + ? item["all_retrieved_documents"] + : azureChatExtensionRetrievedDocumentArrayDeserializer( + item["all_retrieved_documents"], + ), + }; +} + /** * A single instance of additional context information available when Azure OpenAI chat extensions are involved * in the generation of a corresponding chat completions response. This context information is only populated when @@ -2503,7 +3096,27 @@ export interface AzureChatExtensionDataSourceResponseCitation { /** The file path of the citation. */ filepath?: string; /** The chunk ID of the citation. */ - chunkId?: string; + chunk_id?: string; +} + +export function azureChatExtensionDataSourceResponseCitationDeserializer( + item: any, +): AzureChatExtensionDataSourceResponseCitation { + return { + content: item["content"], + title: item["title"], + url: item["url"], + filepath: item["filepath"], + chunk_id: item["chunk_id"], + }; +} + +export function azureChatExtensionDataSourceResponseCitationArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return azureChatExtensionDataSourceResponseCitationDeserializer(item); + }); } /** The retrieved document. */ @@ -2517,7 +3130,7 @@ export interface AzureChatExtensionRetrievedDocument { /** The file path of the citation. */ filepath?: string; /** The chunk ID of the citation. */ - chunkId?: string; + chunk_id?: string; /** The search queries used to retrieve the document. */ searchQueries: string[]; /** The index of the data source. */ @@ -2533,15 +3146,56 @@ export interface AzureChatExtensionRetrievedDocument { filterReason?: AzureChatExtensionRetrieveDocumentFilterReason; } +export function azureChatExtensionRetrievedDocumentDeserializer( + item: any, +): AzureChatExtensionRetrievedDocument { + return { + content: item["content"], + title: item["title"], + url: item["url"], + filepath: item["filepath"], + chunk_id: item["chunk_id"], + searchQueries: item["search_queries"].map((p: any) => { + return p; + }), + dataSourceIndex: item["data_source_index"], + originalSearchScore: item["original_search_score"], + rerankScore: item["rerank_score"], + filterReason: item["filter_reason"], + }; +} + /** The reason for filtering the retrieved document. */ export type AzureChatExtensionRetrieveDocumentFilterReason = "score" | "rerank"; +export function azureChatExtensionRetrievedDocumentArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return azureChatExtensionRetrievedDocumentDeserializer(item); + }); +} + /** Log probability information for a choice, as requested via 'logprobs' and 'top_logprobs'. */ export interface ChatChoiceLogProbabilityInfo { /** The list of log probability information entries for the choice's message content tokens, as requested via the 'logprobs' option. */ content: ChatTokenLogProbabilityResult[] | null; } +export function chatChoiceLogProbabilityInfoDeserializer( + item: any, +): ChatChoiceLogProbabilityInfo { + return { + content: !item["content"] + ? item["content"] + : !item["content"] + ? item["content"] + : item["content"].map((p: any) => { + return chatTokenLogProbabilityResultDeserializer(p); + }), + }; +} + /** A representation of the log probability information for a single content token, including a list of most likely tokens if 'top_logprobs' were requested. */ export interface ChatTokenLogProbabilityResult { /** The message content token. */ @@ -2551,7 +3205,30 @@ export interface ChatTokenLogProbabilityResult { /** A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. */ bytes: number[] | null; /** The list of most likely tokens and their log probability information, as requested via 'top_logprobs'. */ - topLogprobs: ChatTokenLogProbabilityInfo[] | null; + top_logprobs: ChatTokenLogProbabilityInfo[] | null; +} + +export function chatTokenLogProbabilityResultDeserializer( + item: any, +): ChatTokenLogProbabilityResult { + return { + token: item["token"], + logprob: item["logprob"], + bytes: !item["bytes"] + ? item["bytes"] + : !item["bytes"] + ? item["bytes"] + : item["bytes"].map((p: any) => { + return p; + }), + top_logprobs: !item["top_logprobs"] + ? item["top_logprobs"] + : !item["top_logprobs"] + ? item["top_logprobs"] + : item["top_logprobs"].map((p: any) => { + return chatTokenLogProbabilityInfoDeserializer(p); + }), + }; } /** A representation of the log probability information for a single message content token. */ @@ -2564,12 +3241,72 @@ export interface ChatTokenLogProbabilityInfo { bytes: number[] | null; } +export function chatTokenLogProbabilityInfoDeserializer( + item: any, +): ChatTokenLogProbabilityInfo { + return { + token: item["token"], + logprob: item["logprob"], + bytes: !item["bytes"] + ? item["bytes"] + : !item["bytes"] + ? item["bytes"] + : item["bytes"].map((p: any) => { + return p; + }), + }; +} + +export function chatTokenLogProbabilityInfoArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return chatTokenLogProbabilityInfoDeserializer(item); + }); +} + +export function chatTokenLogProbabilityResultArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return chatTokenLogProbabilityResultDeserializer(item); + }); +} + /** An abstract representation of structured information about why a chat completions response terminated. */ export interface ChatFinishDetails { - /** the discriminator possible values: stop, max_tokens */ + /** The object type. */ + /** The discriminator possible values: stop, max_tokens */ type: string; } +export function chatFinishDetailsDeserializer(item: any): ChatFinishDetails { + return { + type: item["type"], + }; +} + +/** Alias for ChatFinishDetailsUnion */ +export type ChatFinishDetailsUnion = + | StopFinishDetails + | MaxTokensFinishDetails + | ChatFinishDetails; + +export function chatFinishDetailsUnionDeserializer( + item: any, +): ChatFinishDetailsUnion { + switch (item.type) { + case "stop": + return stopFinishDetailsDeserializer(item as StopFinishDetails); + + case "max_tokens": + return maxTokensFinishDetailsDeserializer(item as MaxTokensFinishDetails); + + default: + return chatFinishDetailsDeserializer(item); + } +} + /** A structured representation of a stop reason that signifies natural termination by the model. */ export interface StopFinishDetails extends ChatFinishDetails { /** The object type, which is always 'stop' for this object. */ @@ -2578,6 +3315,13 @@ export interface StopFinishDetails extends ChatFinishDetails { stop: string; } +export function stopFinishDetailsDeserializer(item: any): StopFinishDetails { + return { + type: item["type"], + stop: item["stop"], + }; +} + /** * A structured representation of a stop reason that signifies a token limit was reached before the model could naturally * complete. @@ -2587,6 +3331,14 @@ export interface MaxTokensFinishDetails extends ChatFinishDetails { type: "max_tokens"; } +export function maxTokensFinishDetailsDeserializer( + item: any, +): MaxTokensFinishDetails { + return { + type: item["type"], + }; +} + /** * Represents the output results of Azure enhancements to chat completions, as configured via the matching input provided * in the request. @@ -2596,12 +3348,30 @@ export interface AzureChatEnhancements { grounding?: AzureGroundingEnhancement; } +export function azureChatEnhancementsDeserializer( + item: any, +): AzureChatEnhancements { + return { + grounding: !item["grounding"] + ? item["grounding"] + : azureGroundingEnhancementDeserializer(item["grounding"]), + }; +} + /** The grounding enhancement that returns the bounding box of the objects detected in the image. */ export interface AzureGroundingEnhancement { /** The lines of text detected by the grounding enhancement. */ lines: AzureGroundingEnhancementLine[]; } +export function azureGroundingEnhancementDeserializer( + item: any, +): AzureGroundingEnhancement { + return { + lines: azureGroundingEnhancementLineArrayDeserializer(item["lines"]), + }; +} + /** A content line object consisting of an adjacent sequence of content elements, such as words and selection marks. */ export interface AzureGroundingEnhancementLine { /** The text within the line. */ @@ -2610,6 +3380,15 @@ export interface AzureGroundingEnhancementLine { spans: AzureGroundingEnhancementLineSpan[]; } +export function azureGroundingEnhancementLineDeserializer( + item: any, +): AzureGroundingEnhancementLine { + return { + text: item["text"], + spans: azureGroundingEnhancementLineSpanArrayDeserializer(item["spans"]), + }; +} + /** A span object that represents a detected object and its bounding box information. */ export interface AzureGroundingEnhancementLineSpan { /** The text content of the span that represents the detected object. */ @@ -2625,6 +3404,19 @@ export interface AzureGroundingEnhancementLineSpan { polygon: AzureGroundingEnhancementCoordinatePoint[]; } +export function azureGroundingEnhancementLineSpanDeserializer( + item: any, +): AzureGroundingEnhancementLineSpan { + return { + text: item["text"], + offset: item["offset"], + length: item["length"], + polygon: azureGroundingEnhancementCoordinatePointArrayDeserializer( + item["polygon"], + ), + }; +} + /** A representation of a single polygon point as used by the Azure grounding enhancement. */ export interface AzureGroundingEnhancementCoordinatePoint { /** The x-coordinate (horizontal axis) of the point. */ @@ -2633,6 +3425,45 @@ export interface AzureGroundingEnhancementCoordinatePoint { y: number; } +export function azureGroundingEnhancementCoordinatePointDeserializer( + item: any, +): AzureGroundingEnhancementCoordinatePoint { + return { + x: item["x"], + y: item["y"], + }; +} + +export function azureGroundingEnhancementCoordinatePointArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return azureGroundingEnhancementCoordinatePointDeserializer(item); + }); +} + +export function azureGroundingEnhancementLineSpanArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return azureGroundingEnhancementLineSpanDeserializer(item); + }); +} + +export function azureGroundingEnhancementLineArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return azureGroundingEnhancementLineDeserializer(item); + }); +} + +export function chatChoiceArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return chatChoiceDeserializer(item); + }); +} + /** Represents the request data used to generate images. */ export interface ImageGenerationOptions { /** @@ -2672,7 +3503,7 @@ export interface ImageGenerationOptions { export function imageGenerationOptionsSerializer( item: ImageGenerationOptions, -): Record { +): any { return { model: item["model"], prompt: item["prompt"], @@ -2685,6 +3516,21 @@ export function imageGenerationOptionsSerializer( }; } +export function imageGenerationOptionsDeserializer( + item: any, +): ImageGenerationOptions { + return { + model: item["model"], + prompt: item["prompt"], + n: item["n"], + size: item["size"], + responseFormat: item["response_format"], + quality: item["quality"], + style: item["style"], + user: item["user"], + }; +} + /** The desired size of generated images. */ export type ImageSize = | "256x256" @@ -2716,6 +3562,13 @@ export interface ImageGenerations { data: ImageGenerationData[]; } +export function imageGenerationsDeserializer(item: any): ImageGenerations { + return { + created: new Date(item["created"]), + data: imageGenerationDataArrayDeserializer(item["data"]), + }; +} + /** * A representation of a single generated image, provided as either base64-encoded data or as a URL from which the image * may be retrieved. @@ -2743,6 +3596,26 @@ export interface ImageGenerationData { promptFilterResults?: ImageGenerationPromptFilterResults; } +export function imageGenerationDataDeserializer( + item: any, +): ImageGenerationData { + return { + url: item["url"], + base64Data: item["b64_json"], + contentFilterResults: !item["content_filter_results"] + ? item["content_filter_results"] + : imageGenerationContentFilterResultsDeserializer( + item["content_filter_results"], + ), + revisedPrompt: item["revised_prompt"], + promptFilterResults: !item["prompt_filter_results"] + ? item["prompt_filter_results"] + : imageGenerationPromptFilterResultsDeserializer( + item["prompt_filter_results"], + ), + }; +} + /** Describes the content filtering result for the image generation request. */ export interface ImageGenerationContentFilterResults { /** @@ -2772,6 +3645,25 @@ export interface ImageGenerationContentFilterResults { selfHarm?: ContentFilterResult; } +export function imageGenerationContentFilterResultsDeserializer( + item: any, +): ImageGenerationContentFilterResults { + return { + sexual: !item["sexual"] + ? item["sexual"] + : contentFilterResultDeserializer(item["sexual"]), + violence: !item["violence"] + ? item["violence"] + : contentFilterResultDeserializer(item["violence"]), + hate: !item["hate"] + ? item["hate"] + : contentFilterResultDeserializer(item["hate"]), + selfHarm: !item["self_harm"] + ? item["self_harm"] + : contentFilterResultDeserializer(item["self_harm"]), + }; +} + /** Describes the content filtering results for the prompt of a image generation request. */ export interface ImageGenerationPromptFilterResults { /** @@ -2807,6 +3699,42 @@ export interface ImageGenerationPromptFilterResults { customBlocklists?: ContentFilterDetailedResults; } +export function imageGenerationPromptFilterResultsDeserializer( + item: any, +): ImageGenerationPromptFilterResults { + return { + sexual: !item["sexual"] + ? item["sexual"] + : contentFilterResultDeserializer(item["sexual"]), + violence: !item["violence"] + ? item["violence"] + : contentFilterResultDeserializer(item["violence"]), + hate: !item["hate"] + ? item["hate"] + : contentFilterResultDeserializer(item["hate"]), + selfHarm: !item["self_harm"] + ? item["self_harm"] + : contentFilterResultDeserializer(item["self_harm"]), + profanity: !item["profanity"] + ? item["profanity"] + : contentFilterDetectionResultDeserializer(item["profanity"]), + jailbreak: !item["jailbreak"] + ? item["jailbreak"] + : contentFilterDetectionResultDeserializer(item["jailbreak"]), + customBlocklists: !item["custom_blocklists"] + ? item["custom_blocklists"] + : contentFilterDetailedResultsDeserializer(item["custom_blocklists"]), + }; +} + +export function imageGenerationDataArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return imageGenerationDataDeserializer(item); + }); +} + /** A representation of the request options that control the behavior of a text-to-speech operation. */ export interface SpeechGenerationOptions { /** The text to generate audio for. The maximum length is 4096 characters. */ @@ -2823,7 +3751,7 @@ export interface SpeechGenerationOptions { export function speechGenerationOptionsSerializer( item: SpeechGenerationOptions, -): Record { +): any { return { input: item["input"], voice: item["voice"], @@ -2883,13 +3811,13 @@ export interface EmbeddingsOptions { inputType?: string; } -export function embeddingsOptionsSerializer( - item: EmbeddingsOptions, -): Record { +export function embeddingsOptionsSerializer(item: EmbeddingsOptions): any { return { user: item["user"], model: item["model"], - input: item["input"], + input: item["input"].map((p: any) => { + return p; + }), encoding_format: item["encodingFormat"], dimensions: item["dimensions"], input_type: item["inputType"], @@ -2911,6 +3839,13 @@ export interface Embeddings { usage: EmbeddingsUsage; } +export function embeddingsDeserializer(item: any): Embeddings { + return { + data: embeddingItemArrayDeserializer(item["data"]), + usage: embeddingsUsageDeserializer(item["usage"]), + }; +} + /** Representation of a single embeddings relatedness comparison. */ export interface EmbeddingItem { /** @@ -2922,6 +3857,23 @@ export interface EmbeddingItem { index: number; } +export function embeddingItemDeserializer(item: any): EmbeddingItem { + return { + embedding: item["embedding"].map((p: any) => { + return p; + }), + index: item["index"], + }; +} + +export function embeddingItemArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return embeddingItemDeserializer(item); + }); +} + /** Measurement of the amount of tokens used in this request and response. */ export interface EmbeddingsUsage { /** Number of tokens sent in the original request. */ @@ -2930,79 +3882,9 @@ export interface EmbeddingsUsage { totalTokens: number; } -/** Type of ServiceApiVersions */ -export type ServiceApiVersions = - | "2022-12-01" - | "2023-05-15" - | "2023-06-01-preview" - | "2023-07-01-preview" - | "2024-02-01" - | "2024-02-15-preview" - | "2024-03-01-preview" - | "2024-04-01-preview" - | "2024-05-01-preview" - | "2024-06-01"; -/** Alias for ChatRequestMessageUnion */ -export type ChatRequestMessageUnion = - | ChatRequestSystemMessage - | ChatRequestUserMessage - | ChatRequestAssistantMessage - | ChatRequestToolMessage - | ChatRequestFunctionMessage - | ChatRequestMessage; -/** Alias for ChatMessageContentItemUnion */ -export type ChatMessageContentItemUnion = - | ChatMessageTextContentItem - | ChatMessageImageContentItem - | ChatMessageContentItem; -/** Alias for ChatCompletionsToolCallUnion */ -export type ChatCompletionsToolCallUnion = - | ChatCompletionsFunctionToolCall - | ChatCompletionsToolCall; -/** Alias for AzureChatExtensionConfigurationUnion */ -export type AzureChatExtensionConfigurationUnion = - | AzureSearchChatExtensionConfiguration - | AzureMachineLearningIndexChatExtensionConfiguration - | AzureCosmosDBChatExtensionConfiguration - | ElasticsearchChatExtensionConfiguration - | PineconeChatExtensionConfiguration - | AzureChatExtensionConfiguration; -/** Alias for OnYourDataAuthenticationOptionsUnion */ -export type OnYourDataAuthenticationOptionsUnion = - | OnYourDataApiKeyAuthenticationOptions - | OnYourDataConnectionStringAuthenticationOptions - | OnYourDataKeyAndKeyIdAuthenticationOptions - | OnYourDataEncodedApiKeyAuthenticationOptions - | OnYourDataAccessTokenAuthenticationOptions - | OnYourDataSystemAssignedManagedIdentityAuthenticationOptions - | OnYourDataUserAssignedManagedIdentityAuthenticationOptions - | OnYourDataAuthenticationOptions; -/** Alias for OnYourDataVectorizationSourceUnion */ -export type OnYourDataVectorizationSourceUnion = - | OnYourDataEndpointVectorizationSource - | OnYourDataDeploymentNameVectorizationSource - | OnYourDataModelIdVectorizationSource - | OnYourDataVectorizationSource; -/** Alias for OnYourDataVectorSearchAuthenticationOptionsUnion */ -export type OnYourDataVectorSearchAuthenticationOptionsUnion = - | OnYourDataVectorSearchApiKeyAuthenticationOptions - | OnYourDataVectorSearchAccessTokenAuthenticationOptions - | OnYourDataVectorSearchAuthenticationOptions; -/** Alias for ChatCompletionsResponseFormatUnion */ -export type ChatCompletionsResponseFormatUnion = - | ChatCompletionsTextResponseFormat - | ChatCompletionsJsonResponseFormat - | ChatCompletionsResponseFormat; -/** Alias for ChatCompletionsToolDefinitionUnion */ -export type ChatCompletionsToolDefinitionUnion = - | ChatCompletionsFunctionToolDefinition - | ChatCompletionsToolDefinition; -/** Alias for ChatCompletionsNamedToolSelectionUnion */ -export type ChatCompletionsNamedToolSelectionUnion = - | ChatCompletionsNamedFunctionToolSelection - | ChatCompletionsNamedToolSelection; -/** Alias for ChatFinishDetailsUnion */ -export type ChatFinishDetailsUnion = - | StopFinishDetails - | MaxTokensFinishDetails - | ChatFinishDetails; +export function embeddingsUsageDeserializer(item: any): EmbeddingsUsage { + return { + promptTokens: item["prompt_tokens"], + totalTokens: item["total_tokens"], + }; +} diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/openAIClient.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/openAIClient.ts index 68cb668883..822d86f5a4 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/openAIClient.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/openAIClient.ts @@ -1,8 +1,29 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential, KeyCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; +import { + createOpenAI, + OpenAIContext, + OpenAIClientOptionalParams, + getAudioTranscriptionAsPlainText, + getAudioTranscriptionAsResponseObject, + getAudioTranslationAsPlainText, + getAudioTranslationAsResponseObject, + getCompletions, + getChatCompletions, + getImageGenerations, + generateSpeechFromText, + getEmbeddings, + GetAudioTranscriptionAsPlainTextOptionalParams, + GetAudioTranscriptionAsResponseObjectOptionalParams, + GetAudioTranslationAsPlainTextOptionalParams, + GetAudioTranslationAsResponseObjectOptionalParams, + GetCompletionsOptionalParams, + GetChatCompletionsOptionalParams, + GetImageGenerationsOptionalParams, + GenerateSpeechFromTextOptionalParams, + GetEmbeddingsOptionalParams, +} from "./api/index.js"; import { AudioTranscriptionOptions, AudioTranscription, @@ -18,31 +39,8 @@ import { EmbeddingsOptions, Embeddings, } from "./models/models.js"; -import { - GetAudioTranscriptionAsPlainTextOptionalParams, - GetAudioTranscriptionAsResponseObjectOptionalParams, - GetAudioTranslationAsPlainTextOptionalParams, - GetAudioTranslationAsResponseObjectOptionalParams, - GetCompletionsOptionalParams, - GetChatCompletionsOptionalParams, - GetImageGenerationsOptionalParams, - GenerateSpeechFromTextOptionalParams, - GetEmbeddingsOptionalParams, -} from "./models/options.js"; -import { - createOpenAI, - OpenAIContext, - OpenAIClientOptionalParams, - getAudioTranscriptionAsPlainText, - getAudioTranscriptionAsResponseObject, - getAudioTranslationAsPlainText, - getAudioTranslationAsResponseObject, - getCompletions, - getChatCompletions, - getImageGenerations, - generateSpeechFromText, - getEmbeddings, -} from "./api/index.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { KeyCredential, TokenCredential } from "@azure/core-auth"; export { OpenAIClientOptionalParams } from "./api/openAIContext.js"; diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md index ac60141552..bfefaec9e2 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md @@ -41,26 +41,26 @@ export interface AudioTranslationsOperations { create: (audio: CreateTranslationRequest, options?: AudioTranslationsCreateOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface ChatCompletionFunctionCallOption { name: string; } -// @public (undocumented) +// @public export interface ChatCompletionFunctionParameters extends Record { } -// @public (undocumented) +// @public export interface ChatCompletionFunctions { description?: string; name: string; parameters: ChatCompletionFunctionParameters; } -// @public (undocumented) +// @public export interface ChatCompletionRequestMessage { content: string | null; - functionCall?: { + function_call?: { name: string; arguments: string; }; @@ -68,10 +68,10 @@ export interface ChatCompletionRequestMessage { role: "system" | "user" | "assistant" | "function"; } -// @public (undocumented) +// @public export interface ChatCompletionResponseMessage { content: string | null; - functionCall?: { + function_call?: { name: string; arguments: string; }; @@ -106,26 +106,26 @@ export interface CompletionsOperations { // @public export interface CompletionUsage { - completionTokens: number; - promptTokens: number; - totalTokens: number; + completion_tokens: number; + prompt_tokens: number; + total_tokens: number; } -// @public (undocumented) +// @public export interface CreateChatCompletionRequest { - frequencyPenalty?: number | null; - functionCall?: "none" | "auto" | ChatCompletionFunctionCallOption; + frequency_penalty?: number | null; + function_call?: "none" | "auto" | ChatCompletionFunctionCallOption; functions?: ChatCompletionFunctions[]; - logitBias?: Record | null; - maxTokens?: number | null; + logit_bias?: Record | null; + max_tokens?: number | null; messages: ChatCompletionRequestMessage[]; - model: string | "gpt4" | "gpt-4-0314" | "gpt-4-0613" | "gpt-4-32k" | "gpt-4-32k-0314" | "gpt-4-32k-0613" | "gpt-3.5-turbo" | "gpt-3.5-turbo-16k" | "gpt-3.5-turbo-0301" | "gpt-3.5-turbo-0613" | "gpt-3.5-turbo-16k-0613"; + model: "gpt4" | "gpt-4-0314" | "gpt-4-0613" | "gpt-4-32k" | "gpt-4-32k-0314" | "gpt-4-32k-0613" | "gpt-3.5-turbo" | "gpt-3.5-turbo-16k" | "gpt-3.5-turbo-0301" | "gpt-3.5-turbo-0613" | "gpt-3.5-turbo-16k-0613"; n?: number | null; - presencePenalty?: number | null; - stop?: Stop; + presence_penalty?: number | null; + stop?: Stop_1 | null; stream?: boolean | null; temperature?: number | null; - topP?: number | null; + top_p?: number | null; user?: string; } @@ -134,7 +134,7 @@ export interface CreateChatCompletionResponse { choices: { index: number; message: ChatCompletionResponseMessage; - finishReason: "stop" | "length" | "function_call" | "content_filter"; + finish_reason: "stop" | "length" | "function_call" | "content_filter"; }[]; created: Date; id: string; @@ -144,23 +144,23 @@ export interface CreateChatCompletionResponse { usage?: CompletionUsage; } -// @public (undocumented) +// @public export interface CreateCompletionRequest { - bestOf?: number | null; + best_of?: number | null; echo?: boolean | null; - frequencyPenalty?: number | null; - logitBias?: Record | null; + frequency_penalty?: number | null; + logit_bias?: Record | null; logprobs?: number | null; - maxTokens?: number | null; - model: string | "babbage-002" | "davinci-002" | "text-davinci-003" | "text-davinci-002" | "text-davinci-001" | "code-davinci-002" | "text-curie-001" | "text-babbage-001" | "text-ada-001"; + max_tokens?: number | null; + model: "babbage-002" | "davinci-002" | "text-davinci-003" | "text-davinci-002" | "text-davinci-001" | "code-davinci-002" | "text-curie-001" | "text-babbage-001" | "text-ada-001"; n?: number | null; - presencePenalty?: number | null; - prompt: Prompt; - stop?: Stop; + presence_penalty?: number | null; + prompt: Prompt | null; + stop?: Stop | null; stream?: boolean | null; suffix?: string | null; temperature?: number | null; - topP?: number | null; + top_p?: number | null; user?: string; } @@ -171,11 +171,11 @@ export interface CreateCompletionResponse { text: string; logprobs: { tokens: string[]; - tokenLogprobs: number[]; - topLogprobs: Record[]; - textOffset: number[]; + token_logprobs: number[]; + top_logprobs: Record[]; + text_offset: number[]; } | null; - finishReason: "stop" | "length" | "content_filter"; + finish_reason: "stop" | "length" | "content_filter"; }[]; created: Date; id: string; @@ -185,22 +185,22 @@ export interface CreateCompletionResponse { usage?: CompletionUsage; } -// @public (undocumented) +// @public export interface CreateEditRequest { input?: string | null; instruction: string; - model: string | "text-davinci-edit-001" | "code-davinci-edit-001"; + model: "text-davinci-edit-001" | "code-davinci-edit-001"; n?: number | null; temperature?: number | null; - topP?: number | null; + top_p?: number | null; } -// @public (undocumented) +// @public export interface CreateEditResponse { choices: { text: string; index: number; - finishReason: "stop" | "length"; + finish_reason: "stop" | "length"; }[]; created: Date; object: "edit"; @@ -208,97 +208,97 @@ export interface CreateEditResponse { usage: CompletionUsage; } -// @public (undocumented) +// @public export interface CreateEmbeddingRequest { input: string | string[] | number[] | number[][]; - model: string | "text-embedding-ada-002"; + model: "text-embedding-ada-002"; // (undocumented) user?: string; } -// @public (undocumented) +// @public export interface CreateEmbeddingResponse { data: Embedding[]; model: string; object: "embedding"; usage: { - promptTokens: number; - totalTokens: number; + prompt_tokens: number; + total_tokens: number; }; } -// @public (undocumented) +// @public export interface CreateFileRequest { file: Uint8Array; purpose: string; } -// @public (undocumented) +// @public export interface CreateFineTuneRequest { - batchSize?: number | null; - classificationBetas?: number[] | null; - classificationNClasses?: number | null; - classificationPositiveClass?: string | null; - computeClassificationMetrics?: boolean | null; - learningRateMultiplier?: number | null; - model?: string | "ada" | "babbage" | "curie" | "davinci"; - nEpochs?: number | null; - promptLossRate?: number | null; + batch_size?: number | null; + classification_betas?: number[] | null; + classification_n_classes?: number | null; + classification_positive_class?: string | null; + compute_classification_metrics?: boolean | null; + learning_rate_multiplier?: number | null; + model?: ("ada" | "babbage" | "curie" | "davinci") | null; + n_epochs?: number | null; + prompt_loss_rate?: number | null; suffix?: string | null; - trainingFile: string; - validationFile?: string | null; + training_file: string; + validation_file?: string | null; } -// @public (undocumented) +// @public export interface CreateFineTuningJobRequest { hyperparameters?: { - nEpochs?: "auto" | number; + n_epochs?: "auto" | number; }; - model: string | "babbage-002" | "davinci-002" | "gpt-3.5-turbo"; + model: "babbage-002" | "davinci-002" | "gpt-3.5-turbo"; suffix?: string | null; - trainingFile: string; - validationFile?: string | null; + training_file: string; + validation_file?: string | null; } -// @public (undocumented) +// @public export interface CreateImageEditRequest { image: Uint8Array; mask?: Uint8Array; n?: number | null; prompt: string; - responseFormat?: "url" | "b64_json"; - size?: "256x256" | "512x512" | "1024x1024"; + response_format?: ("url" | "b64_json") | null; + size?: ("256x256" | "512x512" | "1024x1024") | null; // (undocumented) user?: string; } -// @public (undocumented) +// @public export interface CreateImageRequest { n?: number | null; prompt: string; - responseFormat?: "url" | "b64_json"; - size?: "256x256" | "512x512" | "1024x1024"; + response_format?: ("url" | "b64_json") | null; + size?: ("256x256" | "512x512" | "1024x1024") | null; // (undocumented) user?: string; } -// @public (undocumented) +// @public export interface CreateImageVariationRequest { image: Uint8Array; n?: number | null; - responseFormat?: "url" | "b64_json"; - size?: "256x256" | "512x512" | "1024x1024"; + response_format?: ("url" | "b64_json") | null; + size?: ("256x256" | "512x512" | "1024x1024") | null; // (undocumented) user?: string; } -// @public (undocumented) +// @public export interface CreateModerationRequest { input: string | string[]; - model?: string | "text-moderation-latest" | "text-moderation-stable"; + model?: "text-moderation-latest" | "text-moderation-stable"; } -// @public (undocumented) +// @public export interface CreateModerationResponse { id: string; model: string; @@ -309,22 +309,22 @@ export interface CreateModerationResponse { "hate/threatening": boolean; harassment: boolean; "harassment/threatening": boolean; - selfHarm: boolean; - "selfHarm/intent": boolean; - "selfHarm/instructive": boolean; + "self-harm": boolean; + "self-harm/intent": boolean; + "self-harm/instructive": boolean; sexual: boolean; "sexual/minors": boolean; violence: boolean; "violence/graphic": boolean; }; - categoryScores: { + category_scores: { hate: number; "hate/threatening": number; harassment: number; "harassment/threatening": number; - selfHarm: number; - "selfHarm/intent": number; - "selfHarm/instructive": number; + "self-harm": number; + "self-harm/intent": number; + "self-harm/instructive": number; sexual: number; "sexual/minors": number; violence: number; @@ -333,38 +333,38 @@ export interface CreateModerationResponse { }[]; } -// @public (undocumented) +// @public export interface CreateTranscriptionRequest { file: Uint8Array; language?: string; - model: string | "whisper-1"; + model: "whisper-1"; prompt?: string; - responseFormat?: "json" | "text" | "srt" | "verbose_json" | "vtt"; + response_format?: "json" | "text" | "srt" | "verbose_json" | "vtt"; temperature?: number; } -// @public (undocumented) +// @public export interface CreateTranscriptionResponse { // (undocumented) text: string; } -// @public (undocumented) +// @public export interface CreateTranslationRequest { file: Uint8Array; - model: string | "whisper-1"; + model: "whisper-1"; prompt?: string; - responseFormat?: "json" | "text" | "srt" | "verbose_json" | "vtt"; + response_format?: "json" | "text" | "srt" | "verbose_json" | "vtt"; temperature?: number; } -// @public (undocumented) +// @public export interface CreateTranslationResponse { // (undocumented) text: string; } -// @public (undocumented) +// @public export interface DeleteFileResponse { // (undocumented) deleted: boolean; @@ -374,7 +374,7 @@ export interface DeleteFileResponse { object: string; } -// @public (undocumented) +// @public export interface DeleteModelResponse { // (undocumented) deleted: boolean; @@ -411,7 +411,7 @@ export interface EmbeddingsOperations { create: (embedding: CreateEmbeddingRequest, options?: EmbeddingsCreateOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface ErrorModel { // (undocumented) code: string | null; @@ -423,7 +423,7 @@ export interface ErrorModel { type: string; } -// @public (undocumented) +// @public export interface ErrorResponse { // (undocumented) error: ErrorModel; @@ -466,33 +466,33 @@ export interface FilesRetrieveOptionalParams extends OperationOptions { // @public export interface FineTune { - createdAt: Date; + created_at: Date; events?: FineTuneEvent[]; - fineTunedModel: string | null; + fine_tuned_model: string | null; hyperparams: { - nEpochs: number; - batchSize: number; - promptLossWeight: number; - learningRateMultiplier: number; - computeClassificationMetrics?: boolean; - classificationPositiveClass?: string; - classificationNClasses?: number; + n_epochs: number; + batch_size: number; + prompt_loss_weight: number; + learning_rate_multiplier: number; + compute_classification_metrics?: boolean; + classification_positive_class?: string; + classification_n_classes?: number; }; id: string; model: string; object: "fine-tune"; - organizationId: string; - resultFiles: OpenAIFile[]; + organization_id: string; + result_files: OpenAIFile[]; status: "created" | "running" | "succeeded" | "failed" | "cancelled"; - trainingFiles: OpenAIFile[]; - updatedAt: Date; - validationFiles: OpenAIFile[]; + training_files: OpenAIFile[]; + updated_at: Date; + validation_files: OpenAIFile[]; } -// @public (undocumented) +// @public export interface FineTuneEvent { // (undocumented) - createdAt: Date; + created_at: Date; // (undocumented) level: string; // (undocumented) @@ -536,34 +536,34 @@ export interface FineTunesOperations { export interface FineTunesRetrieveOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTuningJob { - createdAt: Date; + created_at: Date; error: { message?: string; code?: string; param?: string | null; } | null; - fineTunedModel: string | null; - finishedAt: Date | null; + fine_tuned_model: string | null; + finished_at: Date | null; hyperparameters: { - nEpochs?: "auto" | number; + n_epochs?: "auto" | number; }; id: string; model: string; object: "fine_tuning.job"; - organizationId: string; - resultFiles: string[]; + organization_id: string; + result_files: string[]; status: "created" | "pending" | "running" | "succeeded" | "failed" | "cancelled"; - trainedTokens: number | null; - trainingFile: string; - validationFile: string | null; + trained_tokens: number | null; + training_file: string; + validation_file: string | null; } -// @public (undocumented) +// @public export interface FineTuningJobEvent { // (undocumented) - createdAt: Date; + created_at: Date; // (undocumented) id: string; // (undocumented) @@ -619,7 +619,7 @@ export interface FineTuningOperations { // @public export interface Image { - b64Json?: Uint8Array; + b64_json?: Uint8Array; url?: string; } @@ -649,7 +649,7 @@ export interface ImagesOperations { createVariation: (image: CreateImageVariationRequest, options?: ImagesCreateVariationOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface ImagesResponse { // (undocumented) created: Date; @@ -657,7 +657,7 @@ export interface ImagesResponse { data: Image[]; } -// @public (undocumented) +// @public export interface ListFilesResponse { // (undocumented) data: OpenAIFile[]; @@ -665,7 +665,7 @@ export interface ListFilesResponse { object: string; } -// @public (undocumented) +// @public export interface ListFineTuneEventsResponse { // (undocumented) data: FineTuneEvent[]; @@ -673,7 +673,7 @@ export interface ListFineTuneEventsResponse { object: string; } -// @public (undocumented) +// @public export interface ListFineTunesResponse { // (undocumented) data: FineTune[]; @@ -681,7 +681,7 @@ export interface ListFineTunesResponse { object: string; } -// @public (undocumented) +// @public export interface ListFineTuningJobEventsResponse { // (undocumented) data: FineTuningJobEvent[]; @@ -689,7 +689,7 @@ export interface ListFineTuningJobEventsResponse { object: string; } -// @public (undocumented) +// @public export interface ListModelsResponse { // (undocumented) data: Model[]; @@ -697,12 +697,12 @@ export interface ListModelsResponse { object: string; } -// @public (undocumented) +// @public export interface ListPaginatedFineTuningJobsResponse { // (undocumented) data: FineTuningJob[]; // (undocumented) - hasMore: boolean; + has_more: boolean; // (undocumented) object: string; } @@ -712,7 +712,7 @@ export interface Model { created: Date; id: string; object: "model"; - ownedBy: string; + owned_by: string; } // @public @@ -776,7 +776,7 @@ export interface OpenAIFile { object: "file"; purpose: string; status: "uploaded" | "processed" | "pending" | "error" | "deleting" | "deleted"; - statusDetails?: string | null; + status_details?: string | null; } // @public @@ -785,6 +785,9 @@ export type Prompt = string | string[] | number[] | number[][]; // @public export type Stop = string | string[]; +// @public +export type Stop_1 = string | string[]; + // (No @packageDocumentation comment for this package) ``` diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/transcriptions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/transcriptions/index.ts index 0caaac5618..838d4b582a 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/transcriptions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/transcriptions/index.ts @@ -1,18 +1,21 @@ // Licensed under the MIT License. +import { + AudioTranscriptionsCreateOptionalParams, + OpenAIContext as Client, +} from "../../index.js"; import { CreateTranscriptionRequest, + createTranscriptionRequestSerializer, CreateTranscriptionResponse, + createTranscriptionResponseDeserializer, } from "../../../models/models.js"; -import { OpenAIContext as Client } from "../../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { uint8ArrayToString } from "@typespec/ts-http-runtime"; -import { AudioTranscriptionsCreateOptionalParams } from "../../../models/options.js"; export function _createSend( context: Client, @@ -24,14 +27,7 @@ export function _createSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(audio["file"], "base64"), - model: audio["model"], - prompt: audio["prompt"], - response_format: audio["responseFormat"], - temperature: audio["temperature"], - language: audio["language"], - }, + body: createTranscriptionRequestSerializer(audio), }); } @@ -43,9 +39,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - text: result.body["text"], - }; + return createTranscriptionResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/translations/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/translations/index.ts index 55d779e893..3ea71814e4 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/translations/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/translations/index.ts @@ -1,18 +1,21 @@ // Licensed under the MIT License. +import { + AudioTranslationsCreateOptionalParams, + OpenAIContext as Client, +} from "../../index.js"; import { CreateTranslationRequest, + createTranslationRequestSerializer, CreateTranslationResponse, + createTranslationResponseDeserializer, } from "../../../models/models.js"; -import { OpenAIContext as Client } from "../../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { uint8ArrayToString } from "@typespec/ts-http-runtime"; -import { AudioTranslationsCreateOptionalParams } from "../../../models/options.js"; export function _createSend( context: Client, @@ -24,13 +27,7 @@ export function _createSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(audio["file"], "base64"), - model: audio["model"], - prompt: audio["prompt"], - response_format: audio["responseFormat"], - temperature: audio["temperature"], - }, + body: createTranslationRequestSerializer(audio), }); } @@ -42,9 +39,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - text: result.body["text"], - }; + return createTranslationResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts index a9d73f7d13..9c44d2c245 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts @@ -1,20 +1,21 @@ // Licensed under the MIT License. import { - chatCompletionRequestMessageSerializer, - chatCompletionFunctionsSerializer, + ChatCompletionsCreateOptionalParams, + OpenAIContext as Client, +} from "../../index.js"; +import { CreateChatCompletionRequest, + createChatCompletionRequestSerializer, CreateChatCompletionResponse, + createChatCompletionResponseDeserializer, } from "../../../models/models.js"; -import { OpenAIContext as Client } from "../../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { serializeRecord } from "../../../helpers/serializerHelpers.js"; -import { ChatCompletionsCreateOptionalParams } from "../../../models/options.js"; export function _createSend( context: Client, @@ -25,27 +26,7 @@ export function _createSend( .path("/chat/completions") .post({ ...operationOptionsToRequestParameters(options), - body: { - model: body["model"], - messages: body["messages"].map(chatCompletionRequestMessageSerializer), - functions: - body["functions"] === undefined - ? body["functions"] - : body["functions"].map(chatCompletionFunctionsSerializer), - function_call: body["functionCall"], - temperature: body["temperature"], - top_p: body["topP"], - n: body["n"], - max_tokens: body["maxTokens"], - stop: body["stop"], - presence_penalty: body["presencePenalty"], - frequency_penalty: body["frequencyPenalty"], - logit_bias: !body.logitBias - ? body.logitBias - : (serializeRecord(body.logitBias as any) as any), - user: body["user"], - stream: body["stream"], - }, + body: createChatCompletionRequestSerializer(body), }); } @@ -57,35 +38,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - created: new Date(result.body["created"]), - model: result.body["model"], - choices: result.body["choices"].map((p: any) => { - return { - index: p["index"], - message: { - role: p.message["role"], - content: p.message["content"], - functionCall: !p.message.function_call - ? undefined - : { - name: p.message.function_call?.["name"], - arguments: p.message.function_call?.["arguments"], - }, - }, - finishReason: p["finish_reason"], - }; - }), - usage: !result.body.usage - ? undefined - : { - promptTokens: result.body.usage?.["prompt_tokens"], - completionTokens: result.body.usage?.["completion_tokens"], - totalTokens: result.body.usage?.["total_tokens"], - }, - }; + return createChatCompletionResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts index e92f3bee28..ae8fa55f21 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts @@ -1,18 +1,21 @@ // Licensed under the MIT License. +import { + OpenAIContext as Client, + CompletionsCreateOptionalParams, +} from "../index.js"; import { CreateCompletionRequest, + createCompletionRequestSerializer, CreateCompletionResponse, + createCompletionResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { serializeRecord } from "../../helpers/serializerHelpers.js"; -import { CompletionsCreateOptionalParams } from "../../models/options.js"; export function _createSend( context: Client, @@ -23,26 +26,7 @@ export function _createSend( .path("/completions") .post({ ...operationOptionsToRequestParameters(options), - body: { - model: body["model"], - prompt: body["prompt"], - suffix: body["suffix"], - temperature: body["temperature"], - top_p: body["topP"], - n: body["n"], - max_tokens: body["maxTokens"], - stop: body["stop"], - presence_penalty: body["presencePenalty"], - frequency_penalty: body["frequencyPenalty"], - logit_bias: !body.logitBias - ? body.logitBias - : (serializeRecord(body.logitBias as any) as any), - user: body["user"], - stream: body["stream"], - logprobs: body["logprobs"], - echo: body["echo"], - best_of: body["bestOf"], - }, + body: createCompletionRequestSerializer(body), }); } @@ -54,35 +38,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - created: new Date(result.body["created"]), - model: result.body["model"], - choices: result.body["choices"].map((p: any) => { - return { - index: p["index"], - text: p["text"], - logprobs: - p.logprobs === null - ? null - : { - tokens: p.logprobs["tokens"], - tokenLogprobs: p.logprobs["token_logprobs"], - topLogprobs: p.logprobs["top_logprobs"], - textOffset: p.logprobs["text_offset"], - }, - finishReason: p["finish_reason"], - }; - }), - usage: !result.body.usage - ? undefined - : { - promptTokens: result.body.usage?.["prompt_tokens"], - completionTokens: result.body.usage?.["completion_tokens"], - totalTokens: result.body.usage?.["total_tokens"], - }, - }; + return createCompletionResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/edits/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/edits/index.ts index d10824b850..732bc9d9a8 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/edits/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/edits/index.ts @@ -1,14 +1,21 @@ // Licensed under the MIT License. -import { CreateEditRequest, CreateEditResponse } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; +import { + OpenAIContext as Client, + EditsCreateOptionalParams, +} from "../index.js"; +import { + CreateEditRequest, + createEditRequestSerializer, + CreateEditResponse, + createEditResponseDeserializer, +} from "../../models/models.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { EditsCreateOptionalParams } from "../../models/options.js"; export function _createSend( context: Client, @@ -19,14 +26,7 @@ export function _createSend( .path("/edits") .post({ ...operationOptionsToRequestParameters(options), - body: { - model: edit["model"], - input: edit["input"], - instruction: edit["instruction"], - n: edit["n"], - temperature: edit["temperature"], - top_p: edit["topP"], - }, + body: createEditRequestSerializer(edit), }); } @@ -38,22 +38,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - created: new Date(result.body["created"]), - choices: result.body["choices"].map((p: any) => { - return { - text: p["text"], - index: p["index"], - finishReason: p["finish_reason"], - }; - }), - usage: { - promptTokens: result.body.usage["prompt_tokens"], - completionTokens: result.body.usage["completion_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; + return createEditResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/embeddings/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/embeddings/index.ts index 7080bdddb9..091d9c344d 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/embeddings/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/embeddings/index.ts @@ -1,17 +1,21 @@ // Licensed under the MIT License. +import { + OpenAIContext as Client, + EmbeddingsCreateOptionalParams, +} from "../index.js"; import { CreateEmbeddingRequest, + createEmbeddingRequestSerializer, CreateEmbeddingResponse, + createEmbeddingResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { EmbeddingsCreateOptionalParams } from "../../models/options.js"; export function _createSend( context: Client, @@ -22,11 +26,7 @@ export function _createSend( .path("/embeddings") .post({ ...operationOptionsToRequestParameters(options), - body: { - model: embedding["model"], - input: embedding["input"], - user: embedding["user"], - }, + body: createEmbeddingRequestSerializer(embedding), }); } @@ -38,21 +38,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - model: result.body["model"], - data: result.body["data"].map((p: any) => { - return { - index: p["index"], - object: p["object"], - embedding: p["embedding"], - }; - }), - usage: { - promptTokens: result.body.usage["prompt_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; + return createEmbeddingResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/files/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/files/index.ts index 2e2b8376a7..8b00a519c6 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/files/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/files/index.ts @@ -1,26 +1,29 @@ // Licensed under the MIT License. +import { + OpenAIContext as Client, + FilesCreateOptionalParams, + FilesDeleteOptionalParams, + FilesDownloadOptionalParams, + FilesListOptionalParams, + FilesRetrieveOptionalParams, +} from "../index.js"; import { OpenAIFile, + openAIFileDeserializer, ListFilesResponse, + listFilesResponseDeserializer, CreateFileRequest, + createFileRequestSerializer, DeleteFileResponse, + deleteFileResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { uint8ArrayToString } from "@typespec/ts-http-runtime"; -import { - FilesListOptionalParams, - FilesCreateOptionalParams, - FilesRetrieveOptionalParams, - FilesDeleteOptionalParams, - FilesDownloadOptionalParams, -} from "../../models/options.js"; export function _listSend( context: Client, @@ -39,21 +42,7 @@ export async function _listDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - }; + return listFilesResponseDeserializer(result.body); } export async function list( @@ -74,10 +63,7 @@ export function _createSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(file["file"], "base64"), - purpose: file["purpose"], - }, + body: createFileRequestSerializer(file), }); } @@ -89,16 +75,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - bytes: result.body["bytes"], - createdAt: new Date(result.body["createdAt"]), - filename: result.body["filename"], - purpose: result.body["purpose"], - status: result.body["status"], - statusDetails: result.body["status_details"], - }; + return openAIFileDeserializer(result.body); } export async function create( @@ -128,16 +105,7 @@ export async function _retrieveDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - bytes: result.body["bytes"], - createdAt: new Date(result.body["createdAt"]), - filename: result.body["filename"], - purpose: result.body["purpose"], - status: result.body["status"], - statusDetails: result.body["status_details"], - }; + return openAIFileDeserializer(result.body); } export async function retrieve( @@ -167,11 +135,7 @@ export async function _$deleteDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - deleted: result.body["deleted"], - }; + return deleteFileResponseDeserializer(result.body); } /** diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTunes/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTunes/index.ts index 1f02989fbe..75574deb85 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTunes/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTunes/index.ts @@ -1,25 +1,29 @@ // Licensed under the MIT License. +import { + OpenAIContext as Client, + FineTunesCancelOptionalParams, + FineTunesCreateOptionalParams, + FineTunesListEventsOptionalParams, + FineTunesListOptionalParams, + FineTunesRetrieveOptionalParams, +} from "../index.js"; import { CreateFineTuneRequest, + createFineTuneRequestSerializer, FineTune, + fineTuneDeserializer, ListFineTunesResponse, + listFineTunesResponseDeserializer, ListFineTuneEventsResponse, + listFineTuneEventsResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { - FineTunesCreateOptionalParams, - FineTunesListOptionalParams, - FineTunesRetrieveOptionalParams, - FineTunesListEventsOptionalParams, - FineTunesCancelOptionalParams, -} from "../../models/options.js"; export function _createSend( context: Client, @@ -30,21 +34,7 @@ export function _createSend( .path("/fine-tunes") .post({ ...operationOptionsToRequestParameters(options), - body: { - training_file: fineTune["trainingFile"], - validation_file: fineTune["validationFile"], - model: fineTune["model"], - n_epochs: fineTune["nEpochs"], - batch_size: fineTune["batchSize"], - learning_rate_multiplier: fineTune["learningRateMultiplier"], - prompt_loss_rate: fineTune["promptLossRate"], - compute_classification_metrics: - fineTune["computeClassificationMetrics"], - classification_n_classes: fineTune["classificationNClasses"], - classification_positive_class: fineTune["classificationPositiveClass"], - classification_betas: fineTune["classificationBetas"], - suffix: fineTune["suffix"], - }, + body: createFineTuneRequestSerializer(fineTune), }); } @@ -56,76 +46,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - updatedAt: new Date(result.body["updated_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparams: { - nEpochs: result.body.hyperparams["n_epochs"], - batchSize: result.body.hyperparams["batch_size"], - promptLossWeight: result.body.hyperparams["prompt_loss_weight"], - learningRateMultiplier: - result.body.hyperparams["learning_rate_multiplier"], - computeClassificationMetrics: - result.body.hyperparams["compute_classification_metrics"], - classificationPositiveClass: - result.body.hyperparams["classification_positive_class"], - classificationNClasses: - result.body.hyperparams["classification_n_classes"], - }, - trainingFiles: result.body["training_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - validationFiles: result.body["validation_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - resultFiles: result.body["result_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - events: - result.body["events"] === undefined - ? result.body["events"] - : result.body["events"].map((p: any) => { - return { - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; + return fineTuneDeserializer(result.body); } export async function create( @@ -154,79 +75,7 @@ export async function _listDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - createdAt: new Date(p["created_at"]), - updatedAt: new Date(p["updated_at"]), - model: p["model"], - fineTunedModel: p["fine_tuned_model"], - organizationId: p["organization_id"], - status: p["status"], - hyperparams: { - nEpochs: p.hyperparams["n_epochs"], - batchSize: p.hyperparams["batch_size"], - promptLossWeight: p.hyperparams["prompt_loss_weight"], - learningRateMultiplier: p.hyperparams["learning_rate_multiplier"], - computeClassificationMetrics: - p.hyperparams["compute_classification_metrics"], - classificationPositiveClass: - p.hyperparams["classification_positive_class"], - classificationNClasses: p.hyperparams["classification_n_classes"], - }, - trainingFiles: p["training_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - validationFiles: p["validation_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - resultFiles: p["result_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - events: - p["events"] === undefined - ? p["events"] - : p["events"].map((p: any) => { - return { - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; - }), - }; + return listFineTunesResponseDeserializer(result.body); } export async function list( @@ -255,76 +104,7 @@ export async function _retrieveDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - updatedAt: new Date(result.body["updated_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparams: { - nEpochs: result.body.hyperparams["n_epochs"], - batchSize: result.body.hyperparams["batch_size"], - promptLossWeight: result.body.hyperparams["prompt_loss_weight"], - learningRateMultiplier: - result.body.hyperparams["learning_rate_multiplier"], - computeClassificationMetrics: - result.body.hyperparams["compute_classification_metrics"], - classificationPositiveClass: - result.body.hyperparams["classification_positive_class"], - classificationNClasses: - result.body.hyperparams["classification_n_classes"], - }, - trainingFiles: result.body["training_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - validationFiles: result.body["validation_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - resultFiles: result.body["result_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - events: - result.body["events"] === undefined - ? result.body["events"] - : result.body["events"].map((p: any) => { - return { - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; + return fineTuneDeserializer(result.body); } export async function retrieve( @@ -357,17 +137,7 @@ export async function _listEventsDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; + return listFineTuneEventsResponseDeserializer(result.body); } export async function listEvents( @@ -397,76 +167,7 @@ export async function _cancelDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - updatedAt: new Date(result.body["updated_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparams: { - nEpochs: result.body.hyperparams["n_epochs"], - batchSize: result.body.hyperparams["batch_size"], - promptLossWeight: result.body.hyperparams["prompt_loss_weight"], - learningRateMultiplier: - result.body.hyperparams["learning_rate_multiplier"], - computeClassificationMetrics: - result.body.hyperparams["compute_classification_metrics"], - classificationPositiveClass: - result.body.hyperparams["classification_positive_class"], - classificationNClasses: - result.body.hyperparams["classification_n_classes"], - }, - trainingFiles: result.body["training_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - validationFiles: result.body["validation_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - resultFiles: result.body["result_files"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - bytes: p["bytes"], - createdAt: new Date(p["createdAt"]), - filename: p["filename"], - purpose: p["purpose"], - status: p["status"], - statusDetails: p["status_details"], - }; - }), - events: - result.body["events"] === undefined - ? result.body["events"] - : result.body["events"].map((p: any) => { - return { - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; + return fineTuneDeserializer(result.body); } export async function cancel( diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTuning/jobs/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTuning/jobs/index.ts index a6944c3de9..868832e3c3 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTuning/jobs/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTuning/jobs/index.ts @@ -1,25 +1,29 @@ // Licensed under the MIT License. +import { + OpenAIContext as Client, + FineTuningJobsCancelOptionalParams, + FineTuningJobsCreateOptionalParams, + FineTuningJobsListEventsOptionalParams, + FineTuningJobsListOptionalParams, + FineTuningJobsRetrieveOptionalParams, +} from "../../index.js"; import { CreateFineTuningJobRequest, + createFineTuningJobRequestSerializer, FineTuningJob, + fineTuningJobDeserializer, ListPaginatedFineTuningJobsResponse, + listPaginatedFineTuningJobsResponseDeserializer, ListFineTuningJobEventsResponse, + listFineTuningJobEventsResponseDeserializer, } from "../../../models/models.js"; -import { OpenAIContext as Client } from "../../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { - FineTuningJobsCreateOptionalParams, - FineTuningJobsListOptionalParams, - FineTuningJobsRetrieveOptionalParams, - FineTuningJobsListEventsOptionalParams, - FineTuningJobsCancelOptionalParams, -} from "../../../models/options.js"; export function _createSend( context: Client, @@ -30,15 +34,7 @@ export function _createSend( .path("/fine_tuning/jobs") .post({ ...operationOptionsToRequestParameters(options), - body: { - training_file: job["trainingFile"], - validation_file: job["validationFile"], - model: job["model"], - hyperparameters: !job.hyperparameters - ? undefined - : { n_epochs: job.hyperparameters?.["nEpochs"] }, - suffix: job["suffix"], - }, + body: createFineTuningJobRequestSerializer(job), }); } @@ -50,32 +46,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - finishedAt: - result.body["finished_at"] === null - ? null - : new Date(result.body["finished_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparameters: { nEpochs: result.body.hyperparameters["n_epochs"] }, - trainingFile: result.body["training_file"], - validationFile: result.body["validation_file"], - resultFiles: result.body["result_files"], - trainedTokens: result.body["trained_tokens"], - error: - result.body.error === null - ? null - : { - message: result.body.error["message"], - code: result.body.error["code"], - param: result.body.error["param"], - }, - }; + return fineTuningJobDeserializer(result.body); } /** @@ -115,36 +86,7 @@ export async function _listDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - createdAt: new Date(p["created_at"]), - finishedAt: - p["finished_at"] === null ? null : new Date(p["finished_at"]), - model: p["model"], - fineTunedModel: p["fine_tuned_model"], - organizationId: p["organization_id"], - status: p["status"], - hyperparameters: { nEpochs: p.hyperparameters["n_epochs"] }, - trainingFile: p["training_file"], - validationFile: p["validation_file"], - resultFiles: p["result_files"], - trainedTokens: p["trained_tokens"], - error: - p.error === null - ? null - : { - message: p.error["message"], - code: p.error["code"], - param: p.error["param"], - }, - }; - }), - hasMore: result.body["has_more"], - }; + return listPaginatedFineTuningJobsResponseDeserializer(result.body); } export async function list( @@ -173,32 +115,7 @@ export async function _retrieveDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - finishedAt: - result.body["finished_at"] === null - ? null - : new Date(result.body["finished_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparameters: { nEpochs: result.body.hyperparameters["n_epochs"] }, - trainingFile: result.body["training_file"], - validationFile: result.body["validation_file"], - resultFiles: result.body["result_files"], - trainedTokens: result.body["trained_tokens"], - error: - result.body.error === null - ? null - : { - message: result.body.error["message"], - code: result.body.error["code"], - param: result.body.error["param"], - }, - }; + return fineTuningJobDeserializer(result.body); } export async function retrieve( @@ -231,18 +148,7 @@ export async function _listEventsDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - createdAt: new Date(p["created_at"]), - level: p["level"], - message: p["message"], - }; - }), - }; + return listFineTuningJobEventsResponseDeserializer(result.body); } export async function listEvents( @@ -272,32 +178,7 @@ export async function _cancelDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - createdAt: new Date(result.body["created_at"]), - finishedAt: - result.body["finished_at"] === null - ? null - : new Date(result.body["finished_at"]), - model: result.body["model"], - fineTunedModel: result.body["fine_tuned_model"], - organizationId: result.body["organization_id"], - status: result.body["status"], - hyperparameters: { nEpochs: result.body.hyperparameters["n_epochs"] }, - trainingFile: result.body["training_file"], - validationFile: result.body["validation_file"], - resultFiles: result.body["result_files"], - trainedTokens: result.body["trained_tokens"], - error: - result.body.error === null - ? null - : { - message: result.body.error["message"], - code: result.body.error["code"], - param: result.body.error["param"], - }, - }; + return fineTuningJobDeserializer(result.body); } export async function cancel( diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/images/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/images/index.ts index d3dfbe5cc9..66640eae39 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/images/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/images/index.ts @@ -1,27 +1,27 @@ // Licensed under the MIT License. +import { + OpenAIContext as Client, + ImagesCreateEditOptionalParams, + ImagesCreateOptionalParams, + ImagesCreateVariationOptionalParams, +} from "../index.js"; import { CreateImageRequest, + createImageRequestSerializer, ImagesResponse, + imagesResponseDeserializer, CreateImageEditRequest, + createImageEditRequestSerializer, CreateImageVariationRequest, + createImageVariationRequestSerializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { - uint8ArrayToString, - stringToUint8Array, -} from "@typespec/ts-http-runtime"; -import { - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, - ImagesCreateVariationOptionalParams, -} from "../../models/options.js"; export function _createSend( context: Client, @@ -32,13 +32,7 @@ export function _createSend( .path("/images/generations") .post({ ...operationOptionsToRequestParameters(options), - body: { - prompt: image["prompt"], - n: image["n"], - size: image["size"], - response_format: image["responseFormat"], - user: image["user"], - }, + body: createImageRequestSerializer(image), }); } @@ -50,18 +44,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - created: new Date(result.body["created"]), - data: result.body["data"].map((p: any) => { - return { - url: p["url"], - b64Json: - typeof p["b64_json"] === "string" - ? stringToUint8Array(p["b64_json"], "base64") - : p["b64_json"], - }; - }), - }; + return imagesResponseDeserializer(result.body); } export async function create( @@ -83,18 +66,7 @@ export function _createEditSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - prompt: image["prompt"], - image: uint8ArrayToString(image["image"], "base64"), - mask: - image["mask"] !== undefined - ? uint8ArrayToString(image["mask"], "base64") - : undefined, - n: image["n"], - size: image["size"], - response_format: image["responseFormat"], - user: image["user"], - }, + body: createImageEditRequestSerializer(image), }); } @@ -106,18 +78,7 @@ export async function _createEditDeserialize( throw createRestError(result); } - return { - created: new Date(result.body["created"]), - data: result.body["data"].map((p: any) => { - return { - url: p["url"], - b64Json: - typeof p["b64_json"] === "string" - ? stringToUint8Array(p["b64_json"], "base64") - : p["b64_json"], - }; - }), - }; + return imagesResponseDeserializer(result.body); } export async function createEdit( @@ -139,13 +100,7 @@ export function _createVariationSend( .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - image: uint8ArrayToString(image["image"], "base64"), - n: image["n"], - size: image["size"], - response_format: image["responseFormat"], - user: image["user"], - }, + body: createImageVariationRequestSerializer(image), }); } @@ -157,18 +112,7 @@ export async function _createVariationDeserialize( throw createRestError(result); } - return { - created: new Date(result.body["created"]), - data: result.body["data"].map((p: any) => { - return { - url: p["url"], - b64Json: - typeof p["b64_json"] === "string" - ? stringToUint8Array(p["b64_json"], "base64") - : p["b64_json"], - }; - }), - }; + return imagesResponseDeserializer(result.body); } export async function createVariation( diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/index.ts index 1e0a29f5e4..0676bdf731 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/index.ts @@ -5,3 +5,33 @@ export { OpenAIContext, OpenAIClientOptionalParams, } from "./openAIContext.js"; +export { + AudioTranscriptionsCreateOptionalParams, + AudioTranslationsCreateOptionalParams, + ChatCompletionsCreateOptionalParams, + FineTuningJobsCreateOptionalParams, + FineTuningJobsListOptionalParams, + FineTuningJobsRetrieveOptionalParams, + FineTuningJobsListEventsOptionalParams, + FineTuningJobsCancelOptionalParams, + CompletionsCreateOptionalParams, + EditsCreateOptionalParams, + EmbeddingsCreateOptionalParams, + FilesListOptionalParams, + FilesCreateOptionalParams, + FilesRetrieveOptionalParams, + FilesDeleteOptionalParams, + FilesDownloadOptionalParams, + FineTunesCreateOptionalParams, + FineTunesListOptionalParams, + FineTunesRetrieveOptionalParams, + FineTunesListEventsOptionalParams, + FineTunesCancelOptionalParams, + ModelsListOptionalParams, + ModelsRetrieveOptionalParams, + ModelsDeleteOptionalParams, + ImagesCreateOptionalParams, + ImagesCreateEditOptionalParams, + ImagesCreateVariationOptionalParams, + ModerationsCreateOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/models/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/models/index.ts index 787d697860..ac1bd7ae38 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/models/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/models/index.ts @@ -1,22 +1,25 @@ // Licensed under the MIT License. +import { + OpenAIContext as Client, + ModelsDeleteOptionalParams, + ModelsListOptionalParams, + ModelsRetrieveOptionalParams, +} from "../index.js"; import { ListModelsResponse, + listModelsResponseDeserializer, Model, + modelDeserializer, DeleteModelResponse, + deleteModelResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { - ModelsListOptionalParams, - ModelsRetrieveOptionalParams, - ModelsDeleteOptionalParams, -} from "../../models/options.js"; export function _listSend( context: Client, @@ -35,17 +38,7 @@ export async function _listDeserialize( throw createRestError(result); } - return { - object: result.body["object"], - data: result.body["data"].map((p: any) => { - return { - id: p["id"], - object: p["object"], - created: new Date(p["created"]), - ownedBy: p["owned_by"], - }; - }), - }; + return listModelsResponseDeserializer(result.body); } export async function list( @@ -74,12 +67,7 @@ export async function _retrieveDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - created: new Date(result.body["created"]), - ownedBy: result.body["owned_by"], - }; + return modelDeserializer(result.body); } export async function retrieve( @@ -109,11 +97,7 @@ export async function _$deleteDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - object: result.body["object"], - deleted: result.body["deleted"], - }; + return deleteModelResponseDeserializer(result.body); } /** diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/moderations/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/moderations/index.ts index ff3de04cdb..db0953fec8 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/moderations/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/moderations/index.ts @@ -1,17 +1,21 @@ // Licensed under the MIT License. +import { + OpenAIContext as Client, + ModerationsCreateOptionalParams, +} from "../index.js"; import { CreateModerationRequest, + createModerationRequestSerializer, CreateModerationResponse, + createModerationResponseDeserializer, } from "../../models/models.js"; -import { OpenAIContext as Client } from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -import { ModerationsCreateOptionalParams } from "../../models/options.js"; export function _createSend( context: Client, @@ -22,7 +26,7 @@ export function _createSend( .path("/moderations") .post({ ...operationOptionsToRequestParameters(options), - body: { input: content["input"], model: content["model"] }, + body: createModerationRequestSerializer(content), }); } @@ -34,41 +38,7 @@ export async function _createDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - model: result.body["model"], - results: result.body["results"].map((p: any) => { - return { - flagged: p["flagged"], - categories: { - hate: p.categories["hate"], - "hate/threatening": p.categories["hate/threatening"], - harassment: p.categories["harassment"], - "harassment/threatening": p.categories["harassment/threatening"], - selfHarm: p.categories["self-harm"], - "selfHarm/intent": p.categories["self-harm/intent"], - "selfHarm/instructive": p.categories["self-harm/instructive"], - sexual: p.categories["sexual"], - "sexual/minors": p.categories["sexual/minors"], - violence: p.categories["violence"], - "violence/graphic": p.categories["violence/graphic"], - }, - categoryScores: { - hate: p.category_scores["hate"], - "hate/threatening": p.category_scores["hate/threatening"], - harassment: p.category_scores["harassment"], - "harassment/threatening": p.category_scores["harassment/threatening"], - selfHarm: p.category_scores["self-harm"], - "selfHarm/intent": p.category_scores["self-harm/intent"], - "selfHarm/instructive": p.category_scores["self-harm/instructive"], - sexual: p.category_scores["sexual"], - "sexual/minors": p.category_scores["sexual/minors"], - violence: p.category_scores["violence"], - "violence/graphic": p.category_scores["violence/graphic"], - }, - }; - }), - }; + return createModerationResponseDeserializer(result.body); } export async function create( diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts index f264fcb231..3b90d01f83 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts @@ -1,9 +1,14 @@ // Licensed under the MIT License. -import { KeyCredential } from "@typespec/ts-http-runtime"; -import { ClientOptions, Client, getClient } from "@typespec/ts-http-runtime"; -import { isKeyCredential } from "@typespec/ts-http-runtime"; +import { + Client, + ClientOptions, + getClient, + KeyCredential, + isKeyCredential, +} from "@typespec/ts-http-runtime"; +/** The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details. */ export interface OpenAIContext extends Client {} /** Optional parameters for the client. */ diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/transcriptions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/transcriptions/index.ts index 0b7ffb2974..023ea12464 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/transcriptions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/transcriptions/index.ts @@ -1,12 +1,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../../api/openAIContext.js"; +import { create } from "../../../api/audio/transcriptions/index.js"; +import { AudioTranscriptionsCreateOptionalParams } from "../../../api/options.js"; import { CreateTranscriptionRequest, CreateTranscriptionResponse, } from "../../../models/models.js"; -import { create } from "../../../api/audio/transcriptions/index.js"; -import { AudioTranscriptionsCreateOptionalParams } from "../../../models/options.js"; /** Interface representing a AudioTranscriptions operations. */ export interface AudioTranscriptionsOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/translations/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/translations/index.ts index 3178c35a1e..a09457762e 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/translations/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/translations/index.ts @@ -1,12 +1,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../../api/openAIContext.js"; +import { create } from "../../../api/audio/translations/index.js"; +import { AudioTranslationsCreateOptionalParams } from "../../../api/options.js"; import { CreateTranslationRequest, CreateTranslationResponse, } from "../../../models/models.js"; -import { create } from "../../../api/audio/translations/index.js"; -import { AudioTranslationsCreateOptionalParams } from "../../../models/options.js"; /** Interface representing a AudioTranslations operations. */ export interface AudioTranslationsOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/completions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/completions/index.ts index a1b8a55140..b278f1fef9 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/completions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/completions/index.ts @@ -1,12 +1,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../../api/openAIContext.js"; +import { create } from "../../../api/chat/completions/index.js"; +import { ChatCompletionsCreateOptionalParams } from "../../../api/options.js"; import { CreateChatCompletionRequest, CreateChatCompletionResponse, } from "../../../models/models.js"; -import { create } from "../../../api/chat/completions/index.js"; -import { ChatCompletionsCreateOptionalParams } from "../../../models/options.js"; /** Interface representing a ChatCompletions operations. */ export interface ChatCompletionsOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/completions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/completions/index.ts index 8229d38cf9..04de4374c4 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/completions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/completions/index.ts @@ -1,12 +1,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; +import { create } from "../../api/completions/index.js"; +import { CompletionsCreateOptionalParams } from "../../api/options.js"; import { CreateCompletionRequest, CreateCompletionResponse, } from "../../models/models.js"; -import { create } from "../../api/completions/index.js"; -import { CompletionsCreateOptionalParams } from "../../models/options.js"; /** Interface representing a Completions operations. */ export interface CompletionsOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/edits/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/edits/index.ts index a3a5fe1d37..d69529a23b 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/edits/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/edits/index.ts @@ -1,9 +1,9 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { CreateEditRequest, CreateEditResponse } from "../../models/models.js"; import { create } from "../../api/edits/index.js"; -import { EditsCreateOptionalParams } from "../../models/options.js"; +import { EditsCreateOptionalParams } from "../../api/options.js"; +import { CreateEditRequest, CreateEditResponse } from "../../models/models.js"; /** Interface representing a Edits operations. */ export interface EditsOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/embeddings/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/embeddings/index.ts index 224f3f5393..dc9a1d3fb8 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/embeddings/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/embeddings/index.ts @@ -1,12 +1,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; +import { create } from "../../api/embeddings/index.js"; +import { EmbeddingsCreateOptionalParams } from "../../api/options.js"; import { CreateEmbeddingRequest, CreateEmbeddingResponse, } from "../../models/models.js"; -import { create } from "../../api/embeddings/index.js"; -import { EmbeddingsCreateOptionalParams } from "../../models/options.js"; /** Interface representing a Embeddings operations. */ export interface EmbeddingsOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts index c7c5c3aa44..af14b24f2d 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts @@ -1,12 +1,6 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { - OpenAIFile, - ListFilesResponse, - CreateFileRequest, - DeleteFileResponse, -} from "../../models/models.js"; import { list, create, @@ -20,7 +14,13 @@ import { FilesRetrieveOptionalParams, FilesDeleteOptionalParams, FilesDownloadOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; +import { + ListFilesResponse, + CreateFileRequest, + OpenAIFile, + DeleteFileResponse, +} from "../../models/models.js"; /** Interface representing a Files operations. */ export interface FilesOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts index b990730ffa..8cc61c010c 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts @@ -1,12 +1,6 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { - CreateFineTuneRequest, - FineTune, - ListFineTunesResponse, - ListFineTuneEventsResponse, -} from "../../models/models.js"; import { create, list, @@ -20,7 +14,13 @@ import { FineTunesRetrieveOptionalParams, FineTunesListEventsOptionalParams, FineTunesCancelOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; +import { + CreateFineTuneRequest, + FineTune, + ListFineTunesResponse, + ListFineTuneEventsResponse, +} from "../../models/models.js"; /** Interface representing a FineTunes operations. */ export interface FineTunesOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts index 8d5ab757f9..daa86854a9 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts @@ -1,12 +1,6 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../../api/openAIContext.js"; -import { - CreateFineTuningJobRequest, - FineTuningJob, - ListPaginatedFineTuningJobsResponse, - ListFineTuningJobEventsResponse, -} from "../../../models/models.js"; import { create, list, @@ -20,7 +14,13 @@ import { FineTuningJobsRetrieveOptionalParams, FineTuningJobsListEventsOptionalParams, FineTuningJobsCancelOptionalParams, -} from "../../../models/options.js"; +} from "../../../api/options.js"; +import { + CreateFineTuningJobRequest, + FineTuningJob, + ListPaginatedFineTuningJobsResponse, + ListFineTuningJobEventsResponse, +} from "../../../models/models.js"; /** Interface representing a FineTuningJobs operations. */ export interface FineTuningJobsOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts index 094fd14417..928fd8975d 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts @@ -1,18 +1,18 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; +import { create, createEdit, createVariation } from "../../api/images/index.js"; +import { + ImagesCreateOptionalParams, + ImagesCreateEditOptionalParams, + ImagesCreateVariationOptionalParams, +} from "../../api/options.js"; import { CreateImageRequest, ImagesResponse, CreateImageEditRequest, CreateImageVariationRequest, } from "../../models/models.js"; -import { create, createEdit, createVariation } from "../../api/images/index.js"; -import { - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, - ImagesCreateVariationOptionalParams, -} from "../../models/options.js"; /** Interface representing a Images operations. */ export interface ImagesOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts index 92d00fc267..e3ab15fc60 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts @@ -1,17 +1,17 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { - ListModelsResponse, - Model, - DeleteModelResponse, -} from "../../models/models.js"; import { list, retrieve, $delete } from "../../api/models/index.js"; import { ModelsListOptionalParams, ModelsRetrieveOptionalParams, ModelsDeleteOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; +import { + ListModelsResponse, + Model, + DeleteModelResponse, +} from "../../models/models.js"; /** Interface representing a Models operations. */ export interface ModelsOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/moderations/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/moderations/index.ts index 78157f19d9..17c69545e6 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/moderations/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/moderations/index.ts @@ -1,12 +1,12 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; +import { create } from "../../api/moderations/index.js"; +import { ModerationsCreateOptionalParams } from "../../api/options.js"; import { CreateModerationRequest, CreateModerationResponse, } from "../../models/models.js"; -import { create } from "../../api/moderations/index.js"; -import { ModerationsCreateOptionalParams } from "../../models/options.js"; /** Interface representing a Moderations operations. */ export interface ModerationsOperations { diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/index.ts index 01af425307..a7763cb1ee 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/index.ts @@ -1,6 +1,6 @@ // Licensed under the MIT License. -export { OpenAIClient, OpenAIClientOptionalParams } from "./openAIClient.js"; +export { OpenAIClient } from "./openAIClient.js"; export { CreateModerationRequest, CreateModerationResponse, @@ -30,6 +30,8 @@ export { CreateEditResponse, CompletionUsage, CreateCompletionRequest, + Prompt, + Stop, CreateCompletionResponse, CreateFineTuningJobRequest, FineTuningJob, @@ -41,14 +43,16 @@ export { ChatCompletionFunctions, ChatCompletionFunctionParameters, ChatCompletionFunctionCallOption, + Stop_1, CreateChatCompletionResponse, ChatCompletionResponseMessage, CreateTranslationRequest, CreateTranslationResponse, CreateTranscriptionRequest, CreateTranscriptionResponse, - Prompt, - Stop, +} from "./models/index.js"; +export { + OpenAIClientOptionalParams, AudioTranscriptionsCreateOptionalParams, AudioTranslationsCreateOptionalParams, ChatCompletionsCreateOptionalParams, @@ -77,7 +81,7 @@ export { ImagesCreateEditOptionalParams, ImagesCreateVariationOptionalParams, ModerationsCreateOptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; export { AudioOperations, ChatOperations, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/index.ts index d289718279..dd91a2687e 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/index.ts @@ -29,6 +29,8 @@ export { CreateEditResponse, CompletionUsage, CreateCompletionRequest, + Prompt, + Stop, CreateCompletionResponse, CreateFineTuningJobRequest, FineTuningJob, @@ -40,42 +42,11 @@ export { ChatCompletionFunctions, ChatCompletionFunctionParameters, ChatCompletionFunctionCallOption, + Stop_1, CreateChatCompletionResponse, ChatCompletionResponseMessage, CreateTranslationRequest, CreateTranslationResponse, CreateTranscriptionRequest, CreateTranscriptionResponse, - Prompt, - Stop, } from "./models.js"; -export { - AudioTranscriptionsCreateOptionalParams, - AudioTranslationsCreateOptionalParams, - ChatCompletionsCreateOptionalParams, - FineTuningJobsCreateOptionalParams, - FineTuningJobsListOptionalParams, - FineTuningJobsRetrieveOptionalParams, - FineTuningJobsListEventsOptionalParams, - FineTuningJobsCancelOptionalParams, - CompletionsCreateOptionalParams, - EditsCreateOptionalParams, - EmbeddingsCreateOptionalParams, - FilesListOptionalParams, - FilesCreateOptionalParams, - FilesRetrieveOptionalParams, - FilesDeleteOptionalParams, - FilesDownloadOptionalParams, - FineTunesCreateOptionalParams, - FineTunesListOptionalParams, - FineTunesRetrieveOptionalParams, - FineTunesListEventsOptionalParams, - FineTunesCancelOptionalParams, - ModelsListOptionalParams, - ModelsRetrieveOptionalParams, - ModelsDeleteOptionalParams, - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, - ImagesCreateVariationOptionalParams, - ModerationsCreateOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts index 66ebc6e7e5..150b8bb7d8 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts @@ -1,9 +1,11 @@ // Licensed under the MIT License. -import { serializeRecord } from "../helpers/serializerHelpers.js"; -import {} from "@typespec/ts-http-runtime"; -import { uint8ArrayToString } from "@typespec/ts-http-runtime"; +import { + uint8ArrayToString, + stringToUint8Array, +} from "@typespec/ts-http-runtime"; +/** model interface CreateModerationRequest */ export interface CreateModerationRequest { /** The input text to classify */ input: string | string[]; @@ -14,18 +16,34 @@ export interface CreateModerationRequest { * `text-moderation-stable`, we will provide advanced notice before updating the model. Accuracy * of `text-moderation-stable` may be slightly lower than for `text-moderation-latest`. */ - model?: string | "text-moderation-latest" | "text-moderation-stable"; + model?: "text-moderation-latest" | "text-moderation-stable"; } export function createModerationRequestSerializer( item: CreateModerationRequest, -): Record { +): any { return { - input: item["input"], + input: _createModerationRequestInputSerializer(item["input"]), model: item["model"], }; } +/** Alias for _CreateModerationRequestInput */ +export type _CreateModerationRequestInput = string | string[]; + +export function _createModerationRequestInputSerializer( + item: _CreateModerationRequestInput, +): any { + return item; +} + +export function _createModerationRequestInputDeserializer( + item: any, +): _CreateModerationRequestInput { + return item; +} + +/** model interface CreateModerationResponse */ export interface CreateModerationResponse { /** The unique identifier for the moderation request. */ id: string; @@ -39,22 +57,22 @@ export interface CreateModerationResponse { "hate/threatening": boolean; harassment: boolean; "harassment/threatening": boolean; - selfHarm: boolean; - "selfHarm/intent": boolean; - "selfHarm/instructive": boolean; + "self-harm": boolean; + "self-harm/intent": boolean; + "self-harm/instructive": boolean; sexual: boolean; "sexual/minors": boolean; violence: boolean; "violence/graphic": boolean; }; - categoryScores: { + category_scores: { hate: number; "hate/threatening": number; harassment: number; "harassment/threatening": number; - selfHarm: number; - "selfHarm/intent": number; - "selfHarm/instructive": number; + "self-harm": number; + "self-harm/intent": number; + "self-harm/instructive": number; sexual: number; "sexual/minors": number; violence: number; @@ -63,10 +81,192 @@ export interface CreateModerationResponse { }[]; } +export function createModerationResponseDeserializer( + item: any, +): CreateModerationResponse { + return { + id: item["id"], + model: item["model"], + results: createModerationResponseResultArrayDeserializer(item["results"]), + }; +} + +/** model interface _CreateModerationResponseResult */ +export interface _CreateModerationResponseResult { + /** Whether the content violates [OpenAI's usage policies](/policies/usage-policies). */ + flagged: boolean; + /** A list of the categories, and whether they are flagged or not. */ + categories: { + hate: boolean; + "hate/threatening": boolean; + harassment: boolean; + "harassment/threatening": boolean; + "self-harm": boolean; + "self-harm/intent": boolean; + "self-harm/instructive": boolean; + sexual: boolean; + "sexual/minors": boolean; + violence: boolean; + "violence/graphic": boolean; + }; + /** A list of the categories along with their scores as predicted by model. */ + category_scores: { + hate: number; + "hate/threatening": number; + harassment: number; + "harassment/threatening": number; + "self-harm": number; + "self-harm/intent": number; + "self-harm/instructive": number; + sexual: number; + "sexual/minors": number; + violence: number; + "violence/graphic": number; + }; +} + +export function _createModerationResponseResultDeserializer( + item: any, +): _CreateModerationResponseResult { + return { + flagged: item["flagged"], + categories: _createModerationResponseResultCategoriesDeserializer( + item["categories"], + ), + category_scores: _createModerationResponseResultCategoryScoresDeserializer( + item["category_scores"], + ), + }; +} + +/** model interface _CreateModerationResponseResultCategories */ +export interface _CreateModerationResponseResultCategories { + /** + * Content that expresses, incites, or promotes hate based on race, gender, ethnicity, + * religion, nationality, sexual orientation, disability status, or caste. Hateful content + * aimed at non-protected groups (e.g., chess players) is harrassment. + */ + hate: boolean; + /** + * Hateful content that also includes violence or serious harm towards the targeted group + * based on race, gender, ethnicity, religion, nationality, sexual orientation, disability + * status, or caste. + */ + "hate/threatening": boolean; + /** Content that expresses, incites, or promotes harassing language towards any target. */ + harassment: boolean; + /** Harassment content that also includes violence or serious harm towards any target. */ + "harassment/threatening": boolean; + /** + * Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, + * and eating disorders. + */ + "self-harm": boolean; + /** + * Content where the speaker expresses that they are engaging or intend to engage in acts of + * self-harm, such as suicide, cutting, and eating disorders. + */ + "self-harm/intent": boolean; + /** + * Content that encourages performing acts of self-harm, such as suicide, cutting, and eating + * disorders, or that gives instructions or advice on how to commit such acts. + */ + "self-harm/instructive": boolean; + /** + * Content meant to arouse sexual excitement, such as the description of sexual activity, or + * that promotes sexual services (excluding sex education and wellness). + */ + sexual: boolean; + /** Sexual content that includes an individual who is under 18 years old. */ + "sexual/minors": boolean; + /** Content that depicts death, violence, or physical injury. */ + violence: boolean; + /** Content that depicts death, violence, or physical injury in graphic detail. */ + "violence/graphic": boolean; +} + +export function _createModerationResponseResultCategoriesDeserializer( + item: any, +): _CreateModerationResponseResultCategories { + return { + hate: item["hate"], + "hate/threatening": item["hate/threatening"], + harassment: item["harassment"], + "harassment/threatening": item["harassment/threatening"], + "self-harm": item["self-harm"], + "self-harm/intent": item["self-harm/intent"], + "self-harm/instructive": item["self-harm/instructive"], + sexual: item["sexual"], + "sexual/minors": item["sexual/minors"], + violence: item["violence"], + "violence/graphic": item["violence/graphic"], + }; +} + +/** model interface _CreateModerationResponseResultCategoryScores */ +export interface _CreateModerationResponseResultCategoryScores { + /** The score for the category 'hate'. */ + hate: number; + /** The score for the category 'hate/threatening'. */ + "hate/threatening": number; + /** The score for the category 'harassment'. */ + harassment: number; + /** The score for the category 'harassment/threatening'. */ + "harassment/threatening": number; + /** The score for the category 'self-harm'. */ + "self-harm": number; + /** The score for the category 'self-harm/intent'. */ + "self-harm/intent": number; + /** The score for the category 'self-harm/instructive'. */ + "self-harm/instructive": number; + /** The score for the category 'sexual'. */ + sexual: number; + /** The score for the category 'sexual/minors'. */ + "sexual/minors": number; + /** The score for the category 'violence'. */ + violence: number; + /** The score for the category 'violence/graphic'. */ + "violence/graphic": number; +} + +export function _createModerationResponseResultCategoryScoresDeserializer( + item: any, +): _CreateModerationResponseResultCategoryScores { + return { + hate: item["hate"], + "hate/threatening": item["hate/threatening"], + harassment: item["harassment"], + "harassment/threatening": item["harassment/threatening"], + "self-harm": item["self-harm"], + "self-harm/intent": item["self-harm/intent"], + "self-harm/instructive": item["self-harm/instructive"], + sexual: item["sexual"], + "sexual/minors": item["sexual/minors"], + violence: item["violence"], + "violence/graphic": item["violence/graphic"], + }; +} + +export function createModerationResponseResultArrayDeserializer( + result: Array<_CreateModerationResponseResult>, +): any[] { + return result.map((item) => { + return _createModerationResponseResultDeserializer(item); + }); +} + +/** model interface ErrorResponse */ export interface ErrorResponse { error: ErrorModel; } +export function errorResponseDeserializer(item: any): ErrorResponse { + return { + error: errorDeserializer(item["error"]), + }; +} + +/** model interface ErrorModel */ export interface ErrorModel { type: string; message: string; @@ -74,43 +274,77 @@ export interface ErrorModel { code: string | null; } +export function errorDeserializer(item: any): ErrorModel { + return { + type: item["type"], + message: item["message"], + param: item["param"], + code: item["code"], + }; +} + +/** model interface CreateImageRequest */ export interface CreateImageRequest { /** A text description of the desired image(s). The maximum length is 1000 characters. */ prompt: string; /** The number of images to generate. Must be between 1 and 10. */ n?: number | null; /** The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. */ - size?: "256x256" | "512x512" | "1024x1024"; + size?: ("256x256" | "512x512" | "1024x1024") | null; /** The format in which the generated images are returned. Must be one of `url` or `b64_json`. */ - responseFormat?: "url" | "b64_json"; + response_format?: ("url" | "b64_json") | null; user?: string; } -export function createImageRequestSerializer( - item: CreateImageRequest, -): Record { +export function createImageRequestSerializer(item: CreateImageRequest): any { return { prompt: item["prompt"], n: item["n"], size: item["size"], - response_format: item["responseFormat"], + response_format: item["response_format"], user: item["user"], }; } +/** model interface ImagesResponse */ export interface ImagesResponse { created: Date; data: Image[]; } +export function imagesResponseDeserializer(item: any): ImagesResponse { + return { + created: new Date(item["created"]), + data: imageArrayDeserializer(item["data"]), + }; +} + /** Represents the url or the content of an image generated by the OpenAI API. */ export interface Image { /** The URL of the generated image, if `response_format` is `url` (default). */ url?: string; /** The base64-encoded JSON of the generated image, if `response_format` is `b64_json`. */ - b64Json?: Uint8Array; + b64_json?: Uint8Array; +} + +export function imageDeserializer(item: any): Image { + return { + url: item["url"], + b64_json: !item["b64_json"] + ? item["b64_json"] + : typeof item["b64_json"] === "string" + ? stringToUint8Array(item["b64_json"], "base64") + : item["b64_json"], + }; } +export function imageArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return imageDeserializer(item); + }); +} + +/** model interface CreateImageEditRequest */ export interface CreateImageEditRequest { /** A text description of the desired image(s). The maximum length is 1000 characters. */ prompt: string; @@ -128,29 +362,29 @@ export interface CreateImageEditRequest { /** The number of images to generate. Must be between 1 and 10. */ n?: number | null; /** The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. */ - size?: "256x256" | "512x512" | "1024x1024"; + size?: ("256x256" | "512x512" | "1024x1024") | null; /** The format in which the generated images are returned. Must be one of `url` or `b64_json`. */ - responseFormat?: "url" | "b64_json"; + response_format?: ("url" | "b64_json") | null; user?: string; } export function createImageEditRequestSerializer( item: CreateImageEditRequest, -): Record { +): any { return { prompt: item["prompt"], image: uint8ArrayToString(item["image"], "base64"), - mask: - item["mask"] !== undefined - ? uint8ArrayToString(item["mask"], "base64") - : undefined, + mask: !item["mask"] + ? item["mask"] + : uint8ArrayToString(item["mask"], "base64"), n: item["n"], size: item["size"], - response_format: item["responseFormat"], + response_format: item["response_format"], user: item["user"], }; } +/** model interface CreateImageVariationRequest */ export interface CreateImageVariationRequest { /** * The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, @@ -160,29 +394,37 @@ export interface CreateImageVariationRequest { /** The number of images to generate. Must be between 1 and 10. */ n?: number | null; /** The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. */ - size?: "256x256" | "512x512" | "1024x1024"; + size?: ("256x256" | "512x512" | "1024x1024") | null; /** The format in which the generated images are returned. Must be one of `url` or `b64_json`. */ - responseFormat?: "url" | "b64_json"; + response_format?: ("url" | "b64_json") | null; user?: string; } export function createImageVariationRequestSerializer( item: CreateImageVariationRequest, -): Record { +): any { return { image: uint8ArrayToString(item["image"], "base64"), n: item["n"], size: item["size"], - response_format: item["responseFormat"], + response_format: item["response_format"], user: item["user"], }; } +/** model interface ListModelsResponse */ export interface ListModelsResponse { object: string; data: Model[]; } +export function listModelsResponseDeserializer(item: any): ListModelsResponse { + return { + object: item["object"], + data: modelArrayDeserializer(item["data"]), + }; +} + /** Describes an OpenAI model offering that can be used with the API. */ export interface Model { /** The model identifier, which can be referenced in the API endpoints. */ @@ -192,15 +434,42 @@ export interface Model { /** The Unix timestamp (in seconds) when the model was created. */ created: Date; /** The organization that owns the model. */ - ownedBy: string; + owned_by: string; +} + +export function modelDeserializer(item: any): Model { + return { + id: item["id"], + object: item["object"], + created: new Date(item["created"]), + owned_by: item["owned_by"], + }; } +export function modelArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return modelDeserializer(item); + }); +} + +/** model interface DeleteModelResponse */ export interface DeleteModelResponse { id: string; object: string; deleted: boolean; } +export function deleteModelResponseDeserializer( + item: any, +): DeleteModelResponse { + return { + id: item["id"], + object: item["object"], + deleted: item["deleted"], + }; +} + +/** model interface CreateFineTuneRequest */ export interface CreateFineTuneRequest { /** * The ID of an uploaded file that contains training data. @@ -214,7 +483,7 @@ export interface CreateFineTuneRequest { * See the [fine-tuning guide](/docs/guides/legacy-fine-tuning/creating-training-data) for more * details. */ - trainingFile: string; + training_file: string; /** * The ID of an uploaded file that contains validation data. * @@ -230,18 +499,18 @@ export interface CreateFineTuneRequest { * See the [fine-tuning guide](/docs/guides/legacy-fine-tuning/creating-training-data) for more * details. */ - validationFile?: string | null; + validation_file?: string | null; /** * The name of the base model to fine-tune. You can select one of "ada", "babbage", "curie", * "davinci", or a fine-tuned model created after 2022-04-21 and before 2023-08-22. To learn more * about these models, see the [Models](/docs/models) documentation. */ - model?: string | "ada" | "babbage" | "curie" | "davinci"; + model?: ("ada" | "babbage" | "curie" | "davinci") | null; /** * The number of epochs to train the model for. An epoch refers to one full cycle through the * training dataset. */ - nEpochs?: number | null; + n_epochs?: number | null; /** * The batch size to use for training. The batch size is the number of training examples used to * train a single forward and backward pass. @@ -250,7 +519,7 @@ export interface CreateFineTuneRequest { * in the training set, capped at 256 - in general, we've found that larger batch sizes tend to * work better for larger datasets. */ - batchSize?: number | null; + batch_size?: number | null; /** * The learning rate multiplier to use for training. The fine-tuning learning rate is the original * learning rate used for pretraining multiplied by this value. @@ -260,7 +529,7 @@ export interface CreateFineTuneRequest { * recommend experimenting with values in the range 0.02 to 0.2 to see what produces the best * results. */ - learningRateMultiplier?: number | null; + learning_rate_multiplier?: number | null; /** * The weight to use for loss on the prompt tokens. This controls how much the model tries to * learn to generate the prompt (as compared to the completion which always has a weight of 1.0), @@ -269,7 +538,7 @@ export interface CreateFineTuneRequest { * If prompts are extremely long (relative to completions), it may make sense to reduce this * weight so as to avoid over-prioritizing learning the prompt. */ - promptLossRate?: number | null; + prompt_loss_rate?: number | null; /** * If set, we calculate classification-specific metrics such as accuracy and F-1 score using the * validation set at the end of every epoch. These metrics can be viewed in the @@ -279,20 +548,20 @@ export interface CreateFineTuneRequest { * you must specify `classification_n_classes` for multiclass classification or * `classification_positive_class` for binary classification. */ - computeClassificationMetrics?: boolean | null; + compute_classification_metrics?: boolean | null; /** * The number of classes in a classification task. * * This parameter is required for multiclass classification. */ - classificationNClasses?: number | null; + classification_n_classes?: number | null; /** * The positive class in binary classification. * * This parameter is needed to generate precision, recall, and F1 metrics when doing binary * classification. */ - classificationPositiveClass?: string | null; + classification_positive_class?: string | null; /** * If this is provided, we calculate F-beta scores at the specified beta values. The F-beta score * is a generalization of F-1 score. This is only used for binary classification. @@ -301,7 +570,7 @@ export interface CreateFineTuneRequest { * beta score puts more weight on recall and less on precision. A smaller beta score puts more * weight on precision and less on recall. */ - classificationBetas?: number[] | null; + classification_betas?: number[] | null; /** * A string of up to 18 characters that will be added to your fine-tuned model name. * @@ -313,19 +582,23 @@ export interface CreateFineTuneRequest { export function createFineTuneRequestSerializer( item: CreateFineTuneRequest, -): Record { +): any { return { - training_file: item["trainingFile"], - validation_file: item["validationFile"], + training_file: item["training_file"], + validation_file: item["validation_file"], model: item["model"], - n_epochs: item["nEpochs"], - batch_size: item["batchSize"], - learning_rate_multiplier: item["learningRateMultiplier"], - prompt_loss_rate: item["promptLossRate"], - compute_classification_metrics: item["computeClassificationMetrics"], - classification_n_classes: item["classificationNClasses"], - classification_positive_class: item["classificationPositiveClass"], - classification_betas: item["classificationBetas"], + n_epochs: item["n_epochs"], + batch_size: item["batch_size"], + learning_rate_multiplier: item["learning_rate_multiplier"], + prompt_loss_rate: item["prompt_loss_rate"], + compute_classification_metrics: item["compute_classification_metrics"], + classification_n_classes: item["classification_n_classes"], + classification_positive_class: item["classification_positive_class"], + classification_betas: !item["classification_betas"] + ? item["classification_betas"] + : item["classification_betas"].map((p: any) => { + return p; + }), suffix: item["suffix"], }; } @@ -337,15 +610,15 @@ export interface FineTune { /** The object type, which is always "fine-tune". */ object: "fine-tune"; /** The Unix timestamp (in seconds) for when the fine-tuning job was created. */ - createdAt: Date; + created_at: Date; /** The Unix timestamp (in seconds) for when the fine-tuning job was last updated. */ - updatedAt: Date; + updated_at: Date; /** The base model that is being fine-tuned. */ model: string; /** The name of the fine-tuned model that is being created. */ - fineTunedModel: string | null; + fine_tuned_model: string | null; /** The organization that owns the fine-tuning job. */ - organizationId: string; + organization_id: string; /** * The current status of the fine-tuning job, which can be either `created`, `running`, * `succeeded`, `failed`, or `cancelled`. @@ -356,24 +629,82 @@ export interface FineTune { * [fine-tuning guide](/docs/guides/legacy-fine-tuning/hyperparameters) for more details. */ hyperparams: { - nEpochs: number; - batchSize: number; - promptLossWeight: number; - learningRateMultiplier: number; - computeClassificationMetrics?: boolean; - classificationPositiveClass?: string; - classificationNClasses?: number; + n_epochs: number; + batch_size: number; + prompt_loss_weight: number; + learning_rate_multiplier: number; + compute_classification_metrics?: boolean; + classification_positive_class?: string; + classification_n_classes?: number; }; /** The list of files used for training. */ - trainingFiles: OpenAIFile[]; + training_files: OpenAIFile[]; /** The list of files used for validation. */ - validationFiles: OpenAIFile[]; + validation_files: OpenAIFile[]; /** The compiled results files for the fine-tuning job. */ - resultFiles: OpenAIFile[]; + result_files: OpenAIFile[]; /** The list of events that have been observed in the lifecycle of the FineTune job. */ events?: FineTuneEvent[]; } +export function fineTuneDeserializer(item: any): FineTune { + return { + id: item["id"], + object: item["object"], + created_at: new Date(item["created_at"]), + updated_at: new Date(item["updated_at"]), + model: item["model"], + fine_tuned_model: item["fine_tuned_model"], + organization_id: item["organization_id"], + status: item["status"], + hyperparams: _fineTuneHyperparamsDeserializer(item["hyperparams"]), + training_files: openAIFileArrayDeserializer(item["training_files"]), + validation_files: openAIFileArrayDeserializer(item["validation_files"]), + result_files: openAIFileArrayDeserializer(item["result_files"]), + events: !item["events"] + ? item["events"] + : fineTuneEventArrayDeserializer(item["events"]), + }; +} + +/** model interface _FineTuneHyperparams */ +export interface _FineTuneHyperparams { + /** + * The number of epochs to train the model for. An epoch refers to one full cycle through the + * training dataset. + */ + n_epochs: number; + /** + * The batch size to use for training. The batch size is the number of training examples used to + * train a single forward and backward pass. + */ + batch_size: number; + /** The weight to use for loss on the prompt tokens. */ + prompt_loss_weight: number; + /** The learning rate multiplier to use for training. */ + learning_rate_multiplier: number; + /** The classification metrics to compute using the validation dataset at the end of every epoch. */ + compute_classification_metrics?: boolean; + /** The positive class to use for computing classification metrics. */ + classification_positive_class?: string; + /** The number of classes to use for computing classification metrics. */ + classification_n_classes?: number; +} + +export function _fineTuneHyperparamsDeserializer( + item: any, +): _FineTuneHyperparams { + return { + n_epochs: item["n_epochs"], + batch_size: item["batch_size"], + prompt_loss_weight: item["prompt_loss_weight"], + learning_rate_multiplier: item["learning_rate_multiplier"], + compute_classification_metrics: item["compute_classification_metrics"], + classification_positive_class: item["classification_positive_class"], + classification_n_classes: item["classification_n_classes"], + }; +} + /** The `File` object represents a document that has been uploaded to OpenAI. */ export interface OpenAIFile { /** The file identifier, which can be referenced in the API endpoints. */ @@ -403,31 +734,103 @@ export interface OpenAIFile { * Additional details about the status of the file. If the file is in the `error` state, this will * include a message describing the error. */ - statusDetails?: string | null; + status_details?: string | null; +} + +export function openAIFileDeserializer(item: any): OpenAIFile { + return { + id: item["id"], + object: item["object"], + bytes: item["bytes"], + createdAt: new Date(item["createdAt"]), + filename: item["filename"], + purpose: item["purpose"], + status: item["status"], + status_details: item["status_details"], + }; +} + +export function openAIFileArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return openAIFileDeserializer(item); + }); } +/** model interface FineTuneEvent */ export interface FineTuneEvent { object: string; - createdAt: Date; + created_at: Date; level: string; message: string; } +export function fineTuneEventDeserializer(item: any): FineTuneEvent { + return { + object: item["object"], + created_at: new Date(item["created_at"]), + level: item["level"], + message: item["message"], + }; +} + +export function fineTuneEventArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return fineTuneEventDeserializer(item); + }); +} + +/** model interface ListFineTunesResponse */ export interface ListFineTunesResponse { object: string; data: FineTune[]; } +export function listFineTunesResponseDeserializer( + item: any, +): ListFineTunesResponse { + return { + object: item["object"], + data: fineTuneArrayDeserializer(item["data"]), + }; +} + +export function fineTuneArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return fineTuneDeserializer(item); + }); +} + +/** model interface ListFineTuneEventsResponse */ export interface ListFineTuneEventsResponse { object: string; data: FineTuneEvent[]; } +export function listFineTuneEventsResponseDeserializer( + item: any, +): ListFineTuneEventsResponse { + return { + object: item["object"], + data: fineTuneEventArrayDeserializer(item["data"]), + }; +} + +/** model interface ListFilesResponse */ export interface ListFilesResponse { object: string; data: OpenAIFile[]; } +export function listFilesResponseDeserializer(item: any): ListFilesResponse { + return { + object: item["object"], + data: openAIFileArrayDeserializer(item["data"]), + }; +} + +/** model interface CreateFileRequest */ export interface CreateFileRequest { /** * Name of the [JSON Lines](https://jsonlines.readthedocs.io/en/latest/) file to be uploaded. @@ -443,24 +846,32 @@ export interface CreateFileRequest { purpose: string; } -export function createFileRequestSerializer( - item: CreateFileRequest, -): Record { +export function createFileRequestSerializer(item: CreateFileRequest): any { return { file: uint8ArrayToString(item["file"], "base64"), purpose: item["purpose"], }; } +/** model interface DeleteFileResponse */ export interface DeleteFileResponse { id: string; object: string; deleted: boolean; } +export function deleteFileResponseDeserializer(item: any): DeleteFileResponse { + return { + id: item["id"], + object: item["object"], + deleted: item["deleted"], + }; +} + +/** model interface CreateEmbeddingRequest */ export interface CreateEmbeddingRequest { /** ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them. */ - model: string | "text-embedding-ada-002"; + model: "text-embedding-ada-002"; /** * Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a * single request, pass an array of strings or array of token arrays. Each input must not exceed @@ -474,14 +885,34 @@ export interface CreateEmbeddingRequest { export function createEmbeddingRequestSerializer( item: CreateEmbeddingRequest, -): Record { +): any { return { model: item["model"], - input: item["input"], + input: _createEmbeddingRequestInputSerializer(item["input"]), user: item["user"], }; } +/** Alias for _CreateEmbeddingRequestInput */ +export type _CreateEmbeddingRequestInput = + | string + | string[] + | number[] + | number[][]; + +export function _createEmbeddingRequestInputSerializer( + item: _CreateEmbeddingRequestInput, +): any { + return item; +} + +export function _createEmbeddingRequestInputDeserializer( + item: any, +): _CreateEmbeddingRequestInput { + return item; +} + +/** model interface CreateEmbeddingResponse */ export interface CreateEmbeddingResponse { /** The object type, which is always "embedding". */ object: "embedding"; @@ -490,7 +921,21 @@ export interface CreateEmbeddingResponse { /** The list of embeddings generated by the model. */ data: Embedding[]; /** The usage information for the request. */ - usage: { promptTokens: number; totalTokens: number }; + usage: { + prompt_tokens: number; + total_tokens: number; + }; +} + +export function createEmbeddingResponseDeserializer( + item: any, +): CreateEmbeddingResponse { + return { + object: item["object"], + model: item["model"], + data: embeddingArrayDeserializer(item["data"]), + usage: _createEmbeddingResponseUsageDeserializer(item["usage"]), + }; } /** Represents an embedding vector returned by embedding endpoint. */ @@ -506,12 +951,46 @@ export interface Embedding { embedding: number[]; } +export function embeddingDeserializer(item: any): Embedding { + return { + index: item["index"], + object: item["object"], + embedding: item["embedding"].map((p: any) => { + return p; + }), + }; +} + +export function embeddingArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return embeddingDeserializer(item); + }); +} + +/** model interface _CreateEmbeddingResponseUsage */ +export interface _CreateEmbeddingResponseUsage { + /** The number of tokens used by the prompt. */ + prompt_tokens: number; + /** The total number of tokens used by the request. */ + total_tokens: number; +} + +export function _createEmbeddingResponseUsageDeserializer( + item: any, +): _CreateEmbeddingResponseUsage { + return { + prompt_tokens: item["prompt_tokens"], + total_tokens: item["total_tokens"], + }; +} + +/** model interface CreateEditRequest */ export interface CreateEditRequest { /** * ID of the model to use. You can use the `text-davinci-edit-001` or `code-davinci-edit-001` * model with this endpoint. */ - model: string | "text-davinci-edit-001" | "code-davinci-edit-001"; + model: "text-davinci-edit-001" | "code-davinci-edit-001"; /** The input text to use as a starting point for the edit. */ input?: string | null; /** The instruction that tells the model how to edit the prompt. */ @@ -532,42 +1011,95 @@ export interface CreateEditRequest { * * We generally recommend altering this or `temperature` but not both. */ - topP?: number | null; + top_p?: number | null; } -export function createEditRequestSerializer( - item: CreateEditRequest, -): Record { +export function createEditRequestSerializer(item: CreateEditRequest): any { return { model: item["model"], input: item["input"], instruction: item["instruction"], n: item["n"], temperature: item["temperature"], - top_p: item["topP"], + top_p: item["top_p"], }; } +/** model interface CreateEditResponse */ export interface CreateEditResponse { /** The object type, which is always `edit`. */ object: "edit"; /** The Unix timestamp (in seconds) of when the edit was created. */ created: Date; /** description: A list of edit choices. Can be more than one if `n` is greater than 1. */ - choices: { text: string; index: number; finishReason: "stop" | "length" }[]; + choices: { + text: string; + index: number; + finish_reason: "stop" | "length"; + }[]; usage: CompletionUsage; } +export function createEditResponseDeserializer(item: any): CreateEditResponse { + return { + object: item["object"], + created: new Date(item["created"]), + choices: createEditResponseChoiceArrayDeserializer(item["choices"]), + usage: completionUsageDeserializer(item["usage"]), + }; +} + +/** model interface _CreateEditResponseChoice */ +export interface _CreateEditResponseChoice { + /** The edited result. */ + text: string; + /** The index of the choice in the list of choices. */ + index: number; + /** + * The reason the model stopped generating tokens. This will be `stop` if the model hit a + * natural stop point or a provided stop sequence, or `length` if the maximum number of tokens + * specified in the request was reached. + */ + finish_reason: "stop" | "length"; +} + +export function _createEditResponseChoiceDeserializer( + item: any, +): _CreateEditResponseChoice { + return { + text: item["text"], + index: item["index"], + finish_reason: item["finish_reason"], + }; +} + +export function createEditResponseChoiceArrayDeserializer( + result: Array<_CreateEditResponseChoice>, +): any[] { + return result.map((item) => { + return _createEditResponseChoiceDeserializer(item); + }); +} + /** Usage statistics for the completion request. */ export interface CompletionUsage { /** Number of tokens in the prompt. */ - promptTokens: number; + prompt_tokens: number; /** Number of tokens in the generated completion */ - completionTokens: number; + completion_tokens: number; /** Total number of tokens used in the request (prompt + completion). */ - totalTokens: number; + total_tokens: number; +} + +export function completionUsageDeserializer(item: any): CompletionUsage { + return { + prompt_tokens: item["prompt_tokens"], + completion_tokens: item["completion_tokens"], + total_tokens: item["total_tokens"], + }; } +/** model interface CreateCompletionRequest */ export interface CreateCompletionRequest { /** * ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to @@ -575,7 +1107,6 @@ export interface CreateCompletionRequest { * descriptions of them. */ model: - | string | "babbage-002" | "davinci-002" | "text-davinci-003" @@ -592,7 +1123,7 @@ export interface CreateCompletionRequest { * Note that <|endoftext|> is the document separator that the model sees during training, so if a * prompt is not specified the model will generate as if from the beginning of a new document. */ - prompt: Prompt; + prompt: Prompt | null; /** The suffix that comes after a completion of inserted text. */ suffix?: string | null; /** @@ -609,7 +1140,7 @@ export interface CreateCompletionRequest { * * We generally recommend altering this or `temperature` but not both. */ - topP?: number | null; + top_p?: number | null; /** * How many completions to generate for each prompt. * **Note:** Because this parameter generates many completions, it can quickly consume your token @@ -623,16 +1154,16 @@ export interface CreateCompletionRequest { * [Example Python code](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb) * for counting tokens. */ - maxTokens?: number | null; + max_tokens?: number | null; /** Up to 4 sequences where the API will stop generating further tokens. */ - stop?: Stop; + stop?: Stop | null; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear * in the text so far, increasing the model's likelihood to talk about new topics. * * [See more information about frequency and presence penalties.](/docs/guides/gpt/parameter-details) */ - presencePenalty?: number | null; + presence_penalty?: number | null; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing * frequency in the text so far, decreasing the model's likelihood to repeat the same line @@ -640,7 +1171,7 @@ export interface CreateCompletionRequest { * * [See more information about frequency and presence penalties.](/docs/guides/gpt/parameter-details) */ - frequencyPenalty?: number | null; + frequency_penalty?: number | null; /** * Modify the likelihood of specified tokens appearing in the completion. * Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an @@ -649,7 +1180,7 @@ export interface CreateCompletionRequest { * between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 * should result in a ban or exclusive selection of the relevant token. */ - logitBias?: Record | null; + logit_bias?: Record | null; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect * abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). @@ -683,34 +1214,54 @@ export interface CreateCompletionRequest { * **Note:** Because this parameter generates many completions, it can quickly consume your token * quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`. */ - bestOf?: number | null; + best_of?: number | null; } export function createCompletionRequestSerializer( item: CreateCompletionRequest, -): Record { +): any { return { model: item["model"], prompt: item["prompt"], suffix: item["suffix"], temperature: item["temperature"], - top_p: item["topP"], + top_p: item["top_p"], n: item["n"], - max_tokens: item["maxTokens"], + max_tokens: item["max_tokens"], stop: item["stop"], - presence_penalty: item["presencePenalty"], - frequency_penalty: item["frequencyPenalty"], - logit_bias: !item.logitBias - ? item.logitBias - : (serializeRecord(item.logitBias as any) as any), + presence_penalty: item["presence_penalty"], + frequency_penalty: item["frequency_penalty"], + logit_bias: item["logit_bias"], user: item["user"], stream: item["stream"], logprobs: item["logprobs"], echo: item["echo"], - best_of: item["bestOf"], + best_of: item["best_of"], }; } +/** Alias for Prompt */ +export type Prompt = string | string[] | number[] | number[][]; + +export function promptSerializer(item: Prompt): any { + return item; +} + +export function promptDeserializer(item: any): Prompt { + return item; +} + +/** Alias for Stop */ +export type Stop = string | string[]; + +export function stopSerializer(item: Stop): any { + return item; +} + +export function stopDeserializer(item: any): Stop { + return item; +} + /** * Represents a completion response from the API. Note: both the streamed and non-streamed response * objects share the same shape (unlike the chat endpoint). @@ -730,15 +1281,97 @@ export interface CreateCompletionResponse { text: string; logprobs: { tokens: string[]; - tokenLogprobs: number[]; - topLogprobs: Record[]; - textOffset: number[]; + token_logprobs: number[]; + top_logprobs: Record[]; + text_offset: number[]; } | null; - finishReason: "stop" | "length" | "content_filter"; + finish_reason: "stop" | "length" | "content_filter"; }[]; usage?: CompletionUsage; } +export function createCompletionResponseDeserializer( + item: any, +): CreateCompletionResponse { + return { + id: item["id"], + object: item["object"], + created: new Date(item["created"]), + model: item["model"], + choices: createCompletionResponseChoiceArrayDeserializer(item["choices"]), + usage: !item["usage"] + ? item["usage"] + : completionUsageDeserializer(item["usage"]), + }; +} + +/** model interface _CreateCompletionResponseChoice */ +export interface _CreateCompletionResponseChoice { + index: number; + text: string; + logprobs: { + tokens: string[]; + token_logprobs: number[]; + top_logprobs: Record[]; + text_offset: number[]; + } | null; + /** + * The reason the model stopped generating tokens. This will be `stop` if the model hit a + * natural stop point or a provided stop sequence, or `content_filter` if content was omitted + * due to a flag from our content filters, `length` if the maximum number of tokens specified + * in the request was reached, or `content_filter` if content was omitted due to a flag from our + * content filters. + */ + finish_reason: "stop" | "length" | "content_filter"; +} + +export function _createCompletionResponseChoiceDeserializer( + item: any, +): _CreateCompletionResponseChoice { + return { + index: item["index"], + text: item["text"], + logprobs: item["logprobs"], + finish_reason: item["finish_reason"], + }; +} + +/** model interface _CreateCompletionResponseChoiceLogprobs */ +export interface _CreateCompletionResponseChoiceLogprobs { + tokens: string[]; + token_logprobs: number[]; + top_logprobs: Record[]; + text_offset: number[]; +} + +export function _createCompletionResponseChoiceLogprobsDeserializer( + item: any, +): _CreateCompletionResponseChoiceLogprobs { + return { + tokens: item["tokens"].map((p: any) => { + return p; + }), + token_logprobs: item["token_logprobs"].map((p: any) => { + return p; + }), + top_logprobs: item["top_logprobs"].map((p: any) => { + return p; + }), + text_offset: item["text_offset"].map((p: any) => { + return p; + }), + }; +} + +export function createCompletionResponseChoiceArrayDeserializer( + result: Array<_CreateCompletionResponseChoice>, +): any[] { + return result.map((item) => { + return _createCompletionResponseChoiceDeserializer(item); + }); +} + +/** model interface CreateFineTuningJobRequest */ export interface CreateFineTuningJobRequest { /** * The ID of an uploaded file that contains training data. @@ -750,7 +1383,7 @@ export interface CreateFineTuningJobRequest { * * See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. */ - trainingFile: string; + training_file: string; /** * The ID of an uploaded file that contains validation data. * @@ -763,14 +1396,16 @@ export interface CreateFineTuningJobRequest { * * See the [fine-tuning guide](/docs/guides/fine-tuning) for more details. */ - validationFile?: string | null; + validation_file?: string | null; /** * The name of the model to fine-tune. You can select one of the * [supported models](/docs/guides/fine-tuning/what-models-can-be-fine-tuned). */ - model: string | "babbage-002" | "davinci-002" | "gpt-3.5-turbo"; + model: "babbage-002" | "davinci-002" | "gpt-3.5-turbo"; /** The hyperparameters used for the fine-tuning job. */ - hyperparameters?: { nEpochs?: "auto" | number }; + hyperparameters?: { + n_epochs?: "auto" | number; + }; /** * A string of up to 18 characters that will be added to your fine-tuned model name. * @@ -782,39 +1417,78 @@ export interface CreateFineTuningJobRequest { export function createFineTuningJobRequestSerializer( item: CreateFineTuningJobRequest, -): Record { +): any { return { - training_file: item["trainingFile"], - validation_file: item["validationFile"], + training_file: item["training_file"], + validation_file: item["validation_file"], model: item["model"], - hyperparameters: !item.hyperparameters - ? undefined - : { n_epochs: item.hyperparameters?.["nEpochs"] }, + hyperparameters: !item["hyperparameters"] + ? item["hyperparameters"] + : _createFineTuningJobRequestHyperparametersSerializer( + item["hyperparameters"], + ), suffix: item["suffix"], }; } +/** model interface _CreateFineTuningJobRequestHyperparameters */ +export interface _CreateFineTuningJobRequestHyperparameters { + /** + * The number of epochs to train the model for. An epoch refers to one full cycle through the + * training dataset. + */ + n_epochs?: "auto" | number; +} + +export function _createFineTuningJobRequestHyperparametersSerializer( + item: _CreateFineTuningJobRequestHyperparameters, +): any { + return { + n_epochs: !item["n_epochs"] + ? item["n_epochs"] + : _createFineTuningJobRequestHyperparametersNEpochsSerializer( + item["n_epochs"], + ), + }; +} + +/** Alias for _CreateFineTuningJobRequestHyperparametersNEpochs */ +export type _CreateFineTuningJobRequestHyperparametersNEpochs = "auto" | number; + +export function _createFineTuningJobRequestHyperparametersNEpochsSerializer( + item: _CreateFineTuningJobRequestHyperparametersNEpochs, +): any { + return item; +} + +export function _createFineTuningJobRequestHyperparametersNEpochsDeserializer( + item: any, +): _CreateFineTuningJobRequestHyperparametersNEpochs { + return item; +} + +/** model interface FineTuningJob */ export interface FineTuningJob { /** The object identifier, which can be referenced in the API endpoints. */ id: string; /** The object type, which is always "fine_tuning.job". */ object: "fine_tuning.job"; /** The Unix timestamp (in seconds) for when the fine-tuning job was created. */ - createdAt: Date; + created_at: Date; /** * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be * null if the fine-tuning job is still running. */ - finishedAt: Date | null; + finished_at: Date | null; /** The base model that is being fine-tuned. */ model: string; /** * The name of the fine-tuned model that is being created. The value will be null if the * fine-tuning job is still running. */ - fineTunedModel: string | null; + fine_tuned_model: string | null; /** The organization that owns the fine-tuning job. */ - organizationId: string; + organization_id: string; /** * The current status of the fine-tuning job, which can be either `created`, `pending`, `running`, * `succeeded`, `failed`, or `cancelled`. @@ -830,60 +1504,201 @@ export interface FineTuningJob { * The hyperparameters used for the fine-tuning job. See the * [fine-tuning guide](/docs/guides/fine-tuning) for more details. */ - hyperparameters: { nEpochs?: "auto" | number }; + hyperparameters: { + n_epochs?: "auto" | number; + }; /** * The file ID used for training. You can retrieve the training data with the * [Files API](/docs/api-reference/files/retrieve-contents). */ - trainingFile: string; + training_file: string; /** * The file ID used for validation. You can retrieve the validation results with the * [Files API](/docs/api-reference/files/retrieve-contents). */ - validationFile: string | null; + validation_file: string | null; /** * The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the * [Files API](/docs/api-reference/files/retrieve-contents). */ - resultFiles: string[]; + result_files: string[]; /** * The total number of billable tokens processed by this fine tuning job. The value will be null * if the fine-tuning job is still running. */ - trainedTokens: number | null; + trained_tokens: number | null; /** * For fine-tuning jobs that have `failed`, this will contain more information on the cause of the * failure. */ - error: { message?: string; code?: string; param?: string | null } | null; + error: { + message?: string; + code?: string; + param?: string | null; + } | null; } +export function fineTuningJobDeserializer(item: any): FineTuningJob { + return { + id: item["id"], + object: item["object"], + created_at: new Date(item["created_at"]), + finished_at: !item["finished_at"] + ? item["finished_at"] + : !item["finished_at"] + ? item["finished_at"] + : new Date(item["finished_at"]), + model: item["model"], + fine_tuned_model: item["fine_tuned_model"], + organization_id: item["organization_id"], + status: item["status"], + hyperparameters: _fineTuningJobHyperparametersDeserializer( + item["hyperparameters"], + ), + training_file: item["training_file"], + validation_file: item["validation_file"], + result_files: item["result_files"].map((p: any) => { + return p; + }), + trained_tokens: item["trained_tokens"], + error: item["error"], + }; +} + +/** model interface _FineTuningJobHyperparameters */ +export interface _FineTuningJobHyperparameters { + /** + * The number of epochs to train the model for. An epoch refers to one full cycle through the + * training dataset. + * + * "Auto" decides the optimal number of epochs based on the size of the dataset. If setting the + * number manually, we support any number between 1 and 50 epochs. + */ + n_epochs?: "auto" | number; +} + +export function _fineTuningJobHyperparametersDeserializer( + item: any, +): _FineTuningJobHyperparameters { + return { + n_epochs: !item["n_epochs"] + ? item["n_epochs"] + : _fineTuningJobHyperparametersNEpochsDeserializer(item["n_epochs"]), + }; +} + +/** Alias for _FineTuningJobHyperparametersNEpochs */ +export type _FineTuningJobHyperparametersNEpochs = "auto" | number; + +export function _fineTuningJobHyperparametersNEpochsSerializer( + item: _FineTuningJobHyperparametersNEpochs, +): any { + return item; +} + +export function _fineTuningJobHyperparametersNEpochsDeserializer( + item: any, +): _FineTuningJobHyperparametersNEpochs { + return item; +} + +/** model interface _FineTuningJobError */ +export interface _FineTuningJobError { + /** A human-readable error message. */ + message?: string; + /** A machine-readable error code. */ + code?: string; + /** + * The parameter that was invalid, usually `training_file` or `validation_file`. This field + * will be null if the failure was not parameter-specific. + */ + param?: string | null; +} + +export function _fineTuningJobErrorDeserializer( + item: any, +): _FineTuningJobError { + return { + message: item["message"], + code: item["code"], + param: item["param"], + }; +} + +/** model interface ListPaginatedFineTuningJobsResponse */ export interface ListPaginatedFineTuningJobsResponse { object: string; data: FineTuningJob[]; - hasMore: boolean; + has_more: boolean; } +export function listPaginatedFineTuningJobsResponseDeserializer( + item: any, +): ListPaginatedFineTuningJobsResponse { + return { + object: item["object"], + data: fineTuningJobArrayDeserializer(item["data"]), + has_more: item["has_more"], + }; +} + +export function fineTuningJobArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return fineTuningJobDeserializer(item); + }); +} + +/** model interface ListFineTuningJobEventsResponse */ export interface ListFineTuningJobEventsResponse { object: string; data: FineTuningJobEvent[]; } +export function listFineTuningJobEventsResponseDeserializer( + item: any, +): ListFineTuningJobEventsResponse { + return { + object: item["object"], + data: fineTuningJobEventArrayDeserializer(item["data"]), + }; +} + +/** model interface FineTuningJobEvent */ export interface FineTuningJobEvent { id: string; object: string; - createdAt: Date; + created_at: Date; level: "info" | "warn" | "error"; message: string; } +export function fineTuningJobEventDeserializer(item: any): FineTuningJobEvent { + return { + id: item["id"], + object: item["object"], + created_at: new Date(item["created_at"]), + level: item["level"], + message: item["message"], + }; +} + +export function fineTuningJobEventArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return fineTuningJobEventDeserializer(item); + }); +} + +/** model interface CreateChatCompletionRequest */ export interface CreateChatCompletionRequest { /** * ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) * table for details on which models work with the Chat API. */ model: - | string | "gpt4" | "gpt-4-0314" | "gpt-4-0613" @@ -909,7 +1724,7 @@ export interface CreateChatCompletionRequest { * model to call that function. `none` is the default when no functions are present. `auto` is the * default if functions are present. */ - functionCall?: "none" | "auto" | ChatCompletionFunctionCallOption; + function_call?: "none" | "auto" | ChatCompletionFunctionCallOption; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output * more random, while lower values like 0.2 will make it more focused and deterministic. @@ -924,7 +1739,7 @@ export interface CreateChatCompletionRequest { * * We generally recommend altering this or `temperature` but not both. */ - topP?: number | null; + top_p?: number | null; /** * How many completions to generate for each prompt. * **Note:** Because this parameter generates many completions, it can quickly consume your token @@ -938,16 +1753,16 @@ export interface CreateChatCompletionRequest { * [Example Python code](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb) * for counting tokens. */ - maxTokens?: number | null; + max_tokens?: number | null; /** Up to 4 sequences where the API will stop generating further tokens. */ - stop?: Stop; + stop?: Stop_1 | null; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear * in the text so far, increasing the model's likelihood to talk about new topics. * * [See more information about frequency and presence penalties.](/docs/guides/gpt/parameter-details) */ - presencePenalty?: number | null; + presence_penalty?: number | null; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing * frequency in the text so far, decreasing the model's likelihood to repeat the same line @@ -955,7 +1770,7 @@ export interface CreateChatCompletionRequest { * * [See more information about frequency and presence penalties.](/docs/guides/gpt/parameter-details) */ - frequencyPenalty?: number | null; + frequency_penalty?: number | null; /** * Modify the likelihood of specified tokens appearing in the completion. * Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an @@ -964,7 +1779,7 @@ export interface CreateChatCompletionRequest { * between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 * should result in a ban or exclusive selection of the relevant token. */ - logitBias?: Record | null; + logit_bias?: Record | null; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect * abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). @@ -981,30 +1796,32 @@ export interface CreateChatCompletionRequest { export function createChatCompletionRequestSerializer( item: CreateChatCompletionRequest, -): Record { +): any { return { model: item["model"], - messages: item["messages"].map(chatCompletionRequestMessageSerializer), - functions: - item["functions"] === undefined - ? item["functions"] - : item["functions"].map(chatCompletionFunctionsSerializer), - function_call: item["functionCall"], + messages: chatCompletionRequestMessageArraySerializer(item["messages"]), + functions: !item["functions"] + ? item["functions"] + : chatCompletionFunctionsArraySerializer(item["functions"]), + function_call: !item["function_call"] + ? item["function_call"] + : _createChatCompletionRequestFunctionCall1Serializer( + item["function_call"], + ), temperature: item["temperature"], - top_p: item["topP"], + top_p: item["top_p"], n: item["n"], - max_tokens: item["maxTokens"], + max_tokens: item["max_tokens"], stop: item["stop"], - presence_penalty: item["presencePenalty"], - frequency_penalty: item["frequencyPenalty"], - logit_bias: !item.logitBias - ? item.logitBias - : (serializeRecord(item.logitBias as any) as any), + presence_penalty: item["presence_penalty"], + frequency_penalty: item["frequency_penalty"], + logit_bias: item["logit_bias"], user: item["user"], stream: item["stream"], }; } +/** model interface ChatCompletionRequestMessage */ export interface ChatCompletionRequestMessage { /** The role of the messages author. One of `system`, `user`, `assistant`, or `function`. */ role: "system" | "user" | "assistant" | "function"; @@ -1020,25 +1837,54 @@ export interface ChatCompletionRequestMessage { */ name?: string; /** The name and arguments of a function that should be called, as generated by the model. */ - functionCall?: { name: string; arguments: string }; + function_call?: { + name: string; + arguments: string; + }; } export function chatCompletionRequestMessageSerializer( item: ChatCompletionRequestMessage, -): Record { +): any { return { role: item["role"], content: item["content"], name: item["name"], - function_call: !item.functionCall - ? undefined - : { - name: item.functionCall?.["name"], - arguments: item.functionCall?.["arguments"], - }, + function_call: !item["function_call"] + ? item["function_call"] + : _chatCompletionRequestMessageFunctionCallSerializer( + item["function_call"], + ), }; } +/** model interface _ChatCompletionRequestMessageFunctionCall */ +export interface _ChatCompletionRequestMessageFunctionCall { + /** The name of the function to call. */ + name: string; + /** + * The arguments to call the function with, as generated by the model in JSON format. Note that + * the model does not always generate valid JSON, and may hallucinate parameters not defined by + * your function schema. Validate the arguments in your code before calling your function. + */ + arguments: string; +} + +export function _chatCompletionRequestMessageFunctionCallSerializer( + item: _ChatCompletionRequestMessageFunctionCall, +): any { + return { name: item["name"], arguments: item["arguments"] }; +} + +export function chatCompletionRequestMessageArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return chatCompletionRequestMessageSerializer(item); + }); +} + +/** model interface ChatCompletionFunctions */ export interface ChatCompletionFunctions { /** * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and @@ -1062,24 +1908,50 @@ export interface ChatCompletionFunctions { export function chatCompletionFunctionsSerializer( item: ChatCompletionFunctions, -): Record { +): any { return { name: item["name"], description: item["description"], - parameters: serializeRecord(item.parameters as any) as any, + parameters: chatCompletionFunctionParametersSerializer(item["parameters"]), }; } +/** model interface ChatCompletionFunctionParameters */ export interface ChatCompletionFunctionParameters extends Record {} export function chatCompletionFunctionParametersSerializer( item: ChatCompletionFunctionParameters, -): Record { - return { - ...item, - }; +): any { + return { ...item }; +} + +export function chatCompletionFunctionsArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return chatCompletionFunctionsSerializer(item); + }); } +/** Alias for _CreateChatCompletionRequestFunctionCall1 */ +export type _CreateChatCompletionRequestFunctionCall1 = + | "none" + | "auto" + | ChatCompletionFunctionCallOption; + +export function _createChatCompletionRequestFunctionCall1Serializer( + item: _CreateChatCompletionRequestFunctionCall1, +): any { + return item; +} + +export function _createChatCompletionRequestFunctionCall1Deserializer( + item: any, +): _CreateChatCompletionRequestFunctionCall1 { + return item; +} + +/** model interface ChatCompletionFunctionCallOption */ export interface ChatCompletionFunctionCallOption { /** The name of the function to call. */ name: string; @@ -1087,12 +1959,13 @@ export interface ChatCompletionFunctionCallOption { export function chatCompletionFunctionCallOptionSerializer( item: ChatCompletionFunctionCallOption, -): Record { - return { - name: item["name"], - }; +): any { + return { name: item["name"] }; } +/** Alias for Stop */ +export type Stop_1 = string | string[]; + /** Represents a chat completion response returned by model, based on the provided input. */ export interface CreateChatCompletionResponse { /** A unique identifier for the chat completion. */ @@ -1107,20 +1980,109 @@ export interface CreateChatCompletionResponse { choices: { index: number; message: ChatCompletionResponseMessage; - finishReason: "stop" | "length" | "function_call" | "content_filter"; + finish_reason: "stop" | "length" | "function_call" | "content_filter"; }[]; usage?: CompletionUsage; } +export function createChatCompletionResponseDeserializer( + item: any, +): CreateChatCompletionResponse { + return { + id: item["id"], + object: item["object"], + created: new Date(item["created"]), + model: item["model"], + choices: createChatCompletionResponseChoiceArrayDeserializer( + item["choices"], + ), + usage: !item["usage"] + ? item["usage"] + : completionUsageDeserializer(item["usage"]), + }; +} + +/** model interface _CreateChatCompletionResponseChoice */ +export interface _CreateChatCompletionResponseChoice { + /** The index of the choice in the list of choices. */ + index: number; + message: ChatCompletionResponseMessage; + /** + * The reason the model stopped generating tokens. This will be `stop` if the model hit a + * natural stop point or a provided stop sequence, `length` if the maximum number of tokens + * specified in the request was reached, `content_filter` if the content was omitted due to + * a flag from our content filters, or `function_call` if the model called a function. + */ + finish_reason: "stop" | "length" | "function_call" | "content_filter"; +} + +export function _createChatCompletionResponseChoiceDeserializer( + item: any, +): _CreateChatCompletionResponseChoice { + return { + index: item["index"], + message: chatCompletionResponseMessageDeserializer(item["message"]), + finish_reason: item["finish_reason"], + }; +} + +/** model interface ChatCompletionResponseMessage */ export interface ChatCompletionResponseMessage { /** The role of the author of this message. */ role: "system" | "user" | "assistant" | "function"; /** The contents of the message. */ content: string | null; /** The name and arguments of a function that should be called, as generated by the model. */ - functionCall?: { name: string; arguments: string }; + function_call?: { + name: string; + arguments: string; + }; } +export function chatCompletionResponseMessageDeserializer( + item: any, +): ChatCompletionResponseMessage { + return { + role: item["role"], + content: item["content"], + function_call: !item["function_call"] + ? item["function_call"] + : _chatCompletionResponseMessageFunctionCallDeserializer( + item["function_call"], + ), + }; +} + +/** model interface _ChatCompletionResponseMessageFunctionCall */ +export interface _ChatCompletionResponseMessageFunctionCall { + /** The name of the function to call. */ + name: string; + /** + * The arguments to call the function with, as generated by the model in JSON format. Note that + * the model does not always generate valid JSON, and may hallucinate parameters not defined by + * your function schema. Validate the arguments in your code before calling your function. + */ + arguments: string; +} + +export function _chatCompletionResponseMessageFunctionCallDeserializer( + item: any, +): _ChatCompletionResponseMessageFunctionCall { + return { + name: item["name"], + arguments: item["arguments"], + }; +} + +export function createChatCompletionResponseChoiceArrayDeserializer( + result: Array<_CreateChatCompletionResponseChoice>, +): any[] { + return result.map((item) => { + return _createChatCompletionResponseChoiceDeserializer(item); + }); +} + +/** model interface CreateTranslationRequest */ export interface CreateTranslationRequest { /** * The audio file object (not file name) to translate, in one of these formats: flac, mp3, mp4, @@ -1128,7 +2090,7 @@ export interface CreateTranslationRequest { */ file: Uint8Array; /** ID of the model to use. Only `whisper-1` is currently available. */ - model: string | "whisper-1"; + model: "whisper-1"; /** * An optional text to guide the model's style or continue a previous audio segment. The * [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. @@ -1138,7 +2100,7 @@ export interface CreateTranslationRequest { * The format of the transcript output, in one of these options: json, text, srt, verbose_json, or * vtt. */ - responseFormat?: "json" | "text" | "srt" | "verbose_json" | "vtt"; + response_format?: "json" | "text" | "srt" | "verbose_json" | "vtt"; /** * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more * random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, @@ -1150,20 +2112,30 @@ export interface CreateTranslationRequest { export function createTranslationRequestSerializer( item: CreateTranslationRequest, -): Record { +): any { return { file: uint8ArrayToString(item["file"], "base64"), model: item["model"], prompt: item["prompt"], - response_format: item["responseFormat"], + response_format: item["response_format"], temperature: item["temperature"], }; } +/** model interface CreateTranslationResponse */ export interface CreateTranslationResponse { text: string; } +export function createTranslationResponseDeserializer( + item: any, +): CreateTranslationResponse { + return { + text: item["text"], + }; +} + +/** model interface CreateTranscriptionRequest */ export interface CreateTranscriptionRequest { /** * The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, @@ -1171,7 +2143,7 @@ export interface CreateTranscriptionRequest { */ file: Uint8Array; /** ID of the model to use. Only `whisper-1` is currently available. */ - model: string | "whisper-1"; + model: "whisper-1"; /** * An optional text to guide the model's style or continue a previous audio segment. The * [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. @@ -1181,7 +2153,7 @@ export interface CreateTranscriptionRequest { * The format of the transcript output, in one of these options: json, text, srt, verbose_json, or * vtt. */ - responseFormat?: "json" | "text" | "srt" | "verbose_json" | "vtt"; + response_format?: "json" | "text" | "srt" | "verbose_json" | "vtt"; /** * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more * random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, @@ -1199,22 +2171,26 @@ export interface CreateTranscriptionRequest { export function createTranscriptionRequestSerializer( item: CreateTranscriptionRequest, -): Record { +): any { return { file: uint8ArrayToString(item["file"], "base64"), model: item["model"], prompt: item["prompt"], - response_format: item["responseFormat"], + response_format: item["response_format"], temperature: item["temperature"], language: item["language"], }; } +/** model interface CreateTranscriptionResponse */ export interface CreateTranscriptionResponse { text: string; } -/** Alias for Prompt */ -export type Prompt = string | string[] | number[] | number[][]; -/** Alias for Stop */ -export type Stop = string | string[]; +export function createTranscriptionResponseDeserializer( + item: any, +): CreateTranscriptionResponse { + return { + text: item["text"], + }; +} diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/openAIClient.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/openAIClient.ts index f3961703a5..1f75c622e5 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/openAIClient.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/openAIClient.ts @@ -1,7 +1,5 @@ // Licensed under the MIT License. -import { KeyCredential } from "@typespec/ts-http-runtime"; -import { Pipeline } from "@typespec/ts-http-runtime"; import { getAudioOperations, AudioOperations } from "./classic/audio/index.js"; import { getChatOperations, ChatOperations } from "./classic/chat/index.js"; import { @@ -39,6 +37,7 @@ import { OpenAIContext, OpenAIClientOptionalParams, } from "./api/index.js"; +import { Pipeline, KeyCredential } from "@typespec/ts-http-runtime"; export { OpenAIClientOptionalParams } from "./api/openAIContext.js"; diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md index fc32377c3f..2df7926cd7 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md @@ -28,9 +28,6 @@ export interface FooOperationsOperations { getAvatarAsPng: (image: Uint8Array, options?: FooOperationsGetAvatarAsPngOptionalParams) => Promise; } -// @public -export type Versions = "2022-08-30"; - // @public (undocumented) export class WidgetManagerClient { constructor(endpointParam: string, credential: KeyCredential | TokenCredential, options?: WidgetManagerClientOptionalParams); diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/fooOperations/index.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/fooOperations/index.ts index 29c0fa9e3e..861a3f759b 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/fooOperations/index.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/fooOperations/index.ts @@ -1,17 +1,17 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { WidgetManagerContext as Client } from "../index.js"; +import { + WidgetManagerContext as Client, + FooOperationsGetAvatarAsJpegOptionalParams, + FooOperationsGetAvatarAsPngOptionalParams, +} from "../index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { - FooOperationsGetAvatarAsPngOptionalParams, - FooOperationsGetAvatarAsJpegOptionalParams, -} from "../../models/options.js"; export function _getAvatarAsPngSend( context: Client, diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/index.ts index dfff21e925..d8a62d530d 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/index.ts @@ -1,6 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +export { + FooOperationsGetAvatarAsPngOptionalParams, + FooOperationsGetAvatarAsJpegOptionalParams, +} from "./options.js"; export { createWidgetManager, WidgetManagerContext, diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts index 873882612c..b15b1d9547 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential, KeyCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { KeyCredential, TokenCredential } from "@azure/core-auth"; export interface WidgetManagerContext extends Client {} diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts index 88741362b2..b321233d9b 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts @@ -9,7 +9,7 @@ import { import { FooOperationsGetAvatarAsPngOptionalParams, FooOperationsGetAvatarAsJpegOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; /** Interface representing a FooOperations operations. */ export interface FooOperationsOperations { diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/index.ts index 91c85bc651..7aa91e1688 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/index.ts @@ -1,13 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +export { WidgetManagerClient } from "./widgetManagerClient.js"; export { - WidgetManagerClient, - WidgetManagerClientOptionalParams, -} from "./widgetManagerClient.js"; -export { - Versions, FooOperationsGetAvatarAsPngOptionalParams, FooOperationsGetAvatarAsJpegOptionalParams, -} from "./models/index.js"; + WidgetManagerClientOptionalParams, +} from "./api/index.js"; export { FooOperationsOperations } from "./classic/index.js"; diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/index.ts deleted file mode 100644 index 1c2f381121..0000000000 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -export { Versions } from "./models.js"; -export { - FooOperationsGetAvatarAsPngOptionalParams, - FooOperationsGetAvatarAsJpegOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/models.ts deleted file mode 100644 index 21703793d6..0000000000 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/models.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/** The Contoso Widget Manager service version. */ -export type Versions = "2022-08-30"; diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/widgetManagerClient.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/widgetManagerClient.ts index 5fd2968625..8850f5faef 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/widgetManagerClient.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/widgetManagerClient.ts @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential, KeyCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; import { getFooOperationsOperations, FooOperationsOperations, @@ -12,6 +10,8 @@ import { WidgetManagerContext, WidgetManagerClientOptionalParams, } from "./api/index.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { KeyCredential, TokenCredential } from "@azure/core-auth"; export { WidgetManagerClientOptionalParams } from "./api/widgetManagerContext.js"; diff --git a/packages/typespec-test/test/parametrizedHost/generated/openapi/openapi.json b/packages/typespec-test/test/parametrizedHost/generated/openapi/openapi.json index 432e839a74..1816e61290 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/openapi/openapi.json +++ b/packages/typespec-test/test/parametrizedHost/generated/openapi/openapi.json @@ -13,7 +13,7 @@ "https" ], "x-ms-parameterized-host": { - "hostTemplate": "{host}.{subdomain}.{sufix}.com/{apiVersion}", + "hostTemplate": "{host}.{subdomain}.{sufix}.com", "useSchemePrefix": false, "parameters": [ { @@ -36,13 +36,6 @@ "required": false, "type": "string", "default": "three" - }, - { - "name": "apiVersion", - "in": "path", - "required": false, - "type": "string", - "default": "v1" } ] }, diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/review/parametrized-host.api.md b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/review/parametrized-host.api.md index af2b435a49..337ef7b89e 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/review/parametrized-host.api.md +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/review/parametrized-host.api.md @@ -21,20 +21,18 @@ export interface ConfidentialLedgerListCollectionsOptionalParams extends Operati // @public export interface ConfidentialLedgerOperations { - listCollections: (apiVersion: string, options?: ConfidentialLedgerListCollectionsOptionalParams) => Promise; + listCollections: (options?: ConfidentialLedgerListCollectionsOptionalParams) => Promise; } // @public (undocumented) export class ParametrizedHostClient { - constructor(credential: TokenCredential, options?: ParametrizedHostClientOptionalParams); + constructor(credential: TokenCredential, apiVersion: string, options?: ParametrizedHostClientOptionalParams); readonly confidentialLedger: ConfidentialLedgerOperations; readonly pipeline: Pipeline; } // @public export interface ParametrizedHostClientOptionalParams extends ClientOptions { - // (undocumented) - apiVersion?: string; // (undocumented) host?: string; // (undocumented) diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/confidentialLedger/index.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/confidentialLedger/index.ts index a7bb191385..01c4c89c3f 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/confidentialLedger/index.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/confidentialLedger/index.ts @@ -1,29 +1,30 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { Collection } from "../../models/models.js"; -import { ParametrizedHostContext as Client } from "../index.js"; +import { + ParametrizedHostContext as Client, + ConfidentialLedgerListCollectionsOptionalParams, +} from "../index.js"; +import { + Collection, + collectionArrayDeserializer, +} from "../../models/models.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { ConfidentialLedgerListCollectionsOptionalParams } from "../../models/options.js"; export function _listCollectionsSend( context: Client, - apiVersion: string, options: ConfidentialLedgerListCollectionsOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context .path("/app/collections") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { "api-version": apiVersion }, - }); + .get({ ...operationOptionsToRequestParameters(options) }); } export async function _listCollectionsDeserialize( @@ -34,21 +35,16 @@ export async function _listCollectionsDeserialize( throw createRestError(result); } - return result.body === undefined - ? result.body - : result.body.map((p: any) => { - return { collectionId: p["collectionId"] }; - }); + return collectionArrayDeserializer(result.body); } /** Collection ids are user-created collections of ledger entries */ export async function listCollections( context: Client, - apiVersion: string, options: ConfidentialLedgerListCollectionsOptionalParams = { requestOptions: {}, }, ): Promise { - const result = await _listCollectionsSend(context, apiVersion, options); + const result = await _listCollectionsSend(context, options); return _listCollectionsDeserialize(result); } diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/index.ts index a3a570b0b3..12db15b8a7 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/index.ts @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +export { ConfidentialLedgerListCollectionsOptionalParams } from "./options.js"; export { createParametrizedHost, ParametrizedHostContext, diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts index c94d81fbaa..be98d72f79 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { TokenCredential } from "@azure/core-auth"; export interface ParametrizedHostContext extends Client {} @@ -12,21 +12,18 @@ export interface ParametrizedHostClientOptionalParams extends ClientOptions { host?: string; subdomain?: string; sufix?: string; - apiVersion?: string; } export function createParametrizedHost( credential: TokenCredential, + apiVersion: string, options: ParametrizedHostClientOptionalParams = {}, ): ParametrizedHostContext { const host = options.host ?? "one"; const subdomain = options.subdomain ?? "two"; const sufix = options.sufix ?? "three"; - const apiVersion = options.apiVersion ?? "v1"; const endpointUrl = - options.endpoint ?? - options.baseUrl ?? - `${host}.${subdomain}.${sufix}.com/${apiVersion}`; + options.endpoint ?? options.baseUrl ?? `${host}.${subdomain}.${sufix}.com`; const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions @@ -44,5 +41,20 @@ export function createParametrizedHost( }; const clientContext = getClient(endpointUrl, credential, updatedOptions); clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + clientContext.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")) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); return clientContext; } diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/classic/confidentialLedger/index.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/classic/confidentialLedger/index.ts index d009634f41..62eb41260d 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/classic/confidentialLedger/index.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/classic/confidentialLedger/index.ts @@ -2,15 +2,14 @@ // Licensed under the MIT License. import { ParametrizedHostContext } from "../../api/parametrizedHostContext.js"; -import { Collection } from "../../models/models.js"; import { listCollections } from "../../api/confidentialLedger/index.js"; -import { ConfidentialLedgerListCollectionsOptionalParams } from "../../models/options.js"; +import { ConfidentialLedgerListCollectionsOptionalParams } from "../../api/options.js"; +import { Collection } from "../../models/models.js"; /** Interface representing a ConfidentialLedger operations. */ export interface ConfidentialLedgerOperations { /** Collection ids are user-created collections of ledger entries */ listCollections: ( - apiVersion: string, options?: ConfidentialLedgerListCollectionsOptionalParams, ) => Promise; } @@ -18,9 +17,8 @@ export interface ConfidentialLedgerOperations { export function getConfidentialLedger(context: ParametrizedHostContext) { return { listCollections: ( - apiVersion: string, options?: ConfidentialLedgerListCollectionsOptionalParams, - ) => listCollections(context, apiVersion, options), + ) => listCollections(context, options), }; } diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/index.ts index 6fe3c052a1..d71806cc04 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/index.ts @@ -1,12 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +export { ParametrizedHostClient } from "./parametrizedHostClient.js"; +export { Collection } from "./models/index.js"; export { - ParametrizedHostClient, - ParametrizedHostClientOptionalParams, -} from "./parametrizedHostClient.js"; -export { - Collection, ConfidentialLedgerListCollectionsOptionalParams, -} from "./models/index.js"; + ParametrizedHostClientOptionalParams, +} from "./api/index.js"; export { ConfidentialLedgerOperations } from "./classic/index.js"; diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/index.ts index 33912dfd9f..b63230b6f6 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/index.ts @@ -2,4 +2,3 @@ // Licensed under the MIT License. export { Collection } from "./models.js"; -export { ConfidentialLedgerListCollectionsOptionalParams } from "./options.js"; diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/models.ts index c9cad20143..0e9f57ab75 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/models.ts @@ -5,3 +5,15 @@ export interface Collection { readonly collectionId: string; } + +export function collectionDeserializer(item: any): Collection { + return { + collectionId: item["collectionId"], + }; +} + +export function collectionArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return collectionDeserializer(item); + }); +} diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/parametrizedHostClient.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/parametrizedHostClient.ts index c9e80d97b1..5fef72c1c6 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/parametrizedHostClient.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/parametrizedHostClient.ts @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; import { getConfidentialLedgerOperations, ConfidentialLedgerOperations, @@ -12,6 +10,8 @@ import { ParametrizedHostContext, ParametrizedHostClientOptionalParams, } from "./api/index.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TokenCredential } from "@azure/core-auth"; export { ParametrizedHostClientOptionalParams } from "./api/parametrizedHostContext.js"; @@ -22,13 +22,14 @@ export class ParametrizedHostClient { constructor( credential: TokenCredential, + apiVersion: string, options: ParametrizedHostClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-client` : "azsdk-js-client"; - this._client = createParametrizedHost(credential, { + this._client = createParametrizedHost(credential, apiVersion, { ...options, userAgentOptions: { userAgentPrefix }, }); diff --git a/packages/typespec-test/test/parametrizedHost/spec/main.tsp b/packages/typespec-test/test/parametrizedHost/spec/main.tsp index a24dad9c5b..df5b1686fb 100644 --- a/packages/typespec-test/test/parametrizedHost/spec/main.tsp +++ b/packages/typespec-test/test/parametrizedHost/spec/main.tsp @@ -14,11 +14,13 @@ using OpenAPI; // ** Service description ** // +// TODO: remove version in server temporary https://github.com/Azure/typespec-azure/issues/1608 + @service({title: "ParametrizedHost"}) @useAuth(OAuth2Auth<[MyFlow]>) @useDependency(Azure.Core.Versions.v1_0_Preview_1) @server( - "{host}.{subdomain}.{sufix}.com/{apiVersion}", + "{host}.{subdomain}.{sufix}.com", "Confidential Ledger Service", { @path @@ -26,9 +28,7 @@ using OpenAPI; @path subdomain?: string = "two", @path - sufix?: string = "three", - @path - apiVersion?: string = "v1" + sufix?: string = "three" } ) namespace Azure.Test.ParametrizedHost; diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md index 2b9511436b..541e6cf475 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md @@ -106,9 +106,6 @@ export interface SchemaVersion { readonly schemaVersion: number; } -// @public -export type ServiceApiVersions = "2021-10" | "2022-10" | "2023-07-01"; - // (No @packageDocumentation comment for this package) ``` diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/index.ts index ffc1d81489..40c815f457 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/index.ts @@ -1,6 +1,14 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +export { + SchemaOperationsListSchemaGroupsOptionalParams, + SchemaOperationsGetSchemaByIdOptionalParams, + SchemaOperationsListSchemaVersionsOptionalParams, + SchemaOperationsGetSchemaByVersionOptionalParams, + SchemaOperationsGetSchemaIdByContentOptionalParams, + SchemaOperationsRegisterSchemaOptionalParams, +} from "./options.js"; export { createSchemaRegistry, SchemaRegistryContext, diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts index c94be00488..ab083567a0 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts @@ -1,33 +1,35 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + SchemaRegistryContext as Client, + SchemaOperationsGetSchemaByIdOptionalParams, + SchemaOperationsGetSchemaByVersionOptionalParams, + SchemaOperationsGetSchemaIdByContentOptionalParams, + SchemaOperationsListSchemaGroupsOptionalParams, + SchemaOperationsListSchemaVersionsOptionalParams, + SchemaOperationsRegisterSchemaOptionalParams, +} from "../index.js"; import { SchemaGroup, - SchemaContentTypeValues, SchemaVersion, + SchemaContentTypeValues, _PagedSchemaGroup, + _pagedSchemaGroupDeserializer, _PagedVersion, + _pagedVersionDeserializer, } from "../../models/models.js"; -import { SchemaRegistryContext as Client } from "../index.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../../static-helpers/pagingHelpers.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { - PagedAsyncIterableIterator, - buildPagedAsyncIterator, -} from "../../static-helpers/pagingHelpers.js"; import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; -import { - SchemaOperationsListSchemaGroupsOptionalParams, - SchemaOperationsGetSchemaByIdOptionalParams, - SchemaOperationsListSchemaVersionsOptionalParams, - SchemaOperationsGetSchemaByVersionOptionalParams, - SchemaOperationsGetSchemaIdByContentOptionalParams, - SchemaOperationsRegisterSchemaOptionalParams, -} from "../../models/options.js"; export function _listSchemaGroupsSend( context: Client, @@ -48,12 +50,7 @@ export async function _listSchemaGroupsDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { groupName: p["groupName"] }; - }), - nextLink: result.body["nextLink"], - }; + return _pagedSchemaGroupDeserializer(result.body); } /** Gets the list of schema groups user is authorized to access. */ @@ -126,12 +123,7 @@ export async function _listSchemaVersionsDeserialize( throw createRestError(result); } - return { - value: result.body["value"].map((p: any) => { - return { schemaVersion: p["schemaVersion"] }; - }), - nextLink: result.body["nextLink"], - }; + return _pagedVersionDeserializer(result.body); } /** Gets the list of all versions of one schema. */ diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts index fc8dd8cd69..0bde86c933 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { TokenCredential } from "@azure/core-auth"; +/** SchemaRegistryClient is a client for registering and retrieving schemas from the Azure Schema Registry service. */ export interface SchemaRegistryContext extends Client {} /** Optional parameters for the client. */ diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts index d33b5a81cd..75322c6473 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts @@ -2,11 +2,6 @@ // Licensed under the MIT License. import { SchemaRegistryContext } from "../../api/schemaRegistryContext.js"; -import { - SchemaGroup, - SchemaContentTypeValues, - SchemaVersion, -} from "../../models/models.js"; import { listSchemaGroups, getSchemaById, @@ -15,6 +10,11 @@ import { getSchemaIdByContent, registerSchema, } from "../../api/schemaOperations/index.js"; +import { + SchemaGroup, + SchemaVersion, + SchemaContentTypeValues, +} from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; import { SchemaOperationsListSchemaGroupsOptionalParams, @@ -23,7 +23,7 @@ import { SchemaOperationsGetSchemaByVersionOptionalParams, SchemaOperationsGetSchemaIdByContentOptionalParams, SchemaOperationsRegisterSchemaOptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; /** Interface representing a SchemaOperations operations. */ export interface SchemaOperationsOperations { diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts index a8e9b5c7d7..d1ffb2f64c 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts @@ -7,25 +7,24 @@ import { PagedAsyncIterableIterator, } from "./static-helpers/pagingHelpers.js"; -export { - SchemaRegistryClient, - SchemaRegistryClientOptionalParams, -} from "./schemaRegistryClient.js"; +export { SchemaRegistryClient } from "./schemaRegistryClient.js"; export { SchemaGroup, - SchemaContentTypeValues, SchemaVersion, - ServiceApiVersions, SchemaProperties, SchemaFormat, Schema, + SchemaContentTypeValues, ContentTypeEnum, +} from "./models/index.js"; +export { SchemaOperationsListSchemaGroupsOptionalParams, SchemaOperationsGetSchemaByIdOptionalParams, SchemaOperationsListSchemaVersionsOptionalParams, SchemaOperationsGetSchemaByVersionOptionalParams, SchemaOperationsGetSchemaIdByContentOptionalParams, SchemaOperationsRegisterSchemaOptionalParams, -} from "./models/index.js"; + SchemaRegistryClientOptionalParams, +} from "./api/index.js"; export { SchemaOperationsOperations } from "./classic/index.js"; export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/index.ts index 4a30b89dbd..5a0586c5ee 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/index.ts @@ -3,19 +3,10 @@ export { SchemaGroup, - SchemaContentTypeValues, SchemaVersion, - ServiceApiVersions, SchemaProperties, SchemaFormat, Schema, + SchemaContentTypeValues, ContentTypeEnum, } from "./models.js"; -export { - SchemaOperationsListSchemaGroupsOptionalParams, - SchemaOperationsGetSchemaByIdOptionalParams, - SchemaOperationsListSchemaVersionsOptionalParams, - SchemaOperationsGetSchemaByVersionOptionalParams, - SchemaOperationsGetSchemaIdByContentOptionalParams, - SchemaOperationsRegisterSchemaOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/models.ts index 05d8592226..b0758539ee 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/models.ts @@ -7,12 +7,11 @@ export interface SchemaGroup { readonly groupName: string; } -/** Type of SchemaContentTypeValues */ -export type SchemaContentTypeValues = - | "application/json; serialization=Avro" - | "application/json; serialization=json" - | "text/plain; charset=utf-8" - | "text/vnd.ms.protobuf"; +export function schemaGroupDeserializer(item: any): SchemaGroup { + return { + groupName: item["groupName"], + }; +} /** Schema versions resource. */ export interface SchemaVersion { @@ -20,8 +19,11 @@ export interface SchemaVersion { readonly schemaVersion: number; } -/** Represents the Schema Registry API version to use for requests. */ -export type ServiceApiVersions = "2021-10" | "2022-10" | "2023-07-01"; +export function schemaVersionDeserializer(item: any): SchemaVersion { + return { + schemaVersion: item["schemaVersion"], + }; +} /** Meta properties of a schema. */ export interface SchemaProperties { @@ -37,9 +39,17 @@ export interface SchemaProperties { version: number; } -export function schemaPropertiesSerializer( - item: SchemaProperties, -): Record { +export function schemaPropertiesSerializer(item: SchemaProperties): any { + return { + id: item["id"], + format: item["format"], + groupName: item["groupName"], + name: item["name"], + version: item["version"], + }; +} + +export function schemaPropertiesDeserializer(item: any): SchemaProperties { return { id: item["id"], format: item["format"], @@ -60,13 +70,26 @@ export interface Schema { properties: SchemaProperties; } -export function schemaSerializer(item: Schema): Record { +export function schemaSerializer(item: Schema): any { return { definition: item["definition"], - properties: schemaPropertiesSerializer(item.properties), + properties: schemaPropertiesSerializer(item["properties"]), }; } +export function schemaDeserializer(item: any): Schema { + return { + definition: item["definition"], + properties: schemaPropertiesDeserializer(item["properties"]), + }; +} + +/** Type of SchemaContentTypeValues */ +export type SchemaContentTypeValues = + | "application/json; serialization=Avro" + | "application/json; serialization=json" + | "text/plain; charset=utf-8" + | "text/vnd.ms.protobuf"; /** The content type for the schema. */ export type ContentTypeEnum = | "application/octet-stream" @@ -82,6 +105,21 @@ export interface _PagedSchemaGroup { nextLink?: string; } +export function _pagedSchemaGroupDeserializer(item: any): _PagedSchemaGroup { + return { + value: schemaGroupArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function schemaGroupArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return schemaGroupDeserializer(item); + }); +} + /** Paged collection of Version items */ export interface _PagedVersion { /** The Version items on this page */ @@ -89,3 +127,18 @@ export interface _PagedVersion { /** The link to the next page of items */ nextLink?: string; } + +export function _pagedVersionDeserializer(item: any): _PagedVersion { + return { + value: schemaVersionArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function schemaVersionArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return schemaVersionDeserializer(item); + }); +} diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/schemaRegistryClient.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/schemaRegistryClient.ts index 04bc7e9e5f..16e187354a 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/schemaRegistryClient.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/schemaRegistryClient.ts @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { TokenCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; import { getSchemaOperationsOperations, SchemaOperationsOperations, @@ -12,6 +10,8 @@ import { SchemaRegistryContext, SchemaRegistryClientOptionalParams, } from "./api/index.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TokenCredential } from "@azure/core-auth"; export { SchemaRegistryClientOptionalParams } from "./api/schemaRegistryContext.js"; diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/browser.json b/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/browser.json deleted file mode 100644 index 144e29682d..0000000000 --- a/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/browser.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "./build.json", - "include": [ - "../src/**/*.ts", - "../src/**/*.mts", - "../src/**/*.tsx", - "../src/**/*.json" - ], - "exclude": [ - "../src/package.json" - ], - "compilerOptions": { - "outDir": "../.tshy-build/browser" - } -} diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/build.json b/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/build.json deleted file mode 100644 index aea1a9e93b..0000000000 --- a/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/build.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "rootDir": "../src", - "module": "nodenext", - "moduleResolution": "nodenext" - } -} diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/commonjs.json b/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/commonjs.json deleted file mode 100644 index 7c9db50b6a..0000000000 --- a/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/commonjs.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "./build.json", - "include": [ - "../src/**/*.ts", - "../src/**/*.cts", - "../src/**/*.tsx", - "../src/**/*.json" - ], - "exclude": [ - "../src/**/*.mts", - "../src/package.json" - ], - "compilerOptions": { - "outDir": "../.tshy-build/commonjs" - } -} diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/esm.json b/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/esm.json deleted file mode 100644 index 959294a842..0000000000 --- a/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/esm.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "./build.json", - "include": [ - "../src/**/*.ts", - "../src/**/*.mts", - "../src/**/*.tsx", - "../src/**/*.json" - ], - "exclude": [ - "../src/package.json" - ], - "compilerOptions": { - "outDir": "../.tshy-build/esm" - } -} diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/react-native.json b/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/react-native.json deleted file mode 100644 index e3a9d50023..0000000000 --- a/packages/typespec-test/test/spread/generated/typespec-ts/.tshy/react-native.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "./build.json", - "include": [ - "../src/**/*.ts", - "../src/**/*.mts", - "../src/**/*.tsx", - "../src/**/*.json" - ], - "exclude": [ - "../src/package.json" - ], - "compilerOptions": { - "outDir": "../.tshy-build/react-native" - } -} diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/review/spread.api.md b/packages/typespec-test/test/spread/generated/typespec-ts/review/spread.api.md index d826076837..66f83346f7 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/review/spread.api.md +++ b/packages/typespec-test/test/spread/generated/typespec-ts/review/spread.api.md @@ -19,7 +19,9 @@ export interface AOperations { prop: string; }, options?: ATest3OptionalParams) => Promise; // (undocumented) - test4: (body: Test, options?: ATest4OptionalParams) => Promise; + test4: (body: { + prop: string; + }, options?: ATest4OptionalParams) => Promise; } // @public @@ -40,7 +42,7 @@ export interface ATest4OptionalParams extends OperationOptions { // @public (undocumented) export class DemoServiceClient { - constructor(endpoint: string, options?: DemoServiceClientOptionalParams); + constructor(endpointParam: string, options?: DemoServiceClientOptionalParams); readonly a: AOperations; readonly pipeline: Pipeline; } @@ -49,12 +51,6 @@ export class DemoServiceClient { export interface DemoServiceClientOptionalParams extends ClientOptions { } -// @public (undocumented) -export interface Test { - // (undocumented) - prop: string; -} - // (No @packageDocumentation comment for this package) ``` diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/a/index.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/a/index.ts index 9930d694a1..cbf066f16a 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/a/index.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/a/index.ts @@ -1,20 +1,23 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { Test } from "../../models/models.js"; -import { DemoServiceContext as Client } from "../index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; import { ATest1OptionalParams, ATest2OptionalParams, ATest3OptionalParams, ATest4OptionalParams, -} from "../../models/options.js"; + DemoServiceContext as Client, +} from "../index.js"; +import { + _test3RequestSerializer, + _test4RequestSerializer, +} from "../../models/models.js"; +import { + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; export function _test1Send( context: Client, @@ -95,7 +98,7 @@ export function _test3Send( .path("/test3") .post({ ...operationOptionsToRequestParameters(options), - body: { prop: body["prop"] }, + body: _test3RequestSerializer(body), }); } @@ -121,14 +124,14 @@ export async function test3( export function _test4Send( context: Client, - body: Test, + body: { prop: string }, options: ATest4OptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/test4") .post({ ...operationOptionsToRequestParameters(options), - body: { prop: body["prop"] }, + body: _test4RequestSerializer(body), }); } @@ -145,7 +148,7 @@ export async function _test4Deserialize( export async function test4( context: Client, - body: Test, + body: { prop: string }, options: ATest4OptionalParams = { requestOptions: {} }, ): Promise { const result = await _test4Send(context, body, options); diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/demoServiceContext.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/demoServiceContext.ts index d5fc4175fa..8c0ee568df 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/demoServiceContext.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/demoServiceContext.ts @@ -1,8 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; export interface DemoServiceContext extends Client {} @@ -10,7 +10,7 @@ export interface DemoServiceContext extends Client {} export interface DemoServiceClientOptionalParams extends ClientOptions {} export function createDemoService( - endpoint: string, + endpointParam: string, options: DemoServiceClientOptionalParams = {}, ): DemoServiceContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; @@ -23,7 +23,7 @@ export function createDemoService( loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, }; const clientContext = getClient( - options.endpoint ?? options.baseUrl ?? endpoint, + options.endpoint ?? options.baseUrl ?? String(endpointParam), undefined, updatedOptions, ); diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/index.ts index cf708aa052..a17e02a052 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/index.ts @@ -6,3 +6,9 @@ export { DemoServiceContext, DemoServiceClientOptionalParams, } from "./demoServiceContext.js"; +export { + ATest1OptionalParams, + ATest2OptionalParams, + ATest3OptionalParams, + ATest4OptionalParams, +} from "./options.js"; diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/options.ts similarity index 100% rename from packages/typespec-test/test/spread/generated/typespec-ts/src/models/options.ts rename to packages/typespec-test/test/spread/generated/typespec-ts/src/api/options.ts diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/classic/a/index.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/classic/a/index.ts index 6f24c077ba..9662267fb7 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/classic/a/index.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/classic/a/index.ts @@ -2,14 +2,13 @@ // Licensed under the MIT License. import { DemoServiceContext } from "../../api/demoServiceContext.js"; -import { Test } from "../../models/models.js"; import { test1, test2, test3, test4 } from "../../api/a/index.js"; import { ATest1OptionalParams, ATest2OptionalParams, ATest3OptionalParams, ATest4OptionalParams, -} from "../../models/options.js"; +} from "../../api/options.js"; /** Interface representing a A operations. */ export interface AOperations { @@ -24,7 +23,10 @@ export interface AOperations { body: { prop: string }, options?: ATest3OptionalParams, ) => Promise; - test4: (body: Test, options?: ATest4OptionalParams) => Promise; + test4: ( + body: { prop: string }, + options?: ATest4OptionalParams, + ) => Promise; } export function getA(context: DemoServiceContext) { @@ -35,7 +37,7 @@ export function getA(context: DemoServiceContext) { test2(context, prop, options), test3: (body: { prop: string }, options?: ATest3OptionalParams) => test3(context, body, options), - test4: (body: Test, options?: ATest4OptionalParams) => + test4: (body: { prop: string }, options?: ATest4OptionalParams) => test4(context, body, options), }; } diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/demoServiceClient.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/demoServiceClient.ts index 47c2715022..1763c417ab 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/demoServiceClient.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/demoServiceClient.ts @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { Pipeline } from "@azure/core-rest-pipeline"; import { getAOperations, AOperations } from "./classic/a/index.js"; import { createDemoService, DemoServiceContext, DemoServiceClientOptionalParams, } from "./api/index.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; export { DemoServiceClientOptionalParams } from "./api/demoServiceContext.js"; @@ -16,12 +16,15 @@ export class DemoServiceClient { /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; - constructor(endpoint: string, options: DemoServiceClientOptionalParams = {}) { + constructor( + endpointParam: string, + options: DemoServiceClientOptionalParams = {}, + ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-client` : "azsdk-js-client"; - this._client = createDemoService(endpoint, { + this._client = createDemoService(endpointParam, { ...options, userAgentOptions: { userAgentPrefix }, }); diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/index.ts index 45194fc61c..c2ef03828c 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/index.ts @@ -1,15 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +export { DemoServiceClient } from "./demoServiceClient.js"; export { - DemoServiceClient, DemoServiceClientOptionalParams, -} from "./demoServiceClient.js"; -export { - Test, ATest1OptionalParams, ATest2OptionalParams, ATest3OptionalParams, ATest4OptionalParams, -} from "./models/index.js"; +} from "./api/index.js"; export { AOperations } from "./classic/index.js"; diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/models/index.ts index 1ec3b26a46..fc36ab244f 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/models/index.ts @@ -1,10 +1,2 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. - -export { Test } from "./models.js"; -export { - ATest1OptionalParams, - ATest2OptionalParams, - ATest3OptionalParams, - ATest4OptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/models/models.ts index 82562d39e4..1ddfd2ebd8 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/models/models.ts @@ -1,6 +1,20 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -export interface Test { +/** model interface _Test3Request */ +export interface _Test3Request { prop: string; } + +export function _test3RequestSerializer(item: _Test3Request): any { + return { prop: item["prop"] }; +} + +/** model interface _Test4Request */ +export interface _Test4Request { + prop: string; +} + +export function _test4RequestSerializer(item: _Test4Request): any { + return { prop: item["prop"] }; +} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md index c99761931f..b42a93499b 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md @@ -13,7 +13,7 @@ import { PathUncheckedResponse } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; import { PollerLike } from '@azure/core-lro'; -// @public (undocumented) +// @public export interface AnalyzeResult { // (undocumented) summary: string; @@ -35,13 +35,7 @@ export type ContinuablePage = TPage & { continuationToken?: string; }; -// @public (undocumented) -export interface CreateWidget { - color: "red" | "blue"; - weight: number; -} - -// @public (undocumented) +// @public export interface NonReferencedModel { prop1: number; prop2: string; @@ -69,12 +63,6 @@ export interface RestorePollerOptions uint8ArrayToString(p, "base64url")), - ), - "utc-date-header": utcDateHeader.toUTCString(), - ...(options?.optionalDateHeader !== undefined - ? { - "optional-date-header": - options?.optionalDateHeader?.toUTCString(), - } - : {}), - ...(options?.nullableDateHeader !== undefined && - options?.nullableDateHeader !== null - ? { - "nullable-date-header": - options?.nullableDateHeader?.toUTCString(), - } - : {}), - }, - }); + return context.path("/widgets").get({ + ...operationOptionsToRequestParameters(options), + headers: { + "required-header": requiredHeader, + ...(options?.optionalHeader !== undefined + ? { "optional-header": options?.optionalHeader } + : {}), + ...(options?.nullableOptionalHeader !== undefined && + options?.nullableOptionalHeader !== null + ? { "nullable-optional-header": options?.nullableOptionalHeader } + : {}), + "bytes-header": uint8ArrayToString(bytesHeader, "base64"), + value: uint8ArrayToString(value, "base64"), + "csv-array-header": buildCsvCollection( + csvArrayHeader.map((p: any) => { + return uint8ArrayToString(p, "base64url"); + }), + ), + "utc-date-header": utcDateHeader.toUTCString(), + ...(options?.optionalDateHeader !== undefined + ? { + "optional-date-header": !options?.optionalDateHeader + ? options?.optionalDateHeader + : options?.optionalDateHeader.toUTCString(), + } + : {}), + ...(options?.nullableDateHeader !== undefined && + options?.nullableDateHeader !== null + ? { + "nullable-date-header": !options?.nullableDateHeader + ? options?.nullableDateHeader + : options?.nullableDateHeader.toUTCString(), + } + : {}), + }, + }); } export async function _listWidgetsDeserialize( @@ -87,11 +95,7 @@ export async function _listWidgetsDeserialize( throw createRestError(result); } - return result.body === undefined - ? result.body - : result.body.map((p: any) => { - return { id: p["id"], weight: p["weight"], color: p["color"] }; - }); + return widgetArrayDeserializer(result.body); } /** @@ -142,12 +146,7 @@ export async function _listWidgetsPagesDeserialize( throw createRestError(result); } - return { - results: result.body["results"].map((p: any) => { - return { id: p["id"], weight: p["weight"], color: p["color"] }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _listWidgetsPagesResultsDeserializer(result.body); } export function listWidgetsPages( @@ -187,12 +186,7 @@ export async function _queryWidgetsPagesDeserialize( throw createRestError(result); } - return { - results: result.body["results"].map((p: any) => { - return { id: p["id"], weight: p["weight"], color: p["color"] }; - }), - "odata.nextLink": result.body["odata.nextLink"], - }; + return _listWidgetsPagesResultsDeserializer(result.body); } export function queryWidgetsPages( @@ -228,11 +222,7 @@ export async function _getWidgetDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - weight: result.body["weight"], - color: result.body["color"], - }; + return widgetDeserializer(result.body); } /** Get a widget by ID. */ @@ -267,11 +257,7 @@ export async function _createWidgetDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - weight: result.body["weight"], - color: result.body["color"], - }; + return widgetDeserializer(result.body); } /** @@ -301,7 +287,7 @@ export function _createOrReplaceSend( .put({ ...operationOptionsToRequestParameters(options), queryParameters: { "api-version": options?.apiVersion ?? "1.0.0" }, - body: { role: resource["role"], id: resource["id"] }, + body: userSerializer(resource), }); } @@ -313,11 +299,7 @@ export async function _createOrReplaceDeserialize( throw createRestError(result); } - return { - name: result.body["name"], - role: result.body["role"], - id: result.body["id"], - }; + return userDeserializer(result.body); } /** Long-running resource create or replace operation template. */ @@ -362,11 +344,7 @@ export async function _updateWidgetDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - weight: result.body["weight"], - color: result.body["color"], - }; + return widgetDeserializer(result.body); } /** @@ -431,9 +409,7 @@ export async function _analyzeWidgetDeserialize( throw createRestError(result); } - return { - summary: result.body["summary"], - }; + return analyzeResultDeserializer(result.body); } /** Analyze a widget. The only guarantee is that this method will return a string containing the results of the analysis. */ diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts index f3da533c4e..4080ee166e 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts @@ -2,10 +2,10 @@ // Licensed under the MIT License. import { WidgetServiceContext } from "../../api/widgetServiceContext.js"; -import { User } from "../../models/models.js"; import { createOrReplace } from "../../api/budgets/index.js"; +import { User } from "../../models/models.js"; import { PollerLike, OperationState } from "@azure/core-lro"; -import { BudgetsCreateOrReplaceOptionalParams } from "../../models/options.js"; +import { BudgetsCreateOrReplaceOptionalParams } from "../../api/options.js"; /** Interface representing a Budgets operations. */ export interface BudgetsOperations { diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts index e90126492c..2279c56f25 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts @@ -1,8 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +import { + WidgetsListWidgetsOptionalParams, + WidgetsListWidgetsPagesOptionalParams, + WidgetsQueryWidgetsPagesOptionalParams, + WidgetsGetWidgetOptionalParams, + WidgetsCreateWidgetOptionalParams, + WidgetsCreateOrReplaceOptionalParams, + WidgetsUpdateWidgetOptionalParams, + WidgetsDeleteWidgetOptionalParams, + WidgetsAnalyzeWidgetOptionalParams, +} from "../../api/options.js"; import { WidgetServiceContext } from "../../api/widgetServiceContext.js"; -import { User, Widget, AnalyzeResult } from "../../models/models.js"; import { listWidgets, listWidgetsPages, @@ -14,19 +24,9 @@ import { deleteWidget, analyzeWidget, } from "../../api/widgets/index.js"; +import { User, Widget, AnalyzeResult } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; import { PollerLike, OperationState } from "@azure/core-lro"; -import { - WidgetsListWidgetsOptionalParams, - WidgetsListWidgetsPagesOptionalParams, - WidgetsQueryWidgetsPagesOptionalParams, - WidgetsGetWidgetOptionalParams, - WidgetsCreateWidgetOptionalParams, - WidgetsCreateOrReplaceOptionalParams, - WidgetsUpdateWidgetOptionalParams, - WidgetsDeleteWidgetOptionalParams, - WidgetsAnalyzeWidgetOptionalParams, -} from "../../models/options.js"; /** Interface representing a Widgets operations. */ export interface WidgetsOperations { diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts index 4c8f896aba..d90505664c 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts @@ -7,20 +7,16 @@ import { PagedAsyncIterableIterator, } from "./static-helpers/pagingHelpers.js"; -export { - WidgetServiceClient, - WidgetServiceClientOptionalParams, -} from "./widgetServiceClient.js"; +export { WidgetServiceClient } from "./widgetServiceClient.js"; export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js"; export { User, Widget, WidgetError, - CreateWidget, - UpdateWidget, AnalyzeResult, - Versions, NonReferencedModel, +} from "./models/index.js"; +export { WidgetsListWidgetsOptionalParams, WidgetsListWidgetsPagesOptionalParams, WidgetsQueryWidgetsPagesOptionalParams, @@ -31,6 +27,7 @@ export { WidgetsDeleteWidgetOptionalParams, WidgetsAnalyzeWidgetOptionalParams, BudgetsCreateOrReplaceOptionalParams, -} from "./models/index.js"; + WidgetServiceClientOptionalParams, +} from "./api/index.js"; export { BudgetsOperations, WidgetsOperations } from "./classic/index.js"; export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts index b90dc93b50..4538834321 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts @@ -5,21 +5,6 @@ export { User, Widget, WidgetError, - CreateWidget, - UpdateWidget, AnalyzeResult, - Versions, NonReferencedModel, } from "./models.js"; -export { - WidgetsListWidgetsOptionalParams, - WidgetsListWidgetsPagesOptionalParams, - WidgetsQueryWidgetsPagesOptionalParams, - WidgetsGetWidgetOptionalParams, - WidgetsCreateWidgetOptionalParams, - WidgetsCreateOrReplaceOptionalParams, - WidgetsUpdateWidgetOptionalParams, - WidgetsDeleteWidgetOptionalParams, - WidgetsAnalyzeWidgetOptionalParams, - BudgetsCreateOrReplaceOptionalParams, -} from "./options.js"; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts index e31929aa92..34a06d5521 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts @@ -11,13 +11,19 @@ export interface User { id: string; } -export function userSerializer(item: User): Record { +export function userSerializer(item: User): any { + return { role: item["role"], id: item["id"] }; +} + +export function userDeserializer(item: any): User { return { + name: item["name"], role: item["role"], id: item["id"], }; } +/** model interface Widget */ export interface Widget { /** The UUID of this widget. This is generated automatically by the service. */ id: string; @@ -27,6 +33,15 @@ export interface Widget { color: "red" | "blue"; } +export function widgetDeserializer(item: any): Widget { + return { + id: item["id"], + weight: item["weight"], + color: item["color"], + }; +} + +/** model interface WidgetError */ export interface WidgetError { /** The HTTP error code. */ code: number; @@ -34,6 +49,14 @@ export interface WidgetError { message: string; } +export function widgetErrorDeserializer(item: any): WidgetError { + return { + code: item["code"], + message: item["message"], + }; +} + +/** model interface _ListWidgetsPagesResults */ export interface _ListWidgetsPagesResults { /** The current page of results. */ results: Widget[]; @@ -41,27 +64,33 @@ export interface _ListWidgetsPagesResults { "odata.nextLink"?: string; } -export interface CreateWidget { - /** The weight of the widget. This is an int32, but must be greater than zero. */ - weight: number; - /** The color of the widget. */ - color: "red" | "blue"; +export function _listWidgetsPagesResultsDeserializer( + item: any, +): _ListWidgetsPagesResults { + return { + results: widgetArrayDeserializer(item["results"]), + "odata.nextLink": item["odata.nextLink"], + }; } -export interface UpdateWidget { - /** The weight of the widget. This is an int32, but must be greater than zero. */ - weight?: number; - /** The color of the widget. */ - color?: "red" | "blue"; +export function widgetArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return widgetDeserializer(item); + }); } +/** model interface AnalyzeResult */ export interface AnalyzeResult { summary: string; } -/** The Contoso Widget Manager service version. */ -export type Versions = "1.0.0"; +export function analyzeResultDeserializer(item: any): AnalyzeResult { + return { + summary: item["summary"], + }; +} +/** model interface NonReferencedModel */ export interface NonReferencedModel { /** The weight of the widget. This is an int32, but must be greater than zero. */ prop1: number; @@ -69,9 +98,11 @@ export interface NonReferencedModel { prop2: string; } -export function nonReferencedModelSerializer( - item: NonReferencedModel, -): Record { +export function nonReferencedModelSerializer(item: NonReferencedModel): any { + return { prop1: item["prop1"], prop2: item["prop2"] }; +} + +export function nonReferencedModelDeserializer(item: any): NonReferencedModel { return { prop1: item["prop1"], prop2: item["prop2"], diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/widgetServiceClient.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/widgetServiceClient.ts index 3a0022b70a..c60d45ed62 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/widgetServiceClient.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/widgetServiceClient.ts @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { KeyCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; import { getWidgetsOperations, WidgetsOperations, @@ -16,6 +14,8 @@ import { WidgetServiceContext, WidgetServiceClientOptionalParams, } from "./api/index.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { KeyCredential } from "@azure/core-auth"; export { WidgetServiceClientOptionalParams } from "./api/widgetServiceContext.js"; @@ -25,7 +25,7 @@ export class WidgetServiceClient { public readonly pipeline: Pipeline; constructor( - endpoint: string, + endpointParam: string, credential: KeyCredential, options: WidgetServiceClientOptionalParams = {}, ) { @@ -33,7 +33,7 @@ export class WidgetServiceClient { const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-client` : "azsdk-js-client"; - this._client = createWidgetService(endpoint, credential, { + this._client = createWidgetService(endpointParam, credential, { ...options, userAgentOptions: { userAgentPrefix }, }); diff --git a/packages/typespec-ts/package.json b/packages/typespec-ts/package.json index e2c801f598..e9ef1ef2e4 100644 --- a/packages/typespec-ts/package.json +++ b/packages/typespec-ts/package.json @@ -99,7 +99,7 @@ "mkdirp": "^3.0.1", "mocha": "^10.4.0", "npm-run-all": "~4.1.5", - "prettier": "^3.1.0", + "prettier": "^3.3.3", "rimraf": "^5.0.0", "ts-node": "~10.9.1", "typescript": "~5.6.2", @@ -121,7 +121,7 @@ "@azure-tools/rlc-common": "workspace:^0.33.0", "fs-extra": "^11.1.0", "lodash": "^4.17.21", - "prettier": "^3.1.0", + "prettier": "^3.3.3", "ts-morph": "^23.0.0", "tslib": "^2.3.1" }, diff --git a/packages/typespec-ts/src/framework/dependency.ts b/packages/typespec-ts/src/framework/dependency.ts index 4a3c181a87..40875fee06 100644 --- a/packages/typespec-ts/src/framework/dependency.ts +++ b/packages/typespec-ts/src/framework/dependency.ts @@ -26,6 +26,11 @@ export interface CoreDependencies extends Record { name: "OperationOptions"; module: string; }; + StreamableMethod: { + kind: "externalDependency"; + name: "StreamableMethod"; + module: string; + }; PathUncheckedResponse: { kind: "externalDependency"; name: "PathUncheckedResponse"; @@ -56,6 +61,26 @@ export interface CoreDependencies extends Record { name: "stringToUint8Array"; module: string; }; + isKeyCredential: { + kind: "externalDependency"; + name: "isKeyCredential"; + module: string; + }; + KeyCredential: { + kind: "externalDependency"; + name: "KeyCredential"; + module: string; + }; + TokenCredential: { + kind: "externalDependency"; + name: "TokenCredential"; + module: string; + }; + ErrorModel: { + kind: "externalDependency"; + name: "ErrorModel"; + module: string; + }; } export type CoreDependency = keyof CoreDependencies; diff --git a/packages/typespec-ts/src/framework/hooks/binder.ts b/packages/typespec-ts/src/framework/hooks/binder.ts index 94dc1961a2..53512259ff 100644 --- a/packages/typespec-ts/src/framework/hooks/binder.ts +++ b/packages/typespec-ts/src/framework/hooks/binder.ts @@ -43,7 +43,7 @@ export interface Binder { resolveAllReferences(): void; } -const PLACEHOLDER_PREFIX = "_PLACEHOLDER_"; +const PLACEHOLDER_PREFIX = "__PLACEHOLDER_"; class BinderImp implements Binder { private declarations = new Map(); @@ -157,7 +157,7 @@ class BinderImp implements Binder { * @returns The serialized placeholder string. */ private serializePlaceholder(refkey: unknown): string { - return `${PLACEHOLDER_PREFIX}${String(refkey)}_`; + return `${PLACEHOLDER_PREFIX}${String(refkey)}__`; } /** diff --git a/packages/typespec-ts/src/framework/hooks/sdkTypes.ts b/packages/typespec-ts/src/framework/hooks/sdkTypes.ts index fc86a5fede..1d45696cd6 100644 --- a/packages/typespec-ts/src/framework/hooks/sdkTypes.ts +++ b/packages/typespec-ts/src/framework/hooks/sdkTypes.ts @@ -1,14 +1,16 @@ +import { Operation, Type, getNamespaceFullName } from "@typespec/compiler"; import { SdkClientType, + SdkContext, SdkHttpOperation, - SdkPackage, SdkServiceMethod, SdkType, getClientType } from "@azure-tools/typespec-client-generator-core"; -import { Operation, Type, getNamespaceFullName } from "@typespec/compiler"; import { provideContext, useContext } from "../../contextManager.js"; +import { visitPackageTypes } from "../../modular/emitModels.js"; + export interface SdkTypeContext { operations: Map>; types: Map; @@ -50,25 +52,57 @@ export function useSdkTypes() { return getSdkType; } -export function provideSdkTypes(sdkPackage: SdkPackage) { +export function provideSdkTypes(context: SdkContext) { + const sdkPackage = context.sdkPackage; const sdkTypesContext = { operations: new Map>(), types: new Map() }; - - for (const sdkEnum of sdkPackage.enums) { - if (!sdkEnum.__raw) { - continue; + const emitQueue: Set = new Set(); + visitPackageTypes(sdkPackage, emitQueue); + for (const sdkModel of emitQueue) { + switch (sdkModel.kind) { + case "model": + sdkModel.properties.forEach((prop) => { + sdkTypesContext.types.set(prop.type.__raw!, prop.type); + }); + if (sdkModel.discriminatedSubtypes) { + Object.values(sdkModel.discriminatedSubtypes).forEach((subtype) => { + sdkTypesContext.types.set(subtype.__raw!, subtype); + }); + } + break; + case "enum": + if (sdkModel.__raw) { + sdkTypesContext.types.set(sdkModel.__raw, sdkModel); + } + break; + case "union": + sdkModel.variantTypes.forEach((v) => { + if (v.__raw) { + sdkTypesContext.types.set(v.__raw, v); + } + }); + break; + case "array": + sdkTypesContext.types.set( + sdkModel.valueType.__raw!, + sdkModel.valueType + ); + break; + case "dict": + sdkTypesContext.types.set( + sdkModel.valueType.__raw!, + sdkModel.valueType + ); + break; + case "nullable": + sdkTypesContext.types.set(sdkModel.type.__raw!, sdkModel.type); + break; } - - sdkTypesContext.types.set(sdkEnum.__raw, sdkEnum); - } - - for (const sdkModel of sdkPackage.models) { if (!sdkModel.__raw) { continue; } - sdkTypesContext.types.set(sdkModel.__raw, sdkModel); } @@ -79,6 +113,11 @@ export function provideSdkTypes(sdkPackage: SdkPackage) { } sdkTypesContext.operations.set(method.__raw, method); + + // Visit the parameters of the method to add them to the types map + method.parameters.forEach((param) => { + sdkTypesContext.types.set(param.type.__raw!, param.type); + }); } } diff --git a/packages/typespec-ts/src/framework/refkey.ts b/packages/typespec-ts/src/framework/refkey.ts index 57f766b50c..76558d1b8b 100644 --- a/packages/typespec-ts/src/framework/refkey.ts +++ b/packages/typespec-ts/src/framework/refkey.ts @@ -24,5 +24,5 @@ function getKey(value: unknown): RefKey { } export function refkey(...args: unknown[]) { - return args.map((v) => getKey(v)).join("\u2063"); + return args.map((v) => getKey(v)).join("_"); } diff --git a/packages/typespec-ts/src/index.ts b/packages/typespec-ts/src/index.ts index 934bb3dd35..b38b8c6b2f 100644 --- a/packages/typespec-ts/src/index.ts +++ b/packages/typespec-ts/src/index.ts @@ -48,7 +48,6 @@ import { updatePackageFile, buildSampleEnvFile } from "@azure-tools/rlc-common"; -import { buildModels, buildModelsOptions } from "./modular/emitModels.js"; import { buildRootIndex, buildSubClientIndexFile @@ -62,15 +61,15 @@ import { Project } from "ts-morph"; import { buildClassicOperationFiles } from "./modular/buildClassicalOperationGroups.js"; import { buildClassicalClient } from "./modular/buildClassicalClient.js"; import { buildClientContext } from "./modular/buildClientContext.js"; +import { buildApiOptions } from "./modular/emitModelsOptions.js"; import { buildOperationFiles } from "./modular/buildOperations.js"; import { buildRestorePoller } from "./modular/buildRestorePoller.js"; -import { buildSerializeUtils } from "./modular/buildSerializeUtils.js"; import { buildSubpathIndexFile } from "./modular/buildSubpathIndex.js"; import { createSdkContext } from "@azure-tools/typespec-client-generator-core"; import { emitCodeModel } from "./modular/buildCodeModel.js"; import { emitLoggerFile } from "./modular/emitLoggerFile.js"; import { emitSerializerHelpersFile } from "./modular/buildHelperSerializers.js"; -import { env } from "process"; +import { emitTypes } from "./modular/emitModels.js"; import { existsSync } from "fs"; import { getModuleExports } from "./modular/buildProjectFiles.js"; import { getRLCClients } from "./utils/clientUtils.js"; @@ -108,7 +107,6 @@ export async function $onEmit(context: EmitContext) { compilerContext: context, tcgcContext: dpgContext }); - provideSdkTypes(dpgContext.sdkPackage); const { modularSourcesDir } = await calculateGenerationDir(rlcOptions); const staticHelpers = await loadStaticHelpers( outputProject, @@ -132,6 +130,7 @@ export async function $onEmit(context: EmitContext) { ...extraDependencies } }); + provideSdkTypes(dpgContext); const rlcCodeModels: RLCModel[] = []; let modularCodeModel: ModularCodeModel; @@ -266,6 +265,8 @@ export async function $onEmit(context: EmitContext) { const isMultiClients = modularCodeModel.clients.length > 1; + emitTypes(dpgContext, { sourceRoot: modularSourcesRoot }); + buildSubpathIndexFile(modularCodeModel, "models"); // Enable modular sample generation when explicitly set to true or MPG if (emitterOptions?.generateSample === true) { const samples = emitSamples(dpgContext); @@ -276,26 +277,21 @@ export async function $onEmit(context: EmitContext) { } } for (const subClient of modularCodeModel.clients) { - buildModels(subClient, modularCodeModel); - buildModelsOptions(subClient, modularCodeModel); - if (!env["EXPERIMENTAL_TYPESPEC_TS_SERIALIZATION"]) - buildSerializeUtils(modularCodeModel); - // build operation files + buildApiOptions(subClient, modularCodeModel); buildOperationFiles(subClient, dpgContext, modularCodeModel); buildClientContext(subClient, dpgContext, modularCodeModel); - buildSubpathIndexFile(subClient, modularCodeModel, "models"); buildRestorePoller(modularCodeModel, subClient); if (dpgContext.rlcOptions?.hierarchyClient) { - buildSubpathIndexFile(subClient, modularCodeModel, "api"); + buildSubpathIndexFile(modularCodeModel, "api", subClient); } else { - buildSubpathIndexFile(subClient, modularCodeModel, "api", { + buildSubpathIndexFile(modularCodeModel, "api", subClient, { exportIndex: true }); } buildClassicalClient(subClient, dpgContext, modularCodeModel); buildClassicOperationFiles(dpgContext, modularCodeModel, subClient); - buildSubpathIndexFile(subClient, modularCodeModel, "classic", { + buildSubpathIndexFile(modularCodeModel, "classic", subClient, { exportIndex: true, interfaceOnly: true }); @@ -309,6 +305,28 @@ export async function $onEmit(context: EmitContext) { for (const file of project.getSourceFiles()) { file.fixMissingImports({}, { importModuleSpecifierEnding: "js" }); + file.getImportDeclarations().map((importDeclaration) => { + importDeclaration.getNamedImports().map((namedImport) => { + if ( + namedImport + .getNameNode() + .findReferencesAsNodes() + .filter((n) => { + return n.getSourceFile().getFilePath() === file.getFilePath(); + }).length === 1 + ) { + namedImport.remove(); + } + }); + if (importDeclaration.getNamedImports().length === 0) { + importDeclaration.remove(); + } + }); + file.getExportDeclarations().map((exportDeclaration) => { + if (exportDeclaration.getNamedExports().length === 0) { + exportDeclaration.remove(); + } + }); file.fixUnusedIdentifiers(); await emitContentByBuilder( program, @@ -319,6 +337,7 @@ export async function $onEmit(context: EmitContext) { } async function generateMetadataAndTest() { + const project = useContext("outputProject"); if (rlcCodeModels.length === 0 || !rlcCodeModels[0]) { return; } @@ -377,7 +396,6 @@ export async function $onEmit(context: EmitContext) { ); if (option.isModularLibrary) { - const project = useContext("outputProject"); for (const file of project.getSourceFiles()) { await emitContentByBuilder( program, diff --git a/packages/typespec-ts/src/modular/buildClassicalClient.ts b/packages/typespec-ts/src/modular/buildClassicalClient.ts index 410fb55c53..9884d852ac 100644 --- a/packages/typespec-ts/src/modular/buildClassicalClient.ts +++ b/packages/typespec-ts/src/modular/buildClassicalClient.ts @@ -1,9 +1,3 @@ -import { - getImportSpecifier, - Imports as RuntimeImports, - NameType, - normalizeName -} from "@azure-tools/rlc-common"; import { ClassDeclaration, MethodDeclarationStructure, @@ -11,34 +5,44 @@ import { SourceFile, StructureKind } from "ts-morph"; -import { isRLCMultiEndpoint } from "../utils/clientUtils.js"; -import { SdkContext } from "../utils/interfaces.js"; +import { Client, ModularCodeModel } from "./modularCodeModel.js"; +import { NameType, normalizeName } from "@azure-tools/rlc-common"; import { buildUserAgentOptions, - getClientParameters, - importCredential + getClientParametersDeclaration } from "./helpers/clientHelpers.js"; -import { getDocsFromDescription } from "./helpers/docsHelpers.js"; import { + getClassicalClientName, getClassicalLayerPrefix, getClientName } from "./helpers/namingHelpers.js"; + +import { SdkContext } from "../utils/interfaces.js"; +import { getDocsFromDescription } from "./helpers/docsHelpers.js"; import { getOperationFunction } from "./helpers/operationHelpers.js"; -import { Client, ModularCodeModel } from "./modularCodeModel.js"; +import { isRLCMultiEndpoint } from "../utils/clientUtils.js"; +import { resolveReference } from "../framework/reference.js"; import { shouldPromoteSubscriptionId } from "./helpers/classicalOperationHelpers.js"; +import { useDependencies } from "../framework/hooks/useDependencies.js"; export function buildClassicalClient( - client: Client, + _client: Client, dpgContext: SdkContext, codeModel: ModularCodeModel ) { - const { description } = client; + const { description, tcgcClient: client } = _client; + const dependencies = useDependencies(); const modularClientName = getClientName(client); - const classicalClientName = `${getClientName(client)}Client`; - const classicalParams = getClientParameters(client, dpgContext, true); - const contextParams = getClientParameters(client, dpgContext, false); + const classicalClientName = `${getClassicalClientName(client)}`; + const classicalParams = getClientParametersDeclaration(_client, dpgContext, { + requiredOnly: true + }); + const contextParams = getClientParametersDeclaration(_client, dpgContext, { + onClientOnly: true, + requiredOnly: true + }); const srcPath = codeModel.modularOptions.sourceRoot; - const subfolder = client.subfolder ?? ""; + const subfolder = _client.subfolder ?? ""; const clientFile = codeModel.project.createSourceFile( `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}${normalizeName( @@ -64,21 +68,20 @@ export function buildClassicalClient( if (isRLCMultiEndpoint(dpgContext)) { clientClass.addProperty({ name: "_client", - type: `Client.${client.rlcClientName}`, + type: `Client.${_client.rlcClientName}`, scope: Scope.Private }); } else { clientClass.addProperty({ name: "_client", - type: `${client.rlcClientName}`, + type: `${_client.rlcClientName}`, scope: Scope.Private }); } - // Add the pipeline member. This will be the pipeline from /api clientClass.addProperty({ name: "pipeline", - type: "Pipeline", + type: resolveReference(dependencies.Pipeline), scope: Scope.Public, isReadonly: true, docs: ["The pipeline used by this client to make requests"] @@ -107,11 +110,10 @@ export function buildClassicalClient( `this._client = create${modularClientName}(${paramNames.join(",")})` ]); constructor.addStatements(`this.pipeline = this._client.pipeline`); - importCredential(codeModel.runtimeImports, clientFile); - importPipeline(codeModel.runtimeImports, clientFile); - importAllModels(clientFile, srcPath, subfolder); - buildClientOperationGroups(clientFile, client, dpgContext, clientClass); + + buildClientOperationGroups(clientFile, _client, dpgContext, clientClass); importAllApis(clientFile, srcPath, subfolder); + clientFile.fixUnusedIdentifiers(); return clientFile; } @@ -137,76 +139,6 @@ function importAllApis( }); } -function importAllModels( - clientFile: SourceFile, - srcPath: string, - subfolder: string -) { - const project = clientFile.getProject(); - const apiModels = project.getSourceFile( - `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}models/models.ts` - ); - - if (!apiModels) { - return; - } - - const exported = [...apiModels.getExportedDeclarations().keys()].filter( - (e) => { - return !e.startsWith("_"); - } - ); - - if (exported.length > 0) { - clientFile.addImportDeclaration({ - moduleSpecifier: `./models/models.js`, - namedImports: exported - }); - } - - const apiModelsOptions = project.getSourceFile( - `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}models/options.ts` - ); - - if (!apiModelsOptions) { - return; - } - - const exportedOptions = [ - ...apiModelsOptions.getExportedDeclarations().keys() - ]; - - clientFile.addImportDeclaration({ - moduleSpecifier: `./models/options.js`, - namedImports: exportedOptions - }); - - const pagingTypes = project.getSourceFile( - `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}models/pagingTypes.ts` - ); - - if (!pagingTypes) { - return; - } - - const exportedPaingTypes = [...pagingTypes.getExportedDeclarations().keys()]; - - clientFile.addImportDeclaration({ - moduleSpecifier: `./models/pagingTypes.js`, - namedImports: exportedPaingTypes - }); -} - -function importPipeline( - runtimeImports: RuntimeImports, - clientSourceFile: SourceFile -): void { - clientSourceFile.addImportDeclaration({ - moduleSpecifier: getImportSpecifier("restPipeline", runtimeImports), - namedImports: ["Pipeline"] - }); -} - function buildClientOperationGroups( clientFile: SourceFile, client: Client, diff --git a/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts b/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts index 4f56ddd447..921fc68f9d 100644 --- a/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts +++ b/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts @@ -1,6 +1,5 @@ import { NameType } from "@azure-tools/rlc-common"; import { SourceFile } from "ts-morph"; -import { importModels } from "./buildOperations.js"; import { getClassicalOperation } from "./helpers/classicalOperationHelpers.js"; import { getClassicalLayerPrefix } from "./helpers/namingHelpers.js"; import { @@ -44,15 +43,6 @@ export function buildClassicOperationFiles( ); getClassicalOperation(dpgContext, client, classicFile, operationGroup); - // Import models used from ./models.ts - // We SHOULD keep this because otherwise ts-morph will "helpfully" try to import models from the rest layer when we call fixMissingImports(). - importModels( - srcPath, - classicFile, - codeModel.project, - subfolder, - operationGroup.namespaceHierarchies.length - ); importApis(classicFile, client, codeModel, operationGroup); // We need to import the paging helpers and types explicitly because ts-morph may not be able to find them. classicOperationFiles.set(classicOperationFileName, classicFile); @@ -93,10 +83,6 @@ export function buildClassicOperationFiles( operationGroup, layer ); - - // Import models used from ./models.ts - // We SHOULD keep this because otherwise ts-morph will "helpfully" try to import models from the rest layer when we call fixMissingImports(). - importModels(srcPath, classicFile, codeModel.project, subfolder, layer); importApis(classicFile, client, codeModel, operationGroup, layer); classicOperationFiles.set(classicOperationFileName, classicFile); } diff --git a/packages/typespec-ts/src/modular/buildClientContext.ts b/packages/typespec-ts/src/modular/buildClientContext.ts index 407e177202..c6755d32e6 100644 --- a/packages/typespec-ts/src/modular/buildClientContext.ts +++ b/packages/typespec-ts/src/modular/buildClientContext.ts @@ -1,35 +1,41 @@ +import { Client, ModularCodeModel } from "./modularCodeModel.js"; import { - getImportSpecifier, - isAzurePackage, NameType, + isAzurePackage, normalizeName } from "@azure-tools/rlc-common"; -import { SourceFile } from "ts-morph"; -import { SdkContext } from "../utils/interfaces.js"; -import { importModels } from "./buildOperations.js"; import { buildGetClientCredentialParam, buildGetClientEndpointParam, buildGetClientOptionsParam, + getClientParameterName, getClientParameters, - importCredential + getClientParametersDeclaration } from "./helpers/clientHelpers.js"; -import { getDocsFromDescription } from "./helpers/docsHelpers.js"; + +import { SdkContext } from "../utils/interfaces.js"; +import { SourceFile } from "ts-morph"; import { getClientName } from "./helpers/namingHelpers.js"; -import { getType } from "./helpers/typeHelpers.js"; -import { Client, ModularCodeModel } from "./modularCodeModel.js"; +import { getDocsFromDescription } from "./helpers/docsHelpers.js"; +import { getTypeExpression } from "./type-expressions/get-type-expression.js"; +import { resolveReference } from "../framework/reference.js"; +import { useDependencies } from "../framework/hooks/useDependencies.js"; /** * This function creates the file containing the modular client context */ export function buildClientContext( - client: Client, + _client: Client, dpgContext: SdkContext, codeModel: ModularCodeModel ): SourceFile { - const { description, subfolder } = client; + const { description, subfolder, tcgcClient: client } = _client; + const dependencies = useDependencies(); const name = getClientName(client); - const params = getClientParameters(client, dpgContext); + const requiredParams = getClientParametersDeclaration(_client, dpgContext, { + onClientOnly: false, + requiredOnly: true + }); const srcPath = codeModel.modularOptions.sourceRoot; const clientContextFile = codeModel.project.createSourceFile( `${srcPath}/${ @@ -37,33 +43,28 @@ export function buildClientContext( }/api/${normalizeName(name, NameType.File)}Context.ts` ); - importCredential(codeModel.runtimeImports, clientContextFile); - importModels(srcPath, clientContextFile, codeModel.project, subfolder); - clientContextFile.addImportDeclaration({ - moduleSpecifier: getImportSpecifier("restClient", codeModel.runtimeImports), - namedImports: ["ClientOptions", "Client", "getClient"] - }); - clientContextFile.addInterface({ isExported: true, - name: `${client.rlcClientName}`, - extends: ["Client"] + name: `${_client.rlcClientName}`, + extends: [resolveReference(dependencies.Client)], + docs: getDocsFromDescription(description) }); clientContextFile.addInterface({ name: `${name}ClientOptionalParams`, isExported: true, - extends: ["ClientOptions"], - properties: client.parameters - .filter((p) => { - return ( - p.optional || (p.type.type !== "constant" && p.clientDefaultValue) - ); - }) + extends: [resolveReference(dependencies.ClientOptions)], + properties: getClientParameters(_client, dpgContext, { + optionalOnly: true + }) + .filter((p) => p.name !== "endpoint") .map((p) => { return { - name: p.clientName, - type: getType(p.type).name, + name: normalizeName(p.name, NameType.Parameter), + type: + p.name.toLowerCase() === "apiversion" + ? "string" + : getTypeExpression(dpgContext, p.type), hasQuestionToken: true, docs: getDocsFromDescription(p.description) }; @@ -84,13 +85,17 @@ export function buildClientContext( const factoryFunction = clientContextFile.addFunction({ docs: getDocsFromDescription(description), name: `create${name}`, - returnType: `${client.rlcClientName}`, - parameters: params, + returnType: `${_client.rlcClientName}`, + parameters: requiredParams, isExported: true }); - const endpointParam = buildGetClientEndpointParam(factoryFunction, client); - const credentialParam = buildGetClientCredentialParam(client, codeModel); + const endpointParam = buildGetClientEndpointParam( + factoryFunction, + dpgContext, + _client + ); + const credentialParam = buildGetClientCredentialParam(_client, codeModel); const optionsParam = buildGetClientOptionsParam( factoryFunction, codeModel, @@ -98,20 +103,17 @@ export function buildClientContext( ); factoryFunction.addStatements( - `const clientContext = getClient(${endpointParam}, ${credentialParam}, ${optionsParam});` + `const clientContext = ${resolveReference( + dependencies.getClient + )}(${endpointParam}, ${credentialParam}, ${optionsParam});` ); const { customHttpAuthHeaderName, customHttpAuthSharedKeyPrefix } = codeModel.options; if (customHttpAuthHeaderName && customHttpAuthSharedKeyPrefix) { - clientContextFile.addImportDeclaration({ - moduleSpecifier: getImportSpecifier("coreAuth", codeModel.runtimeImports), - namedImports: ["isKeyCredential"] - }); - factoryFunction.addStatements(` - if(isKeyCredential(credential)) { + if(${resolveReference(dependencies.isKeyCredential)}(credential)) { clientContext.pipeline.addPolicy({ name: "customKeyCredentialPolicy", sendRequest(request, next) { @@ -126,11 +128,13 @@ export function buildClientContext( let apiVersionPolicyStatement = `clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" });`; if (dpgContext.hasApiVersionInClient) { - const apiVersionParam = client.parameters.find((x) => x.isApiVersion); + const apiVersionParam = getClientParameters(_client, dpgContext).find( + (x) => x.isApiVersionParam && x.kind === "method" + ); - if (apiVersionParam?.location === "query") { + if (apiVersionParam) { if (apiVersionParam.clientDefaultValue) { - apiVersionPolicyStatement += `const ${apiVersionParam.clientName} = options.${apiVersionParam.clientName} ?? "${apiVersionParam.clientDefaultValue}";`; + apiVersionPolicyStatement += `const apiVersion = options.apiVersion ?? "${apiVersionParam.clientDefaultValue}";`; } apiVersionPolicyStatement += ` @@ -143,7 +147,7 @@ export function buildClientContext( if (!url.searchParams.get("api-version")) { req.url = \`\${req.url}\${ Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" - }api-version=\${${apiVersionParam.clientName}}\`; + }api-version=\${${getClientParameterName(apiVersionParam)}}\`; } return next(req); diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index f00fb055b9..b5dd8d8de8 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -61,7 +61,6 @@ import { NameType, RLCModel, buildRuntimeImports, - getClientName, isAzurePackage, normalizeName } from "@azure-tools/rlc-common"; @@ -113,9 +112,9 @@ import { getAddedOnVersions } from "@typespec/versioning"; import { getModelNamespaceName } from "../utils/namespaceUtils.js"; import { getSupportedHttpAuth } from "../utils/credentialUtils.js"; import { getType as getTypeName } from "./helpers/typeHelpers.js"; -import { isModelWithAdditionalProperties } from "./emitModels.js"; import { reportDiagnostic } from "../lib.js"; import { useContext } from "../contextManager.js"; +import { normalizeModelName } from "./emitModels.js"; interface HttpServerParameter { type: "endpointPath"; @@ -212,6 +211,7 @@ function handleDiscriminator( const discriminatorValues: string[] = []; const aliases: string[] = []; const discriminatedSubtypes: Type[] = []; + let discriminatorTcgcType = undefined; for (const childModel of type.derivedModels) { const modelType = getType(context, childModel, { usage }); aliases.push(modelType.name); @@ -219,6 +219,7 @@ function handleDiscriminator( if (property.restApiName === discriminator.propertyName) { modelType.discriminatorValue = property.type.value; discriminatorValues.push(modelType.discriminatorValue); + discriminatorTcgcType = getClientType(context, property.type); } } discriminatedSubtypes.push(modelType); @@ -230,7 +231,7 @@ function handleDiscriminator( ", " )}` : "discriminator property", - type: { type: "string" }, + type: { type: "string", tcgcType: discriminatorTcgcType }, restApiName: discriminator.propertyName, clientName: discriminator.propertyName, name: discriminator.propertyName, @@ -269,7 +270,8 @@ function processModelProperties( newProperty = { ...newProperty, ...discriminatorInfo, - type: newProperty["type"] + type: newProperty["type"], + tcgcType: getClientType(context, property) }; } newValue.properties.push(newProperty); @@ -306,7 +308,7 @@ function isEmptyAnonymousModel(type: EmitterType): boolean { ); } -function getType( +export function getType( context: SdkContext, type: EmitterType, options: { disableEffectiveModel?: boolean; usage?: UsageFlags } = {} @@ -326,7 +328,7 @@ function getType( return cached; } } - let newValue: any; + let newValue: any = { __raw: type }; if (isEmptyAnonymousModel(type)) { // do not generate model for empty model, treat it as any @@ -346,6 +348,9 @@ function getType( if (enableCache) { if (!options.disableEffectiveModel) { + if (newValue.__raw === undefined) { + newValue.__raw = type; + } typesMap.set(effectiveModel, newValue); } if (type.kind === "Union") { @@ -375,7 +380,8 @@ function getType( } if ( type.kind === "Model" && - isModelWithAdditionalProperties(newValue) && + newValue.type === "dict" && + newValue.name !== "Record" && !context.rlcOptions?.compatibilityMode ) { reportDiagnostic(context.program, { @@ -387,6 +393,7 @@ function getType( }); } + typesMap.set(effectiveModel, newValue); return newValue; } @@ -477,6 +484,9 @@ function emitBodyParameter( usage: UsageFlags.Input }); + type.name = !type.tcgcType.isGeneratedName + ? normalizeModelName(context, type.tcgcType) + : ""; return { contentTypes, type, @@ -987,7 +997,7 @@ function emitProperty( } const type = getType(context, property.type, { usage }); return { - clientName: applyCasing(clientName, { casing: CASING }), + clientName, restApiName: jsonName, type: newProperty.format ? { ...type, format: newProperty.format } : type, optional: property.optional, @@ -1022,7 +1032,7 @@ function getName(program: Program, type: Model): string { } } -function emitModel( +export function emitModel( context: SdkContext, type: Model, usage: UsageFlags @@ -1410,8 +1420,10 @@ function emitUnion( const unionName = getLibraryName(context, type) ? getLibraryName(context, type) : type.name; - const discriminatorPropertyName = getDiscriminator(context.program, type) - ?.propertyName; + const discriminatorPropertyName = getDiscriminator( + context.program, + type + )?.propertyName; const variantTypes = sdkType.variantTypes.map((x) => { const valueType = getType(context, x.__raw!, { usage }); if (valueType.properties && discriminatorPropertyName) { @@ -1572,7 +1584,7 @@ function emitOperationGroups( const name = context.rlcOptions?.hierarchyClient || context.rlcOptions?.enableOperationGroup - ? overrideName ?? operationGroup.type.name + ? (overrideName ?? operationGroup.type.name) : ""; const hierarchies = context.rlcOptions?.hierarchyClient || @@ -1659,14 +1671,14 @@ function emitServerParams( namespace: Namespace ): Parameter[] { const server = getServerHelper(context.program, namespace); - if (server === undefined) { + if (server === undefined || server.parameters.size === 0) { return [ { optional: false, description: "Service host", - clientName: "endpoint", + clientName: "endpointParam", clientDefaultValue: null, - restApiName: "$host", + restApiName: "endpoint", location: "endpointPath", type: { type: "string" }, implementation: "Client", @@ -1701,9 +1713,9 @@ function emitServerParams( { optional: false, description: "Service host", - clientName: "endpoint", + clientName: "endpointParam", clientDefaultValue: server.url, - restApiName: "$host", + restApiName: "endpoint", location: "path", type: { type: "string" }, implementation: "Client", @@ -1787,6 +1799,14 @@ function emitClients( const retval: HrlcClient[] = []; methodApiVersionParam = undefined; for (const client of clients) { + const sdkPackageClient = context.sdkPackage.clients.find((p) => { + return p.name === client.name; + }); + + if (!sdkPackageClient) { + throw new Error(`Client ${client.name} not found in the SDK package`); + } + const clientName = client.name.replace("Client", ""); const server = getServerHelper(program, client.service); const rlcModels = rlcModelsMap.get(client.service.name); @@ -1798,9 +1818,10 @@ function emitClients( description: getDocStr(program, client.type), parameters: emitGlobalParameters(context, client.service), operationGroups: emitOperationGroups(context, client, rlcModels), + tcgcClient: sdkPackageClient, url: server ? server.url : "", apiVersions: [], - rlcClientName: rlcModels ? getClientName(rlcModels) : client.name, + rlcClientName: `${client.name.replace("Client", "")}Context`, subfolder: "", rlcHelperDetails: rlcModels && rlcModels.helperDetails ? rlcModels.helperDetails : {} diff --git a/packages/typespec-ts/src/modular/buildOperations.ts b/packages/typespec-ts/src/modular/buildOperations.ts index 21b8e03b41..e6a2f5f2ea 100644 --- a/packages/typespec-ts/src/modular/buildOperations.ts +++ b/packages/typespec-ts/src/modular/buildOperations.ts @@ -1,15 +1,10 @@ +import { Client, ModularCodeModel, Operation } from "./modularCodeModel.js"; import { - addImportsToFiles, - clearImportSets, - getImportSpecifier, NameType, + clearImportSets, normalizeName } from "@azure-tools/rlc-common"; import { Project, SourceFile } from "ts-morph"; -import { isRLCMultiEndpoint } from "../utils/clientUtils.js"; -import { SdkContext } from "../utils/interfaces.js"; -import { getDocsFromDescription } from "./helpers/docsHelpers.js"; -import { getOperationName } from "./helpers/namingHelpers.js"; import { getDeserializePrivateFunction, getExpectedStatuses, @@ -18,10 +13,15 @@ import { getSendPrivateFunction, isLroOnlyOperation } from "./helpers/operationHelpers.js"; -import { buildType } from "./helpers/typeHelpers.js"; + import { OperationPathAndDeserDetails } from "./interfaces.js"; -import { Client, ModularCodeModel, Operation } from "./modularCodeModel.js"; +import { SdkContext } from "../utils/interfaces.js"; import { addImportBySymbol } from "../utils/importHelper.js"; +import { buildType } from "./helpers/typeHelpers.js"; +import { getDocsFromDescription } from "./helpers/docsHelpers.js"; +import { getOperationName } from "./helpers/namingHelpers.js"; +import { isRLCMultiEndpoint } from "../utils/clientUtils.js"; + /** * This function creates a file under /api for each operation group. * If there is no operation group in the TypeSpec program, we create a single @@ -58,16 +58,6 @@ export function buildOperationFiles( }api/${operationFileName}.ts` ); - // Import models used from ./models.ts - // We SHOULD keep this because otherwise ts-morph will "helpfully" try to import models from the rest layer when we call fixMissingImports(). - importModels( - srcPath, - operationGroupFile, - codeModel.project, - subfolder, - operationGroup.namespaceHierarchies.length - ); - // Import the deserializeUtils importDeserializeUtils( srcPath, @@ -100,12 +90,11 @@ export function buildOperationFiles( const sendOperationDeclaration = getSendPrivateFunction( dpgContext, o, - clientType, - codeModel.runtimeImports + clientType ); const deserializeOperationDeclaration = getDeserializePrivateFunction( - o, - codeModel.runtimeImports + dpgContext, + o ); operationGroupFile.addFunctions([ sendOperationDeclaration, @@ -114,20 +103,8 @@ export function buildOperationFiles( ]); }); - operationGroupFile.addImportDeclarations([ - { - moduleSpecifier: getImportSpecifier( - "restClient", - codeModel?.runtimeImports - ), - namedImports: [ - "StreamableMethod", - "operationOptionsToRequestParameters" - ] - } - ]); - - addImportsToFiles(codeModel.runtimeImports, operationGroupFile); + // addImportsToFiles(codeModel.runtimeImports, operationGroupFile); + operationGroupFile.fixUnusedIdentifiers(); addImportBySymbol("serializeRecord", operationGroupFile); operationFiles.push(operationGroupFile); @@ -135,42 +112,6 @@ export function buildOperationFiles( return operationFiles; } -export function importModels( - srcPath: string, - sourceFile: SourceFile, - project: Project, - subfolder: string = "", - importLayer: number = 0 -) { - const hasModelsImport = sourceFile.getImportDeclarations().some((i) => { - return i.getModuleSpecifierValue().endsWith(`models/models.js`); - }); - const modelsFile = project.getSourceFile( - `${srcPath}/${ - subfolder && subfolder !== "" ? subfolder + "/" : "" - }models/models.ts` - ); - const models: string[] = []; - - for (const [name] of modelsFile?.getExportedDeclarations().entries() ?? []) { - if (name.startsWith("_")) { - continue; - } - models.push(name); - } - - if (models.length > 0 && !hasModelsImport) { - sourceFile.addImportDeclaration({ - moduleSpecifier: `${"../".repeat(importLayer + 1)}models/models.js`, - namedImports: models - }); - } - - // Import all models and then let ts-morph clean up the unused ones - // we can't fixUnusedIdentifiers here because the operaiton files are still being generated. - // sourceFile.fixUnusedIdentifiers(); -} - export function importDeserializeUtils( srcPath: string, sourceFile: SourceFile, diff --git a/packages/typespec-ts/src/modular/buildRestorePoller.ts b/packages/typespec-ts/src/modular/buildRestorePoller.ts index f1e98c7933..431719371a 100644 --- a/packages/typespec-ts/src/modular/buildRestorePoller.ts +++ b/packages/typespec-ts/src/modular/buildRestorePoller.ts @@ -230,7 +230,7 @@ function importClassicalClient( client: Client, sourceFile: SourceFile ): string[] { - const classicalClientName = `${getClientName(client)}Client`; + const classicalClientName = `${getClientName(client.tcgcClient)}Client`; sourceFile.addImportDeclaration({ namedImports: [`${classicalClientName}`], moduleSpecifier: `./${normalizeName(classicalClientName, NameType.File)}.js` diff --git a/packages/typespec-ts/src/modular/buildRootIndex.ts b/packages/typespec-ts/src/modular/buildRootIndex.ts index 236db37d93..fcc3944914 100644 --- a/packages/typespec-ts/src/modular/buildRootIndex.ts +++ b/packages/typespec-ts/src/modular/buildRootIndex.ts @@ -1,6 +1,9 @@ import { NameType, normalizeName } from "@azure-tools/rlc-common"; import { Project, SourceFile } from "ts-morph"; -import { getClientName } from "./helpers/namingHelpers.js"; +import { + getClassicalClientName, + getClientName +} from "./helpers/namingHelpers.js"; import { Client, ModularCodeModel } from "./modularCodeModel.js"; import { resolveReference } from "../framework/reference.js"; import { PagingHelpers } from "./static-helpers-metadata.js"; @@ -13,7 +16,7 @@ export function buildRootIndex( const { project } = codeModel; const srcPath = codeModel.modularOptions.sourceRoot; const subfolder = client.subfolder ?? ""; - const clientName = `${getClientName(client)}Client`; + const clientName = `${getClassicalClientName(client.tcgcClient)}`; const clientFile = project.getSourceFile( `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}${normalizeName( clientName, @@ -39,24 +42,25 @@ export function buildRootIndex( subfolder, true ); - exportModules( - rootIndexFile, - project, - srcPath, - clientName, - "models", + const modelsExportsIndex = rootIndexFile + .getExportDeclarations() + ?.find((i) => { + return i.getModuleSpecifierValue() === `./models/index.js`; + }); + if (!modelsExportsIndex) { + exportModules(rootIndexFile, project, srcPath, clientName, "models", { + isTopLevel: true + }); + } + exportModules(rootIndexFile, project, srcPath, clientName, "api", { subfolder, - true - ); - exportModules( - rootIndexFile, - project, - srcPath, - clientName, - "classic", + interfaceOnly: true, + isTopLevel: true + }); + exportModules(rootIndexFile, project, srcPath, clientName, "classic", { subfolder, - true - ); + isTopLevel: true + }); exportPagingTypes(codeModel, rootIndexFile); } @@ -165,27 +169,38 @@ function exportClassicalClient( subfolder: string, isSubClient: boolean = false ) { - const clientName = `${getClientName(client)}Client`; + const clientName = `${getClientName(client.tcgcClient)}Client`; indexFile.addExportDeclaration({ - namedExports: [clientName, `${clientName}OptionalParams`], + namedExports: [clientName], moduleSpecifier: `./${ subfolder !== "" && !isSubClient ? subfolder + "/" : "" }${normalizeName(clientName, NameType.File)}.js` }); } +export interface ExportModulesOptions { + interfaceOnly?: boolean; + isTopLevel?: boolean; + subfolder?: string; +} + function exportModules( indexFile: SourceFile, project: Project, srcPath: string, clientName: string, moduleName: string, - subfolder: string = "", - isTopLevel: boolean = false + options: ExportModulesOptions = { + interfaceOnly: false, + isTopLevel: false, + subfolder: "" + } ) { const modelsFile = project.getSourceFile( `${srcPath}/${ - subfolder !== "" ? subfolder + "/" : "" + options.subfolder !== "" && options.subfolder + ? options.subfolder + "/" + : "" }${moduleName}/index.ts` ); if (!modelsFile) { @@ -193,16 +208,38 @@ function exportModules( } const exported = [...indexFile.getExportedDeclarations().keys()]; - const namedExports = [...modelsFile.getExportedDeclarations().keys()].map( - (modelName) => { - if (exported.indexOf(modelName) > -1) { - return `${modelName} as ${clientName}${modelName}`; + const namedExports = [...modelsFile.getExportedDeclarations().entries()] + .filter((exDeclaration) => { + if (exDeclaration[0].startsWith("_")) { + return false; } - return modelName; - } - ); + return exDeclaration[1].some((ex) => { + if ( + options.interfaceOnly && + ex.getKindName() !== "InterfaceDeclaration" + ) { + return false; + } + if ( + options.interfaceOnly && + options.isTopLevel && + exDeclaration[0].endsWith("Context") + ) { + return false; + } + return true; + }); + }) + .map((exDeclaration) => { + if (exported.indexOf(exDeclaration[0]) > -1) { + return `${exDeclaration[0]} as ${clientName}${exDeclaration[0]}`; + } + return exDeclaration[0]; + }); const moduleSpecifier = `./${ - isTopLevel && subfolder !== "" ? subfolder + "/" : "" + options.isTopLevel && options.subfolder !== "" && options.subfolder + ? options.subfolder + "/" + : "" }${moduleName}/index.js`; indexFile.addExportDeclaration({ moduleSpecifier, @@ -221,7 +258,7 @@ export function buildSubClientIndexFile( undefined, { overwrite: true } ); - const clientName = `${getClientName(client)}Client`; + const clientName = `${getClientName(client.tcgcClient)}Client`; const clientFilePath = `${srcPath}/${ subfolder !== "" ? subfolder + "/" : "" }${normalizeName(clientName, NameType.File)}.ts`; @@ -244,8 +281,11 @@ export function buildSubClientIndexFile( codeModel.project, srcPath, clientName, - "models", - subfolder + "api", + { + subfolder, + interfaceOnly: true + } ); exportModules( subClientIndexFile, @@ -253,6 +293,6 @@ export function buildSubClientIndexFile( srcPath, clientName, "classic", - subfolder + { subfolder } ); } diff --git a/packages/typespec-ts/src/modular/buildSerializeUtils.ts b/packages/typespec-ts/src/modular/buildSerializeUtils.ts deleted file mode 100644 index 52db572c5d..0000000000 --- a/packages/typespec-ts/src/modular/buildSerializeUtils.ts +++ /dev/null @@ -1,749 +0,0 @@ -import { - addImportsToFiles, - addImportToSpecifier, - clearImportSets, - Imports as RuntimeImports -} from "@azure-tools/rlc-common"; -import { UsageFlags } from "@typespec/compiler"; -import { - FunctionDeclarationStructure, - SourceFile, - StructureKind -} from "ts-morph"; -import { toPascalCase } from "../utils/casingUtils.js"; -import { - deserializeResponseValue, - getAllAncestors, - getRequestModelMapping, - getResponseMapping, - serializeRequestValue -} from "./helpers/operationHelpers.js"; -import { ModularCodeModel, Type } from "./modularCodeModel.js"; - -/** - * This function creates serialize and deserialize utils for special unions and that are used in the operation. - */ -export function buildSerializeUtils(model: ModularCodeModel) { - const serializeUtilFiles = []; - for (const serializeType of ["deserialize"]) { - const usageCondition = - serializeType === "serialize" ? UsageFlags.Input : UsageFlags.Output; - const specialUnions = model.types.filter( - (t) => isSpecialHandledUnion(t) && (t.usage ?? 0) & usageCondition - ); - if (specialUnions.length === 0) { - continue; - } - clearImportSets(model.runtimeImports); - const utilsFile = model.project.createSourceFile( - `${model.modularOptions.sourceRoot}/utils/${serializeType}Util.ts` - ); - - specialUnions.forEach((su) => { - let types = su.types; - if (su.type === "list") { - types = su.elementType?.types; - } - const unionDeserializeTypes = types?.filter((et) => { - return isSpecialUnionVariant(et); - }); - unionDeserializeTypes?.forEach((et) => { - if (serializeType === "serialize") { - // getTypePredictFunction( - // utilsFile, - // et, - // serializeType, - // getTypeUnionName(su, false, model.runtimeImports, serializeType) - // ); - getTypeSerializeFunction( - utilsFile, - et, - serializeType, - model.runtimeImports - ); - } else { - // getTypePredictFunction( - // utilsFile, - // et, - // serializeType, - // getTypeUnionName(su, true, model.runtimeImports, serializeType) - // ); - getTypeDeserializeFunction( - utilsFile, - et, - serializeType, - model.runtimeImports - ); - } - }); - const deserializeFunctionName = getDeserializeFunctionName( - su, - serializeType, - model.runtimeImports - ); - if (serializeType === "serialize") { - deserializeUnionTypesFunction( - utilsFile, - unionDeserializeTypes ?? [], - deserializeFunctionName, - serializeType, - getTypeUnionName(su, false, model.runtimeImports, serializeType), - getTypeUnionName(su, true, model.runtimeImports, serializeType), - su.discriminator, - su.isPolymorphicBaseModel - ); - } else { - deserializeUnionTypesFunction( - utilsFile, - unionDeserializeTypes ?? [], - deserializeFunctionName, - serializeType, - getTypeUnionName(su, true, model.runtimeImports, serializeType), - getTypeUnionName(su, false, model.runtimeImports, serializeType), - su.discriminator, - su.isPolymorphicBaseModel - ); - } - }); - addImportsToFiles(model.runtimeImports, utilsFile, { - rlcIndex: "../rest/index.js", - modularModel: "../models/models.js", - coreUtil: "@azure/core-util" - }); - serializeUtilFiles.push(utilsFile); - } - return serializeUtilFiles; -} - -export function getDeserializeFunctionName( - type: Type, - serializeType: string, - runtimeImports?: RuntimeImports -) { - const typeUnionNames = getTypeUnionName( - type, - false, - runtimeImports, - serializeType - ); - const deserializeFunctionName = `${serializeType}${toPascalCase( - formalizeTypeUnionName(typeUnionNames ?? "") - )}`; - return deserializeFunctionName; -} - -function formalizeTypeUnionName(typeUnionName: string) { - return typeUnionName - .replace(/\[\]/g, "Array") - .replace(/ /g, "") - .replace(/\|/g, "And"); -} - -/** - * - * In general, we have two kinds of basic special union variants. - * 1. datetime type - * 2. bytes type - * If we consider model type, we have the following three type. - * 3. model with property of datetime type. - * 4. model with property of binary array type. - * 5. model that has different property name between rest layer and modular layer. - * 6. nested model i.e. model with property that is a model with one of the above three conditions. - * If we consider array type, with all the above 6 types as the element types. - */ -const specialVariantMap = new Map(); -export function isSpecialUnionVariant( - t: Type, - variantStack: Type[] = [] -): boolean { - if (variantStack.length <= 0) { - variantStack.push(t); - } - const ancestors = getAllAncestors(t); - if (specialVariantMap.has(t)) { - variantStack.pop(); - return specialVariantMap.get(t) ?? false; - } - - if ( - t.type === "datetime" || - t.type === "byte-array" || - (t.type === "model" && - t.properties - ?.filter((p) => { - return !( - variantStack.includes(p.type) || - ancestors.includes(p.type) || - (p.type.type === "list" && - p.type.elementType && - (variantStack.includes(p.type.elementType) || - ancestors.includes(p.type.elementType))) - ); - }) - ?.some( - (p) => - p.clientName !== p.restApiName || - isSpecialUnionVariant(p.type, [...variantStack, p.type]) - )) || - isPolymorphicUnion(t) || - (t.type === "list" && - t.elementType && - !variantStack.includes(t.elementType) && - !ancestors.includes(t.elementType) && - isSpecialUnionVariant(t.elementType, [...variantStack, t.elementType])) || - (t.type === "combined" && - t.types - ?.filter((p) => { - return !(variantStack.includes(p) || ancestors.includes(p)); - }) - ?.some((p) => { - return isSpecialUnionVariant(p, [...variantStack, p]); - })) || - (t.type === "enum" && !(t.isFixed || t.isNonExhaustive)) - ) { - specialVariantMap.set(t, true); - variantStack.pop(); - return true; - } - variantStack.pop(); - specialVariantMap.set(t, false); - return false; -} - -export function isNormalUnion(t: Type): boolean { - return ( - t.type === "combined" && - !( - t.types?.some((p) => { - return isSpecialUnionVariant(p); - }) ?? false - ) - ); -} - -export function isDiscriminatedUnion(t: Type): boolean { - return ( - t.type === "combined" && - (t.discriminator ? true : false) && - (t.types?.some((p) => { - return isSpecialUnionVariant(p); - }) ?? - false) - ); -} - -export function isSpecialHandledUnion(t: Type): boolean { - return isDiscriminatedUnion(t) || isPolymorphicUnion(t); -} - -const polymorphicUnionMap = new Map(); -export function isPolymorphicUnion(t: Type): boolean { - if (polymorphicUnionMap.has(t)) { - return polymorphicUnionMap.get(t) ?? false; - } - const ancestors = getAllAncestors(t); - if ( - t.type === "model" && - t.isPolymorphicBaseModel && - t.types - ?.filter((p) => { - return !ancestors.includes(p); - }) - ?.some((p) => { - return isSpecialUnionVariant(p); - }) - ) { - polymorphicUnionMap.set(t, true); - return true; - } - polymorphicUnionMap.set(t, false); - return false; -} - -function getTypeUnionName( - type: Type, - fromRest: boolean, - runtimeImports?: RuntimeImports, - serializeType?: string -) { - const types = type.types; - if (type.type === "list") { - types === type.elementType?.types; - } - if (type.name) { - const typeName = - (fromRest && type.alias ? type.alias : type.name) + - (fromRest ? (serializeType === "serialize" ? "Rest" : "Output") : ""); - if (fromRest && runtimeImports) { - addImportToSpecifier( - "rlcIndex", - runtimeImports, - (type.alias ?? type.name) + - (serializeType === "serialize" - ? " as " + (type.alias ?? type.name) + "Rest" - : "Output") - ); - } else if (runtimeImports) { - addImportToSpecifier("modularModel", runtimeImports, type.name); - } - return typeName; - } - return types - ?.map((t) => { - if (t.type === "list" && t.elementType?.type === "model") { - if (fromRest && t.elementType.name && runtimeImports) { - addImportToSpecifier( - "rlcIndex", - runtimeImports, - (t.elementType.alias ?? t.elementType.name) + - (serializeType === "serialize" - ? " as " + t.elementType.name + "Rest" - : "Output") - ); - } else if (t.elementType.name && runtimeImports) { - addImportToSpecifier( - "modularModel", - runtimeImports, - t.elementType.name - ); - } - return ( - (t.elementType.alias ?? t.elementType.name) + - (fromRest - ? serializeType === "serialize" - ? "Rest" - : "Output" - : "") + - "[]" - ); - } - if (fromRest && t.name && runtimeImports) { - addImportToSpecifier( - "rlcIndex", - runtimeImports, - (t.alias ?? t.name) + - (serializeType === "serialize" - ? " as " + (t.alias ?? t.name) + "Rest" - : "Output") - ); - } else if (t.name && runtimeImports) { - addImportToSpecifier("modularModel", runtimeImports, t.name); - } - return t.name - ? (fromRest && t.alias ? t.alias : t.name) + - (fromRest - ? serializeType === "serialize" - ? "Rest" - : "Output" - : "") - : getMappedType(t.type, fromRest); - }) - .join(" | "); -} - -function getMappedType(modularType: string, fromRest?: boolean) { - switch (modularType) { - case "datetime": - return fromRest ? "string" : "Date"; - case "byte-array": - return fromRest ? "string" : "Uint8Array"; - default: - return modularType; - } -} - -function getTypeDeserializeFunction( - sourceFile: SourceFile, - type: Type, - serializeType: string, - runtimeImports: RuntimeImports -) { - const statements: string[] = []; - - if (isSpecialHandledUnion(type)) { - return; - } - if (type.type === "model" && type.name) { - addImportToSpecifier("rlcIndex", runtimeImports, `${type.name}Output`); - addImportToSpecifier("modularModel", runtimeImports, type.name); - const functionStatement: FunctionDeclarationStructure = { - kind: StructureKind.Function, - docs: [`${serializeType} function for ${type.name}`], - name: `${serializeType}${toPascalCase(type.name)}`, - parameters: [{ name: "obj", type: `${type.name}Output` }], - returnType: type.name - }; - if (type.properties) { - statements.push( - `return {${getResponseMapping(type, "obj", runtimeImports)}};` - ); - } else { - statements.push(`return {};`); - } - functionStatement.statements = statements.join("\n"); - if (!hasDuplicateFunction(sourceFile, functionStatement)) { - if ( - sourceFile - .getFunctions() - .some((f) => f.getName() === functionStatement.name) - ) { - addOverload(sourceFile, type.name + "Output", functionStatement); - } else { - sourceFile.addFunction(functionStatement); - } - } - } else if ( - type.type === "list" && - type.elementType?.type === "model" && - type.elementType.name - ) { - addImportToSpecifier( - "rlcIndex", - runtimeImports, - `${type.elementType.name}Output` - ); - addImportToSpecifier("modularModel", runtimeImports, type.elementType.name); - const functionStatement: FunctionDeclarationStructure = { - kind: StructureKind.Function, - docs: [`${serializeType} function for ${type.elementType.name} array`], - name: `${serializeType}${toPascalCase(type.elementType.name)}Array`, - parameters: [{ name: "obj", type: type.elementType.name + "Output[]" }], - returnType: type.elementType.name + "[]" - }; - statements.push( - `return (obj || []).map(item => { return {${getResponseMapping( - type.elementType, - "item", - runtimeImports - )}}})` - ); - functionStatement.statements = statements.join("\n"); - if (!hasDuplicateFunction(sourceFile, functionStatement)) { - if ( - sourceFile - .getFunctions() - .some((f) => f.getName() === functionStatement.name) - ) { - addOverload( - sourceFile, - type.elementType.name ?? "Output[]", - functionStatement - ); - } else { - sourceFile.addFunction(functionStatement); - } - } - } else if (type.type === "datetime") { - const functionStatement: FunctionDeclarationStructure = { - kind: StructureKind.Function, - docs: [`${serializeType} function for ${type.type}`], - name: `${serializeType}${toPascalCase( - getMappedType(type.type) + - (serializeType === "deserialize" ? "Rest" : "") - )}`, - parameters: [{ name: "obj", type: "string" }], - returnType: "Date" - }; - statements.push(`return new Date(obj);`); - functionStatement.statements = statements.join("\n"); - if (!hasDuplicateFunction(sourceFile, functionStatement)) { - if ( - sourceFile - .getFunctions() - .some((f) => f.getName() === functionStatement.name) - ) { - addOverload(sourceFile, type.name ?? "", functionStatement); - } else { - sourceFile.addFunction(functionStatement); - } - } - } else if (type.type === "byte-array") { - const functionStatement: FunctionDeclarationStructure = { - kind: StructureKind.Function, - docs: [`${serializeType} function for ${type.type}`], - name: `${serializeType}${toPascalCase( - getMappedType(type.name ?? "byte-array") + - (serializeType === "deserialize" ? "Rest" : "") - )}`, - parameters: [{ name: "obj", type: "string" }], - returnType: "Uint8Array" - }; - statements.push( - `return ${deserializeResponseValue( - type, - "obj", - runtimeImports, - true, - [type], - type.format ?? "base64" - )}` - ); - functionStatement.statements = statements.join("\n"); - if (!hasDuplicateFunction(sourceFile, functionStatement)) { - if ( - sourceFile - .getFunctions() - .some((f) => f.getName() === functionStatement.name) - ) { - addOverload(sourceFile, type.name ?? "", functionStatement); - } else { - sourceFile.addFunction(functionStatement); - } - } - } -} - -function getTypeSerializeFunction( - sourceFile: SourceFile, - type: Type, - serializeType: string, - runtimeImports: RuntimeImports -) { - const statements: string[] = []; - if (isSpecialHandledUnion(type)) { - return; - } - if (type.type === "model" && type.name) { - const typeName = type.name + "Rest"; - addImportToSpecifier( - "rlcIndex", - runtimeImports, - `${type.name} as ${typeName}` - ); - addImportToSpecifier("modularModel", runtimeImports, type.name); - const functionStatement: FunctionDeclarationStructure = { - kind: StructureKind.Function, - docs: [`${serializeType} function for ${type.name}`], - name: `${serializeType}${toPascalCase(type.name)}`, - parameters: [{ name: "obj", type: `${type.name}` }], - returnType: typeName - }; - if (type.properties) { - const { propertiesStr } = getRequestModelMapping( - type, - "obj", - runtimeImports - ); - statements.push(`return { - ${propertiesStr.join(", ")} - };`); - } else { - statements.push(`return {};`); - } - functionStatement.statements = statements.join("\n"); - if (!hasDuplicateFunction(sourceFile, functionStatement)) { - if ( - sourceFile - .getFunctions() - .some((f) => f.getName() === functionStatement.name) - ) { - addOverload(sourceFile, typeName, functionStatement); - } else { - sourceFile.addFunction(functionStatement); - } - } - } else if ( - type.type === "list" && - type.elementType?.type === "model" && - type.elementType.name - ) { - const typeName = type.elementType.name + "Rest"; - addImportToSpecifier( - "rlcIndex", - runtimeImports, - `${type.elementType.name} as ${typeName}` - ); - addImportToSpecifier("modularModel", runtimeImports, type.elementType.name); - const functionStatement: FunctionDeclarationStructure = { - kind: StructureKind.Function, - docs: [`${serializeType} function for ${type.elementType.name} array`], - name: `${serializeType}${toPascalCase(type.elementType.name)}Array`, - parameters: [{ name: "obj", type: type.elementType.name + "[]" }], - returnType: `${typeName}[]` - }; - const { propertiesStr } = getRequestModelMapping( - type.elementType, - "item", - runtimeImports - ); - - statements.push( - `return (obj || []).map(item => { - return { ${propertiesStr.join(", ")} } - })` - ); - functionStatement.statements = statements.join("\n"); - if (!hasDuplicateFunction(sourceFile, functionStatement)) { - if ( - sourceFile - .getFunctions() - .some((f) => f.getName() === functionStatement.name) - ) { - addOverload(sourceFile, `${typeName}[]`, functionStatement); - } else { - sourceFile.addFunction(functionStatement); - } - } - } else if (type.type === "datetime") { - const functionStatement: FunctionDeclarationStructure = { - kind: StructureKind.Function, - docs: [`${serializeType} function for ${type.type}`], - name: `${serializeType}${toPascalCase( - getMappedType(type.type) + - (serializeType === "deserialize" ? "Rest" : "") - )}`, - parameters: [{ name: "obj", type: "Date" }], - returnType: "string" - }; - statements.push( - `return ${serializeRequestValue(type, "obj", runtimeImports, true)}` - ); - functionStatement.statements = statements.join("\n"); - if (!hasDuplicateFunction(sourceFile, functionStatement)) { - if ( - sourceFile - .getFunctions() - .some((f) => f.getName() === functionStatement.name) - ) { - addOverload(sourceFile, type.name ?? "", functionStatement); - } else { - sourceFile.addFunction(functionStatement); - } - } - } else if (type.type === "byte-array") { - const functionStatement: FunctionDeclarationStructure = { - kind: StructureKind.Function, - docs: [`${serializeType} function for ${type.type}`], - name: `${serializeType}${toPascalCase( - getMappedType(type.type) + - (serializeType === "deserialize" ? "Rest" : "") - )}`, - parameters: [{ name: "obj", type: "Uint8Array" }], - returnType: "string" - }; - statements.push( - `return ${serializeRequestValue(type, "obj", runtimeImports, true)}` - ); - functionStatement.statements = statements.join("\n"); - if (!hasDuplicateFunction(sourceFile, functionStatement)) { - if ( - sourceFile - .getFunctions() - .some((f) => f.getName() === functionStatement.name) - ) { - addOverload(sourceFile, type.name ?? "", functionStatement); - } else { - sourceFile.addFunction(functionStatement); - } - } - } -} - -function addOverload( - sourceFile: SourceFile, - typeName: string, - functionStatement: FunctionDeclarationStructure -) { - const existFunction = sourceFile.getFunction(functionStatement.name ?? ""); - if (existFunction && existFunction.getOverloads().length === 0) { - existFunction.addOverload({ - kind: StructureKind.FunctionOverload, - parameters: existFunction.getParameters().map((p) => { - return { - name: p.getName(), - type: p.getTypeNode()?.getText() - }; - }), - returnType: existFunction.getReturnTypeNode()?.getText(), - docs: existFunction.getJsDocs().map((d) => { - return { description: d.getInnerText() }; - }) - }); - } - existFunction?.addOverload({ - kind: StructureKind.FunctionOverload, - parameters: [ - { - name: "obj", - type: typeName - } - ], - docs: functionStatement.docs, - returnType: functionStatement.returnType - }); - const implementationParameter = sourceFile - .getFunction(functionStatement.name ?? "") - ?.getParameters(); - if (implementationParameter && implementationParameter.length > 0) { - const oldTypes = implementationParameter[0] - ?.getTypeNode() - ?.getText() - .split(" | "); - const newTypes = typeName.split(" | ").concat(oldTypes ?? []); - const newTypeSet = new Set(newTypes); - implementationParameter[0]?.setType(Array.from(newTypeSet).join(" | ")); - } -} - -function hasDuplicateFunction( - sourceFile: SourceFile, - functionStatement: FunctionDeclarationStructure -) { - return sourceFile.getFunctions().some((f) => { - const paramTypes = f.getParameters().map((param) => { - return param.getName() + param.getType().getText(); - }); - const funcParamTypes = functionStatement.parameters?.map((param) => { - return param.name + param.type; - }); - return ( - f.getName() === functionStatement.name && - paramTypes.join().includes(funcParamTypes?.join() ?? "") - ); - }); -} - -function deserializeUnionTypesFunction( - sourceFile: SourceFile, - unionDeserializeTypes: Type[], - deserializeFunctionName: string, - serializeType: string, - typeUnionNamesOutput: string | undefined, - typeUnionNames: string | undefined, - discriminator?: string, - isPolymorphicBaseModel?: boolean -) { - const functionStatement: FunctionDeclarationStructure = { - kind: StructureKind.Function, - docs: [`${serializeType} function for ${typeUnionNamesOutput}`], - name: deserializeFunctionName, - parameters: [{ name: "obj", type: typeUnionNamesOutput }], - returnType: typeUnionNames, - isExported: true - }; - const statements: string[] = []; - statements.push(`switch (obj.${discriminator}) {`); - for (const type of unionDeserializeTypes) { - const functionName = toPascalCase( - type.name ?? - (type.elementType?.name - ? type.elementType.name + "Array" - : getMappedType(type.type) + - (serializeType === "deserialize" ? "Rest" : "")) - ); - statements.push( - `case "${ - type.discriminatorValue - }": return ${serializeType}${functionName}(obj${ - isPolymorphicBaseModel - ? " as " + (type.name ?? type.elementType?.name + "[]") - : "" - }); ` - ); - } - statements.push("default: return obj; }"); - functionStatement.statements = statements.join("\n"); - if (!hasDuplicateFunction(sourceFile, functionStatement)) { - sourceFile.addFunction(functionStatement); - } -} diff --git a/packages/typespec-ts/src/modular/buildSubpathIndex.ts b/packages/typespec-ts/src/modular/buildSubpathIndex.ts index d4244fddea..ecefb353dc 100644 --- a/packages/typespec-ts/src/modular/buildSubpathIndex.ts +++ b/packages/typespec-ts/src/modular/buildSubpathIndex.ts @@ -1,22 +1,23 @@ -import { join } from "path"; import { Client, ModularCodeModel } from "./modularCodeModel.js"; +import { join } from "path"; + export interface buildSubpathIndexFileOptions { exportIndex?: boolean; interfaceOnly?: boolean; } export function buildSubpathIndexFile( - client: Client, codeModel: ModularCodeModel, subpath: string, + client?: Client, options: buildSubpathIndexFileOptions = {} ) { - const { subfolder } = client; + const subfolder = client?.subfolder ?? ""; const srcPath = codeModel.modularOptions.sourceRoot; // Skip to export these files because they are used internally. const skipFiles = ["pagingHelpers.ts", "pollingHelpers.ts"]; - const apiFilePattern = join(srcPath, client.subfolder ?? "", subpath); + const apiFilePattern = join(srcPath, subfolder, subpath); const apiFiles = codeModel.project.getSourceFiles().filter((file) => { return file .getFilePath() @@ -30,14 +31,15 @@ export function buildSubpathIndexFile( `${srcPath}/${subfolder}/${subpath}/index.ts` ); for (const file of apiFiles) { - if (!options.exportIndex && file.getFilePath().endsWith("index.ts")) { + const filePath = file.getFilePath(); + if (!options.exportIndex && filePath.endsWith("index.ts")) { continue; } // Skip to export these files because they are used internally. - if (skipFiles.some((skipFile) => file.getFilePath().endsWith(skipFile))) { + if (skipFiles.some((skipFile) => filePath.endsWith(skipFile))) { continue; } - if (file.getFilePath() === indexFile.getFilePath()) { + if (filePath === indexFile.getFilePath()) { continue; } @@ -58,7 +60,8 @@ export function buildSubpathIndexFile( if ( subpath === "models" && ex.getKindName() === "FunctionDeclaration" && - exDeclaration[0].endsWith("Serializer") + (exDeclaration[0].endsWith("Serializer") || + exDeclaration[0].endsWith("Deserializer")) ) { return false; } @@ -70,14 +73,13 @@ export function buildSubpathIndexFile( return exDeclaration[0]; }); // Skip to export PagedResult and BuildPagedAsyncIteratorOptions - if (file.getFilePath().endsWith("pagingTypes.ts")) { + if (filePath.endsWith("pagingTypes.ts")) { namedExports = namedExports.filter( (ex) => !["PagedResult", "BuildPagedAsyncIteratorOptions"].includes(ex) ); } indexFile.addExportDeclaration({ - moduleSpecifier: `.${file - .getFilePath() + moduleSpecifier: `.${filePath .replace(indexFile.getDirectoryPath(), "") .replace(/\\/g, "/") .replace(".ts", "")}.js`, diff --git a/packages/typespec-ts/src/modular/emitModels.ts b/packages/typespec-ts/src/modular/emitModels.ts index 688ecd64d8..02a0c11fee 100644 --- a/packages/typespec-ts/src/modular/emitModels.ts +++ b/packages/typespec-ts/src/modular/emitModels.ts @@ -1,317 +1,286 @@ -import * as path from "path"; - -import { - Client, - ModularCodeModel, - Type as ModularType -} from "./modularCodeModel.js"; import { + EnumDeclarationStructure, + EnumMemberStructure, InterfaceDeclarationStructure, OptionalKind, + PropertySignatureStructure, SourceFile, + StructureKind, TypeAliasDeclarationStructure } from "ts-morph"; -import { addImportsToFiles, getImportSpecifier } from "@azure-tools/rlc-common"; +import { NameType, normalizeName } from "@azure-tools/rlc-common"; +import { + SdkArrayType, + SdkBodyModelPropertyType, + SdkClientType, + SdkDictionaryType, + SdkEnumType, + SdkEnumValueType, + SdkHttpOperation, + SdkHttpPackage, + SdkMethod, + SdkModelPropertyType, + SdkModelType, + SdkType, + SdkUnionType, + UsageFlags, + isReadOnly +} from "@azure-tools/typespec-client-generator-core"; +import { + getExternalModel, + getModelExpression +} from "./type-expressions/get-model-expression.js"; +import { SdkContext } from "../utils/interfaces.js"; +import { addDeclaration } from "../framework/declaration.js"; import { addImportBySymbol } from "../utils/importHelper.js"; +import { buildModelDeserializer } from "./serialization/buildDeserializerFunction.js"; import { buildModelSerializer } from "./serialization/buildSerializerFunction.js"; -import { buildOperationOptions } from "./buildOperations.js"; -import { getDocsFromDescription } from "./helpers/docsHelpers.js"; -import { getModularModelFilePath } from "./helpers/namingHelpers.js"; -import { getType } from "./helpers/typeHelpers.js"; -import { toCamelCase } from "../utils/casingUtils.js"; - -// ====== UTILITIES ====== +import { extractPagedMetadataNested } from "../utils/operationUtil.js"; +import { getTypeExpression } from "./type-expressions/get-type-expression.js"; +import path from "path"; +import { refkey } from "../framework/refkey.js"; +import { useContext } from "../contextManager.js"; +import { isMetadata } from "@typespec/http"; +import { + isAzureCoreErrorType, + isAzureCoreLroType +} from "../utils/modelUtils.js"; +import { isExtensibleEnum } from "./type-expressions/get-enum-expression.js"; +import { isDiscriminatedUnion } from "./serialization/serializeUtils.js"; -function isAzureCoreErrorSdkType(t: ModularType) { - return ( - t.name && - ["error", "errormodel", "innererror", "errorresponse"].includes( - t.name.toLowerCase() - ) && - t.coreTypeInfo === "ErrorType" - ); -} +type InterfaceStructure = OptionalKind & { + extends?: string[]; + kind: StructureKind.Interface; +}; -function isAzureCoreLroSdkType(t: ModularType) { +function isGenerableType( + type: SdkType +): type is + | SdkModelType + | SdkEnumType + | SdkUnionType + | SdkDictionaryType + | SdkArrayType { return ( - t.name && - ["operationstate"].includes(t.name.toLowerCase()) && - t.coreTypeInfo === "LroType" + type.kind === "model" || + type.kind === "enum" || + type.kind === "union" || + type.kind === "dict" || + type.kind === "array" ); } +export function emitTypes( + context: SdkContext, + { sourceRoot }: { sourceRoot: string } +) { + const sdkPackage = context.sdkPackage; + const emitQueue: Set = new Set(); + const outputProject = useContext("outputProject"); -function isAnonymousModel(t: ModularType) { - return t.type === "model" && t.name === ""; -} + visitPackageTypes(sdkPackage, emitQueue); + const modelsFilePath = getModelsPath(sourceRoot); + let sourceFile; + if ( + emitQueue.size > 0 && + (sdkPackage.models.length > 0 || sdkPackage.enums.length > 0) + ) { + sourceFile = outputProject.createSourceFile(modelsFilePath); + if (!sourceFile) { + throw new Error(`Failed to create source file at ${modelsFilePath}`); + } + } else { + return; + } -export function isModelWithAdditionalProperties(t: ModularType) { - return t.type === "dict" && t.name !== "Record"; -} + for (const type of emitQueue) { + if (!isGenerableType(type)) { + continue; + } + if (isAzureCoreLroType(type.__raw)) { + continue; + } + if (type.kind === "model") { + if (isAzureCoreErrorType(context.program, type.__raw)) { + continue; + } + if ( + !type.usage || + (type.usage !== undefined && + (type.usage & UsageFlags.Output) !== UsageFlags.Output && + (type.usage & UsageFlags.Input) !== UsageFlags.Input) + ) { + continue; + } + const modelInterface = buildModelInterface(context, type); + if (type.discriminatorProperty) { + modelInterface.properties + ?.filter((p) => { + return p.name === `"${type.discriminatorProperty?.name}"`; + }) + .map((p) => { + p.docs?.push( + `The discriminator possible values: ${Object.keys(type.discriminatedSubtypes ?? {}).join(", ")}` + ); + return p; + }); + } + addDeclaration(sourceFile, modelInterface, type); + const modelPolymorphicType = buildModelPolymorphicType(context, type); + if (modelPolymorphicType) { + addSerializationFunctions(context, type, sourceFile, true); + addDeclaration( + sourceFile, + modelPolymorphicType, + refkey(type, "polymorphicType") + ); + } + addSerializationFunctions(context, type, sourceFile); + } else if (type.kind === "enum") { + if ( + !type.usage || + (type.usage !== undefined && + (type.usage & UsageFlags.Output) !== UsageFlags.Output && + (type.usage & UsageFlags.Input) !== UsageFlags.Input) + ) { + continue; + } + const [enumType, knownValuesEnum] = buildEnumTypes(context, type); + if (isExtensibleEnum(context, type) && !enumType.name.startsWith("_")) { + addDeclaration( + sourceFile, + knownValuesEnum, + refkey(type, "knownValues") + ); + } + if (!enumType.name.startsWith("_")) { + addDeclaration(sourceFile, enumType, type); + } + } else if (type.kind === "union") { + const unionType = buildUnionType(context, type); + addDeclaration(sourceFile, unionType, type); + addSerializationFunctions(context, type, sourceFile); + } else if (type.kind === "dict") { + addSerializationFunctions(context, type, sourceFile); + } else if (type.kind === "array") { + addSerializationFunctions(context, type, sourceFile); + } + } -function getCoreClientErrorType(name: string, coreClientTypes: Set) { - const coreClientType: string = name === "Error" ? "ErrorModel" : name; - coreClientTypes.add(coreClientType); - return coreClientType; + if ( + sourceFile.getInterfaces().length === 0 && + sourceFile.getTypeAliases().length === 0 && + sourceFile.getEnums().length === 0 + ) { + sourceFile.delete(); + return; + } + addImportBySymbol("serializeRecord", sourceFile); + return sourceFile; } -function getCoreLroType(name: string, coreLroTypes: Set) { - const coreLroType = name === "OperationState" ? "CoreOperationStatus" : name; - coreLroTypes.add(coreLroType); - return coreLroType; +export function getModelsPath(sourceRoot: string): string { + return path.join(...[sourceRoot, "models", `models.ts`]); } -// ====== TYPE EXTRACTION ====== - -function extractModels(codeModel: ModularCodeModel): ModularType[] { - const models = codeModel.types.filter( - (t) => - ((t.type === "model" || t.type === "enum") && - !isAzureCoreErrorSdkType(t) && - !isAzureCoreLroSdkType(t) && - !isAnonymousModel(t)) || - isModelWithAdditionalProperties(t) +function addSerializationFunctions( + context: SdkContext, + type: SdkType, + sourceFile: SourceFile, + skipDiscriminatedUnion = false +) { + const serializationFunction = buildModelSerializer( + context, + type, + skipDiscriminatedUnion ); - - for (const model of codeModel.types) { - if (model.type === "combined") { - for (const unionModel of model.types ?? []) { - if (unionModel.type === "model") { - models.push(unionModel); - } - } - } + if ( + serializationFunction && + typeof serializationFunction !== "string" && + serializationFunction.name && + !sourceFile.getFunction(serializationFunction.name) + ) { + addDeclaration( + sourceFile, + serializationFunction, + refkey(type, "serializer") + ); } - return models; -} - -/** - * Extracts all the aliases from the code model - * 1. alias from polymorphic base model, where we need to use typescript union to combine all the sub models - * 2. alias from unions, where we also need to use typescript union to combine all the union variants - */ -export function extractAliases(codeModel: ModularCodeModel): ModularType[] { - const models = codeModel.types.filter( - (t) => - ((t.type === "model" || t.type === "combined") && - t.alias && - t.aliasType) || - (isModelWithAdditionalProperties(t) && t.alias && t.aliasType) + const deserializationFunction = buildModelDeserializer( + context, + type, + skipDiscriminatedUnion ); - return models; + if ( + deserializationFunction && + typeof deserializationFunction !== "string" && + deserializationFunction.name && + !sourceFile.getFunction(deserializationFunction.name) + ) { + addDeclaration( + sourceFile, + deserializationFunction, + refkey(type, "deserializer") + ); + } } -// ====== TYPE BUILDERS ====== -function buildEnumModel( - model: ModularType -): OptionalKind { - const valueType = model.valueType?.type === "string" ? "string" : "number"; - return { - name: model.name!, + +function buildUnionType( + context: SdkContext, + type: SdkUnionType +): TypeAliasDeclarationStructure { + const unionDeclaration: TypeAliasDeclarationStructure = { + kind: StructureKind.TypeAlias, + name: normalizeModelName(context, type), isExported: true, - docs: [...getDocsFromDescription(model.description)], - type: buildEnumType() + type: type.variantTypes + .map((v) => getTypeExpression(context, v)) + .join(" | ") }; - function buildEnumType() { - return model.isFixed || !model.isNonExhaustive - ? getEnumValues(" | ") - : valueType; - } + unionDeclaration.docs = [type.doc ?? `Alias for ${unionDeclaration.name}`]; - function getEnumValues(separator: string = ", ") { - const splitWord = valueType === "string" ? `"` : ``; - return (model.values ?? []) - .map((v) => `${splitWord}${v.value}${splitWord}`) - .join(separator); - } + return unionDeclaration; } -type InterfaceStructure = OptionalKind & { - extends: string[]; -}; - -export function buildModelInterface( - model: ModularType, - cache: { coreClientTypes: Set; coreLroTypes: Set } -): InterfaceStructure { - const modelProperties = model.properties ?? []; - const modelInterface = { - name: model.alias ?? model.name ?? "FIXMYNAME", +function buildEnumTypes( + context: SdkContext, + type: SdkEnumType +): [TypeAliasDeclarationStructure, EnumDeclarationStructure] { + const enumDeclaration: EnumDeclarationStructure = { + kind: StructureKind.Enum, + name: `Known${normalizeModelName(context, type)}`, isExported: true, - docs: getDocsFromDescription(model.description), - extends: [] as string[], - properties: (modelProperties ?? []).map((p) => { - const propertyMetadata = getType(p.type, p.format); - let propertyTypeName = propertyMetadata.name; - if (isAzureCoreErrorSdkType(p.type)) { - propertyTypeName = getCoreClientErrorType( - propertyTypeName, - cache.coreClientTypes - ); - } - if (isAzureCoreLroSdkType(p.type)) { - propertyTypeName = getCoreLroType(propertyTypeName, cache.coreLroTypes); - } - - return { - name: `"${p.clientName}"`, - docs: getDocsFromDescription(p.description), - hasQuestionToken: p.optional, - isReadonly: p.readonly, - type: propertyTypeName - }; - }) + members: type.values.map(emitEnumMember) }; - return modelInterface; -} - -// ====== MAIN FUNCTIONS ====== -/** - * This function creates the file containing all the models defined in TypeSpec - */ -export function buildModels( - subClient: Client, - codeModel: ModularCodeModel -): SourceFile | undefined { - // We are generating both models and enums here - const coreClientTypes = new Set(); - const coreLroTypes = new Set(); - // filter out the models/enums that are anonymous - const models = extractModels(codeModel).filter((m) => !!m.name); - const aliases = extractAliases(codeModel); - // Skip to generate models.ts if there is no any models - if (models.length === 0 && aliases.length === 0) { - return; - } - const modelsFile = codeModel.project.createSourceFile( - getModularModelFilePath(codeModel, subClient) - ); - for (const model of models) { - if (model.type === "enum") { - if (modelsFile.getTypeAlias(model.name!)) { - // If the enum is already defined, we don't need to do anything - continue; - } - const enumAlias = buildEnumModel(model); - - if (model.isNonExhaustive && model.name) { - modelsFile.addEnum({ - name: `Known${model.name}`, - isExported: true, - members: - model.values?.map((v) => ({ - name: v.name, - value: v.value, - docs: v.description ? [v.description] : [v.name] - })) ?? [], - docs: [ - `Known values of {@link ${model.name}} that the service accepts.` - ] - }); - const description = getExtensibleEnumDescription(model); - if (description) { - enumAlias.docs = [description]; - } - } - modelsFile.addTypeAlias(enumAlias); - } else { - const modelInterface = buildModelInterface(model, { - coreClientTypes, - coreLroTypes - }); - - model.parents?.forEach((p) => - modelInterface.extends.push(p.alias ?? getType(p, p.format).name) - ); - if (isModelWithAdditionalProperties(model)) { - addExtendedDictInfo( - model, - modelInterface, - codeModel.modularOptions.compatibilityMode - ); - } - - if (!modelsFile.getInterface(modelInterface.name)) { - modelsFile.addInterface(modelInterface); - } - - // Generate a serializer function next to each model - const serializerFunction = buildModelSerializer( - model, - codeModel.runtimeImports - ); - - if ( - serializerFunction && - !modelsFile.getFunction(toCamelCase(modelInterface.name + "Serializer")) - ) { - modelsFile.addStatements(serializerFunction); - } - addImportBySymbol("serializeRecord", modelsFile); - modelsFile.fixUnusedIdentifiers(); - } - } - - const projectRootFromModels = codeModel.clients.length > 1 ? "../.." : "../"; - addImportsToFiles(codeModel.runtimeImports, modelsFile, { - serializerHelpers: path.posix.join( - projectRootFromModels, - "helpers", - "serializerHelpers.js" - ) - }); - - if (coreClientTypes.size > 0) { - modelsFile.addImportDeclarations([ - { - moduleSpecifier: getImportSpecifier( - "restClient", - codeModel.runtimeImports - ), - namedImports: Array.from(coreClientTypes) - } - ]); - } + const enumAsUnion: TypeAliasDeclarationStructure = { + kind: StructureKind.TypeAlias, + name: normalizeModelName(context, type), + isExported: true, + type: !isExtensibleEnum(context, type) + ? type.values.map((v) => getTypeExpression(context, v)).join(" | ") + : getTypeExpression(context, type.valueType) + }; - if (coreLroTypes.size > 0) { - modelsFile.addImportDeclarations([ - { - moduleSpecifier: getImportSpecifier( - "azureCoreLro", - codeModel.runtimeImports - ), - namedImports: Array.from(coreLroTypes).map((t) => - t === "CoreOperationStatus" - ? "OperationStatus as CoreOperationStatus" - : t - ) - } - ]); - } + const docs = type.doc ? type.doc : "Type of " + enumAsUnion.name; + enumAsUnion.docs = + isExtensibleEnum(context, type) && type.doc + ? [getExtensibleEnumDescription(type) ?? docs] + : [docs]; + enumDeclaration.docs = type.doc + ? [type.doc] + : [`Known values of {@link ${type.name}} that the service accepts.`]; - aliases.forEach((alias) => { - modelsFile.addTypeAlias(buildModelTypeAlias(alias)); - if (!models.includes(alias)) { - // Generate a serializer function next to each model - const serializerFunction = buildModelSerializer( - alias, - codeModel.runtimeImports - ); - if (serializerFunction) { - modelsFile.addStatements(serializerFunction); - } - } - }); - return modelsFile; + return [enumAsUnion, enumDeclaration]; } -function getExtensibleEnumDescription(model: ModularType): string | undefined { - if (!(model.isNonExhaustive && model.name && model.values)) { +function getExtensibleEnumDescription(model: SdkEnumType): string | undefined { + if (model.isFixed && model.name && model.values) { return; } const valueDescriptions = model.values - .map((v) => `**${v.value}**${v.description ? `: ${v.description}` : ""}`) + .map((v) => `**${v.value}**${v.doc ? `: ${v.doc}` : ""}`) .join(` \\\n`) // Escape the character / to make sure we don't incorrectly announce a comment blocks /** */ .replace(/^\//g, "\\/") @@ -319,31 +288,87 @@ function getExtensibleEnumDescription(model: ModularType): string | undefined { const enumLink = `{@link Known${model.name}} can be used interchangeably with ${model.name},\n this enum contains the known values that the service supports.`; return [ - `${model.description} \\`, + `${model.doc} \\`, enumLink, `### Known values supported by the service`, valueDescriptions ].join(" \n"); } +function emitEnumMember(member: SdkEnumValueType): EnumMemberStructure { + const memberStructure: EnumMemberStructure = { + kind: StructureKind.EnumMember, + name: member.name, + value: member.value + }; + + if (member.doc) { + memberStructure.docs = [member.doc]; + } + + return memberStructure; +} + +export function buildModelInterface( + context: SdkContext, + type: SdkModelType +): InterfaceDeclarationStructure { + const interfaceStructure = { + kind: StructureKind.Interface, + name: normalizeModelName(context, type, NameType.Interface, true), + isExported: true, + properties: type.properties + .filter((p) => !isMetadata(context.program, p.__raw!)) + .map((p) => { + return buildModelProperty(context, p); + }) + } as InterfaceStructure; + + if (type.baseModel) { + const parentReference = getModelExpression(context, type.baseModel, { + skipPolymorphicUnion: true + }); + interfaceStructure.extends = [parentReference]; + } + + if (type.additionalProperties) { + addExtendedDictInfo(context, type, interfaceStructure); + } + + interfaceStructure.docs = [ + type.doc ?? "model interface " + interfaceStructure.name + ]; + + return interfaceStructure; +} + function addExtendedDictInfo( - model: ModularType, - modelInterface: InterfaceStructure, - compatibilityMode: boolean = false + context: SdkContext, + model: SdkModelType, + modelInterface: InterfaceStructure ) { + const additionalPropertiesType = model.additionalProperties + ? getTypeExpression(context, model.additionalProperties) + : undefined; if ( (model.properties && model.properties.length > 0 && - model.elementType && + model.additionalProperties && model.properties?.every((p) => { - return getType(model.elementType!)?.name.includes(getType(p.type).name); + return additionalPropertiesType?.includes( + getTypeExpression(context, p.type) + ); })) || - (model.properties?.length === 0 && model.elementType) + (model.properties?.length === 0 && model.additionalProperties) ) { - modelInterface.extends.push( - `Record` - ); - } else if (compatibilityMode) { + modelInterface.extends = [ + ...(modelInterface.extends ?? []), + `Record` + ]; + } else if (context.rlcOptions?.compatibilityMode) { + if (!modelInterface.extends) { + modelInterface.extends = []; + } modelInterface.extends.push(`Record`); } else { modelInterface.properties?.push({ @@ -351,61 +376,250 @@ function addExtendedDictInfo( docs: ["Additional properties"], hasQuestionToken: true, isReadonly: false, - type: `Record` + type: `Record` }); } } -export function buildModelTypeAlias(model: ModularType) { - return { - name: model.name!, +export function normalizeModelName( + context: SdkContext, + type: + | SdkModelType + | SdkEnumType + | SdkUnionType + | SdkArrayType + | SdkDictionaryType, + nameType: NameType = NameType.Interface, + skipPolymorphicUnionSuffix = false +): string { + if (type.kind === "array") { + return `Array<${normalizeModelName(context, type.valueType as any, nameType)}>`; + } else if (type.kind === "dict") { + return `Record`; + } + if (type.kind !== "model" && type.kind !== "enum" && type.kind !== "union") { + return getTypeExpression(context, type); + } + const segments = type.crossLanguageDefinitionId.split("."); + segments.pop(); + segments.shift(); + segments.filter((segment) => segment !== context.sdkPackage.rootNamespace); + let unionSuffix = ""; + if (!skipPolymorphicUnionSuffix) { + if (type.kind === "model" && isDiscriminatedUnion(type)) { + unionSuffix = "Union"; + } + } + const namespacePrefix = context.rlcOptions?.enableModelNamespace + ? segments.join("") + : ""; + let internalModelPrefix = ""; + if (type.__raw && type.__raw.kind === "Model") { + // TODO: this is temporary until we have a better way in tcgc to extract the paged metadata + // issue link https://github.com/Azure/typespec-azure/issues/1464 + const page = extractPagedMetadataNested(context.program, type.__raw!); + internalModelPrefix = + page && page.itemsSegments && page.itemsSegments.length > 0 ? "_" : ""; + } + if (type.isGeneratedName) { + internalModelPrefix = "_"; + } + return `${internalModelPrefix}${normalizeName(namespacePrefix + type.name + unionSuffix, nameType, true)}`; +} + +function buildModelPolymorphicType(context: SdkContext, type: SdkModelType) { + if (!type.discriminatedSubtypes) { + return undefined; + } + + const discriminatedSubtypes = Object.values(type.discriminatedSubtypes); + + const typeDeclaration: TypeAliasDeclarationStructure = { + kind: StructureKind.TypeAlias, + name: `${normalizeName(type.name, NameType.Interface)}Union`, isExported: true, - docs: ["Alias for " + model.name], - type: model.aliasType! + type: discriminatedSubtypes + .filter((p) => { + return ( + p.usage !== undefined && + ((p.usage & UsageFlags.Output) === UsageFlags.Output || + (p.usage & UsageFlags.Input) === UsageFlags.Input) + ); + }) + .map((t) => getTypeExpression(context, t)) + .join(" | ") + }; + typeDeclaration.docs = [`Alias for ${typeDeclaration.name}`]; + + typeDeclaration.type += ` | ${getModelExpression(context, type, { + skipPolymorphicUnion: true + })}`; + return typeDeclaration; +} + +function buildModelProperty( + context: SdkContext, + property: SdkModelPropertyType +): PropertySignatureStructure { + const propertyStructure: PropertySignatureStructure = { + kind: StructureKind.PropertySignature, + name: `"${property.name}"`, + type: getTypeExpression(context, property.type), + hasQuestionToken: property.optional, + isReadonly: isReadOnly(property as SdkBodyModelPropertyType) }; + + if (property.doc) { + propertyStructure.docs = [property.doc]; + } + + return propertyStructure; } -export function buildModelsOptions( - client: Client, - codeModel: ModularCodeModel +export function visitPackageTypes( + sdkPackage: SdkHttpPackage, + emitQueue: Set ) { - const modelOptionsFile = codeModel.project.createSourceFile( - path.join( - codeModel.modularOptions.sourceRoot, - client.subfolder ?? "", - `models/options.ts` - ), - undefined, - { - overwrite: true + // Add all models in the package to the emit queue + for (const model of sdkPackage.models) { + visitType(model, emitQueue); + } + + // Add all enums to the queue + for (const enumType of sdkPackage.enums) { + if (!emitQueue.has(enumType)) { + emitQueue.add(enumType); } + } + + // Visit the clients to discover all models + for (const client of sdkPackage.clients) { + visitClient(client, emitQueue); + } +} + +function visitClient( + client: SdkClientType, + emitQueue: Set +) { + // Comment this out for now, as client initialization is not used in the generated code + // visitType(client.initialization, emitQueue); + client.methods.forEach((method) => visitClientMethod(method, emitQueue)); +} + +function visitClientMethod( + method: SdkMethod, + emitQueue: Set +) { + switch (method.kind) { + case "lro": + case "paging": + case "lropaging": + case "basic": + visitOperation(method.operation, emitQueue); + break; + case "clientaccessor": + method.response.methods.forEach((responseMethod) => + visitClientMethod(responseMethod, emitQueue) + ); + method.parameters.forEach((parameter) => + visitType(parameter.type, emitQueue) + ); + break; + default: + throw new Error(`Unknown sdk method kind: ${(method as any).kind}`); + } +} + +function visitOperation(operation: SdkHttpOperation, emitQueue: Set) { + // Visit the request + visitType(operation.bodyParam?.type, emitQueue); + // Visit the response + operation.exceptions.forEach((exception) => + visitType(exception.type, emitQueue) ); - for (const operationGroup of client.operationGroups) { - operationGroup.operations.forEach((o) => { - buildOperationOptions(o, modelOptionsFile); - }); + + operation.parameters.forEach((parameter) => + visitType(parameter.type, emitQueue) + ); + + operation.responses.forEach((response) => + visitType(response.type, emitQueue) + ); +} + +function visitType(type: SdkType | undefined, emitQueue: Set) { + if (!type) { + return; + } + + if (emitQueue.has(type as any)) { + return; + } + + if (type.kind === "model") { + const externalModel = getExternalModel(type); + if (externalModel) { + return; + } + emitQueue.add(type); + if (type.additionalProperties) { + visitType(type.additionalProperties, emitQueue); + } + for (const property of type.properties) { + if (!emitQueue.has(property.type as any)) { + visitType(property.type, emitQueue); + } + } + if (type.discriminatedSubtypes) { + for (const subType of Object.values(type.discriminatedSubtypes)) { + if (!emitQueue.has(subType as any)) { + visitType(subType, emitQueue); + } + } + } } - modelOptionsFile.addImportDeclarations([ - { - moduleSpecifier: getImportSpecifier( - "restClient", - codeModel.runtimeImports - ), - namedImports: ["OperationOptions"] + if (type.kind === "array") { + if (!emitQueue.has(type.valueType as any)) { + visitType(type.valueType, emitQueue); } - ]); - - modelOptionsFile - .getImportDeclarations() - .filter((id) => { - return ( - id.isModuleSpecifierRelative() && - !id.getModuleSpecifierValue().endsWith(".js") - ); - }) - .map((id) => { - id.setModuleSpecifier(id.getModuleSpecifierValue() + ".js"); - return id; - }); - return modelOptionsFile; + if (!emitQueue.has(type)) { + emitQueue.add(type); + } + } + if (type.kind === "dict") { + if (!emitQueue.has(type.valueType as any)) { + visitType(type.valueType, emitQueue); + } + if (!emitQueue.has(type)) { + emitQueue.add(type); + } + } + if (type.kind === "enum") { + if (!emitQueue.has(type as any)) { + emitQueue.add(type); + } + } + if (type.kind === "nullable") { + if (!emitQueue.has(type as any)) { + emitQueue.add(type); + } + if (!emitQueue.has(type.type as any)) { + visitType(type.type, emitQueue); + } + } + if (type.kind === "union") { + if (!emitQueue.has(type as any)) { + emitQueue.add(type); + } + for (const value of type.variantTypes) { + if (!emitQueue.has(value as any)) { + visitType(value, emitQueue); + } + } + } } diff --git a/packages/typespec-ts/src/modular/emitModelsOptions.ts b/packages/typespec-ts/src/modular/emitModelsOptions.ts new file mode 100644 index 0000000000..b8f514a1e6 --- /dev/null +++ b/packages/typespec-ts/src/modular/emitModelsOptions.ts @@ -0,0 +1,156 @@ +import * as path from "path"; + +import { + Client, + ModularCodeModel, + Type as ModularType +} from "./modularCodeModel.js"; +import { InterfaceDeclarationStructure, OptionalKind } from "ts-morph"; + +import { buildOperationOptions } from "./buildOperations.js"; +import { getDocsFromDescription } from "./helpers/docsHelpers.js"; +import { getImportSpecifier } from "@azure-tools/rlc-common"; +import { getType } from "./helpers/typeHelpers.js"; + +// ====== UTILITIES ====== + +function isAzureCoreErrorSdkType(t: ModularType) { + return ( + t.name && + ["error", "errormodel", "innererror", "errorresponse"].includes( + t.name.toLowerCase() + ) && + t.coreTypeInfo === "ErrorType" + ); +} + +function isAzureCoreLroSdkType(t: ModularType) { + return ( + t.name && + ["operationstate"].includes(t.name.toLowerCase()) && + t.coreTypeInfo === "LroType" + ); +} + +export function isModelWithAdditionalProperties(t: ModularType) { + return t.type === "dict" && t.name !== "Record"; +} + +function getCoreClientErrorType(name: string, coreClientTypes: Set) { + const coreClientType: string = name === "Error" ? "ErrorModel" : name; + coreClientTypes.add(coreClientType); + return coreClientType; +} + +function getCoreLroType(name: string, coreLroTypes: Set) { + const coreLroType = name === "OperationState" ? "CoreOperationStatus" : name; + coreLroTypes.add(coreLroType); + return coreLroType; +} + +/** + * Extracts all the aliases from the code model + * 1. alias from polymorphic base model, where we need to use typescript union to combine all the sub models + * 2. alias from unions, where we also need to use typescript union to combine all the union variants + */ +export function extractAliases(codeModel: ModularCodeModel): ModularType[] { + const models = codeModel.types.filter( + (t) => + ((t.type === "model" || t.type === "combined") && + t.alias && + t.aliasType) || + (isModelWithAdditionalProperties(t) && t.alias && t.aliasType) + ); + return models; +} + +type InterfaceStructure = OptionalKind & { + extends: string[]; +}; + +export function buildModelInterface( + model: ModularType, + cache: { coreClientTypes: Set; coreLroTypes: Set } +): InterfaceStructure { + const modelProperties = model.properties ?? []; + const modelInterface = { + name: model.alias ?? model.name ?? "FIXMYNAME", + isExported: true, + docs: getDocsFromDescription(model.description), + extends: [] as string[], + properties: (modelProperties ?? []).map((p) => { + const propertyMetadata = getType(p.type, p.format); + let propertyTypeName = propertyMetadata.name; + if (isAzureCoreErrorSdkType(p.type)) { + propertyTypeName = getCoreClientErrorType( + propertyTypeName, + cache.coreClientTypes + ); + } + if (isAzureCoreLroSdkType(p.type)) { + propertyTypeName = getCoreLroType(propertyTypeName, cache.coreLroTypes); + } + + return { + name: `"${p.clientName}"`, + docs: getDocsFromDescription(p.description), + hasQuestionToken: p.optional, + isReadonly: p.readonly, + type: propertyTypeName + }; + }) + }; + + return modelInterface; +} + +export function buildModelTypeAlias(model: ModularType) { + return { + name: model.name!, + isExported: true, + docs: ["Alias for " + model.name], + type: model.aliasType! + }; +} + +export function buildApiOptions(client: Client, codeModel: ModularCodeModel) { + const modelOptionsFile = codeModel.project.createSourceFile( + path.join( + codeModel.modularOptions.sourceRoot, + client.subfolder ?? "", + `api/options.ts` + ), + undefined, + { + overwrite: true + } + ); + for (const operationGroup of client.operationGroups) { + operationGroup.operations.forEach((o) => { + buildOperationOptions(o, modelOptionsFile); + }); + } + modelOptionsFile.addImportDeclarations([ + { + moduleSpecifier: getImportSpecifier( + "restClient", + codeModel.runtimeImports + ), + namedImports: ["OperationOptions"] + } + ]); + + modelOptionsFile + .getImportDeclarations() + .filter((id) => { + return ( + id.isModuleSpecifierRelative() && + !id.getModuleSpecifierValue().endsWith(".js") + ); + }) + .map((id) => { + id.setModuleSpecifier(id.getModuleSpecifierValue() + ".js"); + return id; + }); + return modelOptionsFile; +} diff --git a/packages/typespec-ts/src/modular/emitSamples.ts b/packages/typespec-ts/src/modular/emitSamples.ts index aa6c49e1c7..b4a822856d 100644 --- a/packages/typespec-ts/src/modular/emitSamples.ts +++ b/packages/typespec-ts/src/modular/emitSamples.ts @@ -432,7 +432,7 @@ function getParameterValue(value: SdkExampleValue): string { const mapper = buildPropertyNameMapper(value.type); const values = []; const additionalPropertiesValue = - value.kind === "model" ? value?.additionalPropertiesValue ?? {} : {}; + value.kind === "model" ? (value.additionalPropertiesValue ?? {}) : {}; for (const propName in { ...value.value, ...additionalPropertiesValue diff --git a/packages/typespec-ts/src/modular/external-dependencies.ts b/packages/typespec-ts/src/modular/external-dependencies.ts index 4d57bfeee2..9ae5d3d5db 100644 --- a/packages/typespec-ts/src/modular/external-dependencies.ts +++ b/packages/typespec-ts/src/modular/external-dependencies.ts @@ -31,6 +31,11 @@ export const DefaultCoreDependencies: CoreDependencies = { name: "OperationOptions", module: "@typespec/ts-http-runtime" }, + StreamableMethod: { + kind: "externalDependency", + name: "StreamableMethod", + module: "@typespec/ts-http-runtime" + }, PathUncheckedResponse: { kind: "externalDependency", name: "PathUncheckedResponse", @@ -60,6 +65,26 @@ export const DefaultCoreDependencies: CoreDependencies = { kind: "externalDependency", name: "stringToUint8Array", module: "@typespec/ts-http-runtime" + }, + KeyCredential: { + kind: "externalDependency", + name: "KeyCredential", + module: "@typespec/ts-http-runtime" + }, + isKeyCredential: { + kind: "externalDependency", + name: "isKeyCredential", + module: "@typespec/ts-http-runtime" + }, + TokenCredential: { + kind: "externalDependency", + name: "TokenCredential", + module: "@typespec/ts-http-runtime" + }, + ErrorModel: { + kind: "externalDependency", + name: "ErrorModel", + module: "@typespec/ts-http-runtime" } } as const; @@ -99,7 +124,7 @@ export const AzureCoreDependencies: CoreDependencies = { }, Pipeline: { kind: "externalDependency", - module: "@azure-rest/core-client", + module: "@azure/core-rest-pipeline", name: "Pipeline" }, getClient: { @@ -117,6 +142,11 @@ export const AzureCoreDependencies: CoreDependencies = { module: "@azure-rest/core-client", name: "OperationOptions" }, + StreamableMethod: { + kind: "externalDependency", + module: "@azure-rest/core-client", + name: "StreamableMethod" + }, PathUncheckedResponse: { kind: "externalDependency", module: "@azure-rest/core-client", @@ -146,6 +176,26 @@ export const AzureCoreDependencies: CoreDependencies = { kind: "externalDependency", module: "@azure/core-util", name: "stringToUint8Array" + }, + KeyCredential: { + kind: "externalDependency", + name: "KeyCredential", + module: "@azure/core-auth" + }, + isKeyCredential: { + kind: "externalDependency", + name: "isKeyCredential", + module: "@azure/core-auth" + }, + TokenCredential: { + kind: "externalDependency", + name: "TokenCredential", + module: "@azure/core-auth" + }, + ErrorModel: { + kind: "externalDependency", + name: "ErrorModel", + module: "@azure-rest/core-client" } }; diff --git a/packages/typespec-ts/src/modular/helpers/classicalOperationHelpers.ts b/packages/typespec-ts/src/modular/helpers/classicalOperationHelpers.ts index 63c74083b5..dcc75b98d6 100644 --- a/packages/typespec-ts/src/modular/helpers/classicalOperationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/classicalOperationHelpers.ts @@ -33,7 +33,7 @@ export function getClassicalOperation( dpgContext, operationGroup ); - const modularClientName = `${getClientName(client)}Context`; + const modularClientName = `${getClientName(client.tcgcClient)}Context`; const hasClientContextImport = classicFile .getImportDeclarations() .filter((i) => { diff --git a/packages/typespec-ts/src/modular/helpers/clientHelpers.ts b/packages/typespec-ts/src/modular/helpers/clientHelpers.ts index 1923762715..0f37397bc4 100644 --- a/packages/typespec-ts/src/modular/helpers/clientHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/clientHelpers.ts @@ -1,25 +1,94 @@ -import { - getImportSpecifier, - PackageFlavor, - Imports as RuntimeImports -} from "@azure-tools/rlc-common"; +import { Client, ModularCodeModel } from "../modularCodeModel.js"; import { OptionalKind, ParameterDeclarationStructure, - SourceFile, StatementedNode } from "ts-morph"; -import { Client, ModularCodeModel } from "../modularCodeModel.js"; -import { getClientName } from "./namingHelpers.js"; -import { getType, isCredentialType } from "./typeHelpers.js"; +import { + SdkHttpParameter, + SdkParameter +} from "@azure-tools/typespec-client-generator-core"; + +import { + NameType, + normalizeName, + PackageFlavor +} from "@azure-tools/rlc-common"; import { SdkContext } from "../../utils/interfaces.js"; +import { getClientName } from "./namingHelpers.js"; +import { getTypeExpression } from "../type-expressions/get-type-expression.js"; +import { isCredentialType } from "./typeHelpers.js"; + +interface ClientParameterOptions { + onClientOnly?: boolean; + requiredOnly?: boolean; + optionalOnly?: boolean; +} export function getClientParameters( - client: Client, + _client: Client, + dpgContext: SdkContext, + options: ClientParameterOptions = { + requiredOnly: false, + onClientOnly: false, + optionalOnly: false + } +) { + const client = _client.tcgcClient; + const clientParams: (SdkParameter | SdkHttpParameter)[] = []; + for (const property of client.initialization.properties) { + if ( + property.type.kind === "union" && + property.type.variantTypes[0]?.kind === "endpoint" + ) { + clientParams.push(...property.type.variantTypes[0].templateArguments); + } else if (property.type.kind === "endpoint") { + clientParams.push(...property.type.templateArguments); + } else if (!clientParams.find((p) => p.name === property.name)) { + clientParams.push(property); + } + } + const hasDefaultValue = (p: SdkParameter | SdkHttpParameter) => + p.clientDefaultValue || p.__raw?.defaultValue || p.type.kind === "constant"; + const isRequired = (p: SdkParameter | SdkHttpParameter) => + !p.optional && !hasDefaultValue(p); + const isOptional = (p: SdkParameter | SdkHttpParameter) => + p.optional || hasDefaultValue(p); + const skipCredentials = (p: SdkParameter | SdkHttpParameter) => + p.kind !== "credential"; + const skipMethodParam = (p: SdkParameter | SdkHttpParameter) => + p.kind !== "method" || + (p.kind === "method" && + p.isApiVersionParam && + _client.parameters.find((p) => p.isApiVersion)); + const armSpecific = (p: SdkParameter | SdkHttpParameter) => + !(p.kind === "endpoint" && dpgContext.arm); + const filters = [ + options.requiredOnly ? isRequired : undefined, + dpgContext.rlcOptions?.addCredentials === false + ? skipCredentials + : undefined, + options.optionalOnly ? isOptional : undefined, + options.onClientOnly ? skipMethodParam : undefined, + armSpecific + ]; + const params = clientParams.filter((p) => + filters.every((filter) => !filter || filter(p)) + ); + + return params; +} + +export function getClientParametersDeclaration( + _client: Client, dpgContext: SdkContext, - isClassicalClient = false + options: ClientParameterOptions = { + optionalOnly: false, + requiredOnly: false, + onClientOnly: false + } ): OptionalKind[] { - const { parameters } = client; + const client = _client.tcgcClient; const name = getClientName(client); const optionsParam = { name: "options", @@ -28,81 +97,100 @@ export function getClientParameters( }; const params: OptionalKind[] = [ - ...parameters - .filter( - (p) => - p.optional === false && - p.type.type !== "constant" && - (p.clientDefaultValue === null || p.clientDefaultValue === undefined) - ) - .map>((p) => { - const typeMetadata = getType(p.type, p.format); - let typeName = typeMetadata.name; - if (typeMetadata.nullable) { - typeName = `${typeName} | null`; - } - return { - name: p.clientName, - type: typeName - }; - }) + ...getClientParameters(_client, dpgContext, options).map< + OptionalKind + >((p) => { + const typeExpression = getClientParameterTypeExpression(dpgContext, p); + const name = getClientParameterName(p); + return { + name, + type: typeExpression + }; + }) ]; - // Add promoted client-level parameters for classical clients - if (isClassicalClient && dpgContext.rlcOptions?.azureArm) { - // added subscriptionId parameter for ARM clients - params.push({ - name: "subscriptionId", - type: `string` - }); - } params.push(optionsParam); return params; } +function getClientParameterTypeExpression( + context: SdkContext, + parameter: SdkParameter | SdkHttpParameter +) { + // Special handle to work around the fact that TCGC creates a union type for endpoint. The reason they do this + // is to provide a way for users to either pass the value to fill in the template of the whole endpoint. Basically they are + // inserting a variant with {endpoint}. + // Our emitter allows this through the options.endpoint. + if (parameter.type.kind === "union") { + const endpointVariant = parameter.type.variantTypes.find( + (p) => p.kind === "endpoint" + ); + if (endpointVariant) { + return getTypeExpression(context, endpointVariant); + } + } + return getTypeExpression(context, parameter.type); +} + +export function getClientParameterName( + parameter: SdkParameter | SdkHttpParameter +) { + // We have been calling this endpointParam, so special handling this here to make sure there are no unexpected side effects + if ( + (parameter.type.kind === "union" && + parameter.type.variantTypes.some((v) => v.kind === "endpoint")) || + ((parameter.kind === "endpoint" || parameter.kind === "path") && + parameter.name.toLowerCase() === "endpoint") + ) { + return "endpointParam"; + } + + return normalizeName(parameter.name, NameType.Parameter, true); +} + export function buildGetClientEndpointParam( context: StatementedNode, + dpgContext: SdkContext, client: Client ): string { // Special case: endpoint URL not defined if (client.url === "") { - const endpointParam = client.parameters.find( - (x) => x.location === "endpointPath" - ); - return `options.endpoint ?? options.baseUrl ?? ${endpointParam?.clientName}`; + const endpointParam = getClientParameters(client, dpgContext, { + onClientOnly: true + }).find((x) => x.kind === "endpoint" || x.kind === "path"); + if (endpointParam) { + return `options.endpoint ?? options.baseUrl ?? String(${getClientParameterName(endpointParam)})`; + } } - const urlParams = client.parameters.filter( - (x) => x.location === "path" || x.location === "endpointPath" + const urlParams = getClientParameters(client, dpgContext).filter( + (x) => x.kind === "endpoint" || x.kind === "path" ); for (const param of urlParams) { + const paramName = getClientParameterName(param); if (param.clientDefaultValue) { const defaultValue = typeof param.clientDefaultValue === "string" ? `"${param.clientDefaultValue}"` : param.clientDefaultValue; context.addStatements( - `const ${param.clientName} = options.${param.clientName} ?? ${defaultValue};` + `const ${paramName} = options.${paramName} ?? ${defaultValue};` ); } else if (param.optional) { - context.addStatements( - `const ${param.clientName} = options.${param.clientName};` - ); + context.addStatements(`const ${paramName} = options.${paramName};`); } } let parameterizedEndpointUrl = client.url; for (const param of urlParams) { parameterizedEndpointUrl = parameterizedEndpointUrl.replace( - `{${param.restApiName}}`, - `\${${param.clientName}}` + `{${param.serializedName}}`, + `\${${getClientParameterName(param)}}` ); } - - context.addStatements( - `const endpointUrl = options.endpoint ?? options.baseUrl ?? \`${parameterizedEndpointUrl}\`` - ); + const endpointUrl = `const endpointUrl = options.endpoint ?? options.baseUrl ?? \`${parameterizedEndpointUrl}\``; + context.addStatements(endpointUrl); return "endpointUrl"; } @@ -215,13 +303,3 @@ export function buildUserAgentOptions( return `{ userAgentPrefix }`; } - -export function importCredential( - runtimeImports: RuntimeImports, - clientSourceFile: SourceFile -): void { - clientSourceFile.addImportDeclaration({ - moduleSpecifier: getImportSpecifier("coreAuth", runtimeImports), - namedImports: ["TokenCredential", "KeyCredential"] - }); -} diff --git a/packages/typespec-ts/src/modular/helpers/namingHelpers.ts b/packages/typespec-ts/src/modular/helpers/namingHelpers.ts index 268cbbf80d..e25577ca0c 100644 --- a/packages/typespec-ts/src/modular/helpers/namingHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/namingHelpers.ts @@ -18,7 +18,9 @@ import { OperationGroup } from "../modularCodeModel.js"; -export function getClientName(client: Client): string { +export function getClientName( + client: SdkClientType +): string { return client.name.replace(/Client$/, ""); } diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 57281a3e3c..27fdb9a3cc 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -12,18 +12,9 @@ import { OptionalKind, ParameterDeclarationStructure } from "ts-morph"; -import { - NameType, - Imports as RuntimeImports, - addImportToSpecifier -} from "@azure-tools/rlc-common"; import { NoTarget, Program } from "@typespec/compiler"; import { PagingHelpers, PollingHelpers } from "../static-helpers-metadata.js"; -import { - SdkContext, - SdkModelType, - SdkType -} from "@azure-tools/typespec-client-generator-core"; +import { SdkContext } from "@azure-tools/typespec-client-generator-core"; import { buildType, getType, isTypeNullable } from "./typeHelpers.js"; import { getClassicalLayerPrefix, getOperationName } from "./namingHelpers.js"; import { @@ -31,54 +22,56 @@ import { hasCollectionFormatInfo } from "../../utils/operationUtil.js"; import { - getDeserializeFunctionName, isNormalUnion, - isPolymorphicUnion, - isSpecialHandledUnion, - isSpecialUnionVariant -} from "../buildSerializeUtils.js"; + isSpecialHandledUnion +} from "../serialization/serializeUtils.js"; import { getDocsFromDescription, getFixmeForMultilineDocs } from "./docsHelpers.js"; -import { toCamelCase, toPascalCase } from "../../utils/casingUtils.js"; +import { toPascalCase } from "../../utils/casingUtils.js"; import { AzurePollingDependencies } from "../external-dependencies.js"; +import { NameType } from "@azure-tools/rlc-common"; +import { buildModelDeserializer } from "../serialization/buildDeserializerFunction.js"; +import { buildModelSerializer } from "../serialization/buildSerializerFunction.js"; +import { refkey } from "../../framework/refkey.js"; import { reportDiagnostic } from "../../lib.js"; import { resolveReference } from "../../framework/reference.js"; import { useDependencies } from "../../framework/hooks/useDependencies.js"; +import { useSdkTypes } from "../../framework/hooks/sdkTypes.js"; +import { isAzureCoreErrorType } from "../../utils/modelUtils.js"; export function getSendPrivateFunction( dpgContext: SdkContext, operation: Operation, - clientType: string, - runtimeImports: RuntimeImports + clientType: string ): OptionalKind { const parameters = getOperationSignatureParameters(operation, clientType); const { name } = getOperationName(operation); + const dependencies = useDependencies(); const functionStatement: OptionalKind = { isAsync: false, isExported: true, name: `_${name}Send`, parameters, - returnType: "StreamableMethod" + returnType: resolveReference(dependencies.StreamableMethod) }; const operationPath = operation.url; const operationMethod = operation.method.toLowerCase(); - const optionalParamName = parameters.filter( - (p) => p.type?.toString().endsWith("OptionalParams") + const optionalParamName = parameters.filter((p) => + p.type?.toString().endsWith("OptionalParams") )[0]?.name; const statements: string[] = []; statements.push( `return context.path("${operationPath}", ${getPathParameters( operation - )}).${operationMethod}({...operationOptionsToRequestParameters(${optionalParamName}), ${getRequestParameters( + )}).${operationMethod}({...${resolveReference(dependencies.operationOptionsToRequestParameters)}(${optionalParamName}), ${getRequestParameters( dpgContext, - operation, - runtimeImports + operation )}});` ); @@ -89,18 +82,20 @@ export function getSendPrivateFunction( } export function getDeserializePrivateFunction( - operation: Operation, - runtimeImports: RuntimeImports + context: SdkContext, + operation: Operation ): OptionalKind { const { name } = getOperationName(operation); + const dependencies = useDependencies(); + const PathUncheckedResponseReference = resolveReference( + dependencies.PathUncheckedResponse + ); const parameters: OptionalKind[] = [ { name: "result", - type: "PathUncheckedResponse" + type: PathUncheckedResponseReference } ]; - addImportToSpecifier("restClient", runtimeImports, "PathUncheckedResponse"); - // TODO: Support LRO + paging operation // https://github.com/Azure/autorest.typescript/issues/2313 const isLroOnly = isLroOnlyOperation(operation); @@ -129,17 +124,18 @@ export function getDeserializePrivateFunction( returnType: `Promise<${returnType.type}>` }; const statements: string[] = []; + const createRestErrorReference = resolveReference( + dependencies.createRestError + ); statements.push( `const expectedStatuses = ${getExpectedStatuses(operation)};` ); statements.push( `if(!expectedStatuses.includes(result.status)){`, - `throw createRestError(result);`, + `throw ${createRestErrorReference}(result);`, "}" ); - addImportToSpecifier("restClient", runtimeImports, "createRestError"); - const deserializedType = isLroOnly ? operation?.lroMetadata?.finalResult : response.type; @@ -159,47 +155,42 @@ export function getDeserializePrivateFunction( ); } - const allParents = deserializedType ? getAllAncestors(deserializedType) : []; - const properties = deserializedType - ? getAllProperties(deserializedType, allParents) - : []; - if ( - deserializedType?.type === "any" || - deserializedType?.type === "dict" || - (deserializedType?.type === "model" && - allParents.some((p) => p.type === "dict")) || - response.isBinaryPayload - ) { - // TODO: Fix this any cast when implementing handling dict. - statements.push(`return ${deserializedRoot} as any`); - } else if ( - deserializedType && - properties.length > 0 && - !deserializedType.aliasType - ) { - statements.push( - `return {`, - getResponseMapping( - deserializedType, - deserializedRoot, - runtimeImports - ).join(","), - `}` + if (deserializedType?.tcgcType) { + const deserializeFunctionName = buildModelDeserializer( + context, + deserializedType.tcgcType, + false, + true ); - } else if (returnType.type === "void" || deserializedType === undefined) { - statements.push(`return;`); - } else { + if (deserializeFunctionName) { + statements.push(`return ${deserializeFunctionName}(${deserializedRoot})`); + } else if (isAzureCoreErrorType(context.program, deserializedType.__raw)) { + statements.push(`return ${deserializedRoot}`); + } else { + statements.push( + `return ${deserializeResponseValue( + context, + deserializedType, + deserializedRoot, + response.isBinaryPayload ? "binary" : deserializedType.format + )}` + ); + } + } else if (returnType.type === "void") { + statements.push("return;"); + } else if (deserializedType) { statements.push( `return ${deserializeResponseValue( + context, deserializedType, deserializedRoot, - runtimeImports, - false, // TODO: Calculate if required - [deserializedType], - deserializedType.format + response.isBinaryPayload ? "binary" : deserializedType.format )}` ); + } else { + statements.push("return;"); } + return { ...functionStatement, statements @@ -471,8 +462,7 @@ export function getOperationOptionsName( */ function getRequestParameters( dpgContext: SdkContext, - operation: Operation, - runtimeImports: RuntimeImports + operation: Operation ): string { if (!operation.parameters) { return ""; @@ -499,7 +489,7 @@ function getRequestParameters( param.location === "body" ) { parametersImplementation[param.location].push({ - paramMap: getParameterMap(param, runtimeImports), + paramMap: getParameterMap(dpgContext, param), param }); } @@ -530,10 +520,7 @@ function getRequestParameters( .map((i) => i.paramMap) .join(",\n")}}`; } else if (operation.bodyParameter !== undefined) { - paramStr = `${paramStr}${buildBodyParameter( - operation.bodyParameter, - runtimeImports - )}`; + paramStr = `${paramStr}${buildBodyParameter(dpgContext, operation.bodyParameter)}`; } return paramStr; } @@ -564,118 +551,32 @@ function buildHeaderParameter( } function buildBodyParameter( - bodyParameter: BodyParameter | undefined, - runtimeImports: RuntimeImports + context: SdkContext, + bodyParameter: BodyParameter | undefined ) { - if (!bodyParameter) { + if (!bodyParameter || !bodyParameter.type.tcgcType) { return ""; } - - const allParents = getAllAncestors(bodyParameter.type); - if ( - bodyParameter.type.type === "model" && - !bodyParameter.type.aliasType && - !allParents.some((p) => p.type === "dict") - ) { - const { propertiesStr: bodyParts } = getRequestModelMapping( - bodyParameter.type, - bodyParameter.clientName, - runtimeImports, - [bodyParameter.type] - ); - - if (bodyParameter && bodyParts.length > 0) { - const optionalBody = bodyParameter.optional - ? `${bodyParameter.clientName} === undefined ? ${bodyParameter.clientName} : ` - : ""; - return `\nbody: ${optionalBody}{${bodyParts.join(",\n")}},`; - } else if (bodyParameter && bodyParts.length === 0) { - return `\nbody: ${bodyParameter.clientName},`; - } - } else if (isDiscriminatedUnion(bodyParameter.type.tcgcType)) { - const serializerName = toCamelCase(`${bodyParameter.type.name}Serializer`); - addImportToSpecifier("modularModel", runtimeImports, serializerName); - return `\nbody: ${serializerName}(${bodyParameter.clientName}),`; - } else if ( - (bodyParameter.type.type === "model" && - (bodyParameter.type.aliasType || - allParents.some((p) => p.type === "dict"))) || - bodyParameter.type.type === "dict" - ) { - const elementSerializerName = - bodyParameter.type.elementType?.type === "model" - ? toCamelCase(`${bodyParameter.type.elementType.name}Serializer`) - : ""; - let modelSerializerName = ""; - - if (bodyParameter.type.type !== "dict") { - modelSerializerName = toCamelCase(`${bodyParameter.type.name}Serializer`); - } - if (modelSerializerName) { - return `\nbody: ${modelSerializerName}(${bodyParameter.clientName}),`; - } else { - // Need to do this so that Records are compatible with additional properties of other types - // this should check for compatibility mode once we support the additionalProperties property - return `\nbody: serializeRecord(${bodyParameter.clientName} as any, ${elementSerializerName}) as any,`; - } - } - - if (bodyParameter.type.type === "list") { - if ( - bodyParameter.type.elementType?.type === "model" && - !bodyParameter.type.elementType.aliasType - ) { - const { propertiesStr: bodyParts, directAssignment } = - getRequestModelMapping( - bodyParameter.type.elementType, - "p", - runtimeImports, - [bodyParameter.type.elementType] - ); - const mapBody = - directAssignment === true - ? bodyParts.join(", ") - : `{ ${bodyParts.join(", ")} }`; - let bodyElementStatement = ""; - if ( - isTypeNullable(bodyParameter.type.elementType) || - bodyParameter.type.elementType.optional - ) { - bodyElementStatement = `!p ? p : `; - } - return `\nbody: (${bodyParameter.clientName} ?? []).map((p) => { - return ${bodyElementStatement}${mapBody}; - }),`; - } - return `\nbody: ${bodyParameter.clientName},`; - } - - if ( - bodyParameter.type.type === "byte-array" && - !bodyParameter.isBinaryPayload - ) { - const dependencies = useDependencies(); - const uint8ArrayToStringReference = resolveReference( - dependencies.uint8ArrayToString - ); - return bodyParameter.optional - ? `body: typeof ${bodyParameter.clientName} === 'string' - ? ${uint8ArrayToStringReference}(${ - bodyParameter.clientName - }, "${getEncodingFormat(bodyParameter)}") - : ${bodyParameter.clientName}` - : `body: ${uint8ArrayToStringReference}(${ - bodyParameter.clientName - }, "${getEncodingFormat(bodyParameter)}")`; - } else if (bodyParameter.isBinaryPayload) { - return `\nbody: ${bodyParameter.clientName},`; - } - - if (bodyParameter) { - return `\nbody: ${bodyParameter.clientName},`; + const serializerFunctionName = buildModelSerializer( + context, + bodyParameter.type.tcgcType!, + false, + true + ); + const nullOrUndefinedPrefix = getPropertySerializationPrefix(bodyParameter); + if (serializerFunctionName) { + return `\nbody: ${nullOrUndefinedPrefix}${serializerFunctionName}(${bodyParameter.clientName}),`; + } else if (isAzureCoreErrorType(context.program, bodyParameter.type.__raw)) { + return `\nbody: ${nullOrUndefinedPrefix}${bodyParameter.clientName},`; } - - return ""; + const serializedBody = serializeRequestValue( + context, + bodyParameter.type, + bodyParameter.clientName, + !bodyParameter.optional, + bodyParameter.isBinaryPayload ? "binary" : bodyParameter.format + ); + return `\nbody: ${serializedBody === bodyParameter.clientName ? "" : nullOrUndefinedPrefix}${serializedBody},`; } function getEncodingFormat(type: { format?: string }) { @@ -692,30 +593,30 @@ function getEncodingFormat(type: { format?: string }) { * This function helps with renames, translating client names to rest api names */ export function getParameterMap( - param: Parameter | Property, - runtimeImports: RuntimeImports + context: SdkContext, + param: Parameter | Property ): string { if (isConstant(param)) { return getConstantValue(param); } if (hasCollectionFormatInfo((param as any).location, (param as any).format)) { - return getCollectionFormat(param as Parameter, runtimeImports); + return getCollectionFormat(context, param as Parameter); } // if the parameter or property is optional, we don't need to handle the default value if (isOptional(param)) { - return getOptional(param, runtimeImports); + return getOptional(context, param); } if (isRequired(param)) { - return getRequired(param, runtimeImports); + return getRequired(context, param); } throw new Error(`Parameter ${param.clientName} is not supported`); } -function getCollectionFormat(param: Parameter, runtimeImports: RuntimeImports) { +function getCollectionFormat(context: SdkContext, param: Parameter) { const collectionInfo = getCollectionFormatHelper( param.location, param.format ?? "" @@ -727,22 +628,20 @@ function getCollectionFormat(param: Parameter, runtimeImports: RuntimeImports) { const additionalParam = isMulti ? `, "${param.restApiName}"` : ""; if (!param.optional) { return `"${param.restApiName}": ${collectionInfo}(${serializeRequestValue( + context, param.type, param.clientName, - runtimeImports, true, - [param.type], param.format )}${additionalParam})`; } return `"${param.restApiName}": options?.${ param.clientName } !== undefined ? ${collectionInfo}(${serializeRequestValue( + context, param.type, "options?." + param.clientName, - runtimeImports, false, - [param.type], param.format )}${additionalParam}): undefined`; } @@ -777,22 +676,20 @@ function isRequired(param: Parameter | Property): param is RequiredType { return !param.optional; } -function getRequired(param: RequiredType, runtimeImports: RuntimeImports) { +function getRequired(context: SdkContext, param: RequiredType) { if (param.type.type === "model") { const { propertiesStr } = getRequestModelMapping( + context, param.type, - param.clientName, - runtimeImports, - [param.type] + param.clientName ); return `"${param.restApiName}": { ${propertiesStr.join(",")} }`; } return `"${param.restApiName}": ${serializeRequestValue( + context, param.type, param.clientName, - runtimeImports, true, - [param.type], param.format === undefined && (param as Parameter).location === "header" && param.type.type === "datetime" @@ -832,13 +729,12 @@ function isOptional(param: Parameter | Property): param is OptionalType { return Boolean(param.optional); } -function getOptional(param: OptionalType, runtimeImports: RuntimeImports) { +function getOptional(context: SdkContext, param: OptionalType) { if (param.type.type === "model") { const { propertiesStr, directAssignment } = getRequestModelMapping( + context, param.type, - "options?." + param.clientName + "?", - runtimeImports, - [param.type] + "options?." + param.clientName + "?" ); const serializeContent = directAssignment === true @@ -857,11 +753,10 @@ function getOptional(param: OptionalType, runtimeImports: RuntimeImports) { }`; } return `"${param.restApiName}": ${serializeRequestValue( + context, param.type, `options?.${param.clientName}`, - runtimeImports, false, - [param.type], param.format === undefined && (param as Parameter).location === "header" && param.type.type === "datetime" @@ -931,10 +826,9 @@ interface RequestModelMappingResult { directAssignment?: boolean; } export function getRequestModelMapping( + context: SdkContext, modelPropertyType: Type, - propertyPath: string = "body", - runtimeImports: RuntimeImports, - typeStack: Type[] = [] + propertyPath: string = "body" ): RequestModelMappingResult { const props: string[] = []; const allParents = getAllAncestors(modelPropertyType); @@ -943,123 +837,42 @@ export function getRequestModelMapping( if (properties.length <= 0) { return { propertiesStr: [] }; } - - let serializerName = - "name" in modelPropertyType && modelPropertyType.name - ? `${toCamelCase(modelPropertyType.name)}Serializer` - : undefined; - - if (isSpecialHandledUnion(modelPropertyType)) { - serializerName = - serializerName ?? - getDeserializeFunctionName(modelPropertyType, "serialize"); - const definition = `${serializerName}(${propertyPath.replace(/\?$/, "")})`; - props.push(definition); - return { propertiesStr: props, directAssignment: true }; - } for (const property of properties) { if (property.readonly) { continue; } + const dot = propertyPath.endsWith("?") ? "." : ""; + + const propertyPathWithDot = `${propertyPath ? `${propertyPath}${dot}` : `${dot}`}`; const nullOrUndefinedPrefix = getPropertySerializationPrefix( property, propertyPath ); - const propertyFullName = getPropertyFullName(property, propertyPath); - if (property.type.type === "model") { - let definition; - if (property.type.coreTypeInfo === "ErrorType") { - definition = `"${property.restApiName}": ${getNullableCheck( - propertyFullName, - property.type - )} ${ - !property.optional ? "" : `!${propertyFullName} ? undefined :` - } ${propertyFullName}`; - } else if (typeStack.includes(property.type)) { - const isSpecialModel = isSpecialUnionVariant(property.type); - definition = `"${property.restApiName}": ${ - !property.optional - ? `${propertyFullName}${isSpecialModel ? " as any" : ""}` - : `!${propertyFullName} ? undefined : ${propertyFullName}${ - isSpecialModel ? " as any" : "" - }` - }`; - } else if (isPolymorphicUnion(property.type)) { - const deserializeFunctionName = property.type.name - ? `${toCamelCase(property.type.name)}Serializer` - : getDeserializeFunctionName(property.type, "serialize"); - definition = `"${property.restApiName}": ${nullOrUndefinedPrefix}${deserializeFunctionName}(${propertyFullName})`; - } else { - if (property.type.name) { - serializerName = `${toCamelCase(property.type.name)}Serializer`; - definition = `"${property.restApiName}": ${nullOrUndefinedPrefix}${serializerName}(${propertyPath}.${property.clientName})`; - } else { - const { propertiesStr, directAssignment } = getRequestModelMapping( - property.type, - `${propertyPath}.${property.clientName}${ - property.optional ? "?" : "" - }`, - runtimeImports, - [...typeStack, property.type] - ); - - const serializeContent = - directAssignment === true - ? propertiesStr.join(",") - : `{${propertiesStr.join(",")}}`; - definition = `"${property.restApiName}": ${getNullableCheck( - propertyFullName, - property.type - )} ${ - !property.optional ? "" : `!${propertyFullName} ? undefined :` - } ${serializeContent}`; - } - } - - props.push(definition); - } else if (typeStack.includes(property.type)) { - const isSpecialModel = isSpecialUnionVariant(property.type); - const definition = `"${property.restApiName}": ${ - !property.optional - ? `${propertyFullName}${isSpecialModel ? " as any" : ""}` - : `!${propertyFullName} ? undefined : ${propertyFullName}${ - isSpecialModel ? " as any" : "" - }` - }`; - props.push(definition); - } else if (property.type.type === "dict") { - const modelName = property.type.elementType?.name; - serializerName = modelName ? `${toCamelCase(modelName)}Serializer` : ""; - // definition = `"${property.restApiName}": ${nullOrUndefinedPrefix}${serializerName}(${propertyPath}.${property.clientName})`; - const statement = `"${property.restApiName}": ${nullOrUndefinedPrefix} serializeRecord(${propertyFullName} as any, ${serializerName}) as any`; - // addImportToSpecifier( - // "serializerHelpers", - // runtimeImports, - // "serializeRecord" - // ); - - addImportToSpecifier("modularModel", runtimeImports, serializerName); - props.push(statement); - } else if (modelPropertyType.type === "enum") { + const propertyFullName = getPropertyFullName(property, propertyPathWithDot); + const serializeFunctionName = buildModelSerializer( + context, + property.type.tcgcType!, + false, + true + ); + if (serializeFunctionName) { props.push( - `"${property.restApiName}": ${nullOrUndefinedPrefix}${propertyPath}.${property.clientName}` + `"${property.restApiName}": ${nullOrUndefinedPrefix}${serializeFunctionName}(${propertyFullName})` ); - } else { - const dot = propertyPath.endsWith("?") ? "." : ""; - const clientValue = `${ - propertyPath ? `${propertyPath}${dot}` : `${dot}` - }["${property.clientName}"]`; + } else if (isAzureCoreErrorType(context.program, property.type.__raw)) { props.push( - `"${property.restApiName}": ${serializeRequestValue( - property.type, - clientValue, - runtimeImports, - !property.optional, - [...typeStack, property.type], - property.format - )}` + `"${property.restApiName}": ${nullOrUndefinedPrefix}${propertyFullName}` ); + } else { + const serializedValue = serializeRequestValue( + context, + property.type, + propertyFullName, + !property.optional, + property.format + ); + props.push(`"${property.restApiName}": ${serializedValue}`); } } @@ -1071,246 +884,78 @@ export function getRequestModelMapping( * extracting properties from body and headers and building the HLC response object */ export function getResponseMapping( + context: SdkContext, type: Type, - propertyPath: string = "result.body", - runtimeImports: RuntimeImports, - typeStack: Type[] = [] + propertyPath: string = "result.body" ) { const allParents = getAllAncestors(type); const properties = getAllProperties(type, allParents) ?? []; - if (typeStack.length <= 0) { - typeStack.push(type); - } const props: string[] = []; for (const property of properties) { - // TODO: Do we need to also add headers in the result type? - const propertyFullName = `${propertyPath}.${property.restApiName}`; - if (property.type.type === "model") { - let definition; - if (property.type.coreTypeInfo === "ErrorType") { - definition = `"${property.clientName}": ${getNullableCheck( - propertyFullName, - property.type - )} ${ - !property.optional ? "" : `!${propertyFullName} ? undefined :` - } ${propertyFullName}`; - } else if (typeStack.includes(property.type)) { - const isSpecialModel = isSpecialUnionVariant(property.type); - definition = `"${property.clientName}": ${ - !property.optional - ? `${propertyFullName}${isSpecialModel ? " as any" : ""}` - : `!${propertyFullName} ? undefined : ${propertyFullName}${ - isSpecialModel ? " as any" : "" - }` - }`; - } else if (isSpecialHandledUnion(property.type)) { - const nullOrUndefinedPrefix = getPropertySerializationPrefix( - property, - propertyPath - ); - const deserializeFunctionName = getDeserializeFunctionName( - property.type, - "deserialize" - ); - definition = `"${property.clientName}": ${nullOrUndefinedPrefix}${deserializeFunctionName}(${propertyFullName})`; - } else { - definition = `"${property.clientName}": ${getNullableCheck( - propertyFullName, - property.type - )} ${ - !property.optional ? "" : `!${propertyFullName} ? undefined :` - } {${getResponseMapping( - property.type, - `${propertyPath}.${property.restApiName}${ - property.optional ? "?" : "" - }`, - runtimeImports, - [...typeStack, property.type] - )}}`; - } - - props.push(definition); + const dot = propertyPath.endsWith("?") ? "." : ""; + + const restValue = `${ + propertyPath ? `${propertyPath}${dot}` : `${dot}` + }["${property.restApiName}"]`; + const nullOrUndefinedPrefix = + property.optional || isTypeNullable(property.type) + ? `!${restValue}? ${restValue}: ` + : ""; + const deserializeFunctionName = buildModelDeserializer( + context, + property.type.tcgcType!, + false, + true + ); + if (deserializeFunctionName) { + props.push( + `"${property.clientName}": ${nullOrUndefinedPrefix}${deserializeFunctionName}(${restValue})` + ); + } else if (isAzureCoreErrorType(context.program, property.type.__raw)) { + props.push( + `"${property.clientName}": ${nullOrUndefinedPrefix}${restValue}` + ); } else { - const dot = propertyPath.endsWith("?") ? "." : ""; - const restValue = `${ - propertyPath ? `${propertyPath}${dot}` : `${dot}` - }["${property.restApiName}"]`; - if (typeStack.includes(property.type)) { - const isSpecialModel = isSpecialUnionVariant(property.type); - props.push( - `"${property.clientName}": ${ - !property.optional - ? `${propertyFullName}${isSpecialModel ? " as any" : ""}` - : `!${propertyFullName} ? undefined : ${propertyFullName}${ - isSpecialModel ? " as any" : "" - }` - }` - ); - } else { - props.push( - `"${property.clientName}": ${deserializeResponseValue( - property.type, - restValue, - runtimeImports, - property.optional !== undefined ? !property.optional : false, - [...typeStack, property.type], - property.format - )}` - ); - } + const deserializeValue = deserializeResponseValue( + context, + property.type, + `${propertyPath}${dot}["${property.restApiName}"]`, + property.format + ); + props.push( + `"${property.clientName}": ${deserializeValue === `${propertyPath}${dot}["${property.restApiName}"]` ? "" : nullOrUndefinedPrefix}${deserializeValue}` + ); } } - - typeStack.pop(); return props; } -/** - * This function helps converting strings into JS complex types recursively. - * We need to drill down into Array elements to make sure that the element type is - * deserialized correctly - */ -export function deserializeResponseValue( - type: Type, - restValue: string, - runtimeImports: RuntimeImports, - required: boolean, - typeStack: Type[] = [], - format?: string -): string { - const requiredPrefix = required === false ? `${restValue} === undefined` : ""; - const nullablePrefix = isTypeNullable(type) ? `${restValue} === null` : ""; - const dependencies = useDependencies(); - const stringToUint8ArrayReference = resolveReference( - dependencies.stringToUint8Array - ); - const requiredOrNullablePrefix = - requiredPrefix !== "" && nullablePrefix !== "" - ? `(${requiredPrefix} || ${nullablePrefix})` - : `${requiredPrefix}${nullablePrefix}`; - switch (type.type) { - case "datetime": - return required - ? isTypeNullable(type) - ? `${restValue} === null ? null : new Date(${restValue})` - : `new Date(${restValue})` - : `${restValue} !== undefined? new Date(${restValue}): undefined`; - case "list": { - const prefix = - required && !isTypeNullable(type) - ? `${restValue}` - : `${requiredOrNullablePrefix} ? ${restValue} : ${restValue}`; - if (type.elementType?.type === "model") { - if (!type.elementType.aliasType) { - const elementNullOrUndefinedPrefix = - isTypeNullable(type.elementType) || type.elementType.optional - ? "!p ? p :" - : ""; - return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}{${getResponseMapping( - type.elementType, - "p", - runtimeImports, - [...typeStack, type.elementType] - )}}})`; - } else if (isPolymorphicUnion(type.elementType)) { - let nullOrUndefinedPrefix = ""; - if (isTypeNullable(type.elementType)) { - nullOrUndefinedPrefix = `!p ? p :`; - } - const deserializeFunctionName = getDeserializeFunctionName( - type.elementType, - "deserialize" - ); - return `${prefix}.map((p: any) => ${nullOrUndefinedPrefix}${deserializeFunctionName}(p))`; - } - return `${prefix}`; - } else if ( - needsDeserialize(type.elementType) && - !type.elementType?.aliasType - ) { - return `${prefix}.map((p: any) => ${deserializeResponseValue( - type.elementType!, - "p", - runtimeImports, - true, - [...typeStack, type.elementType!], - type.elementType?.format - )})`; - } else { - return restValue; - } - } - case "byte-array": - if (format !== "binary") { - return `typeof ${restValue} === 'string' - ? ${stringToUint8ArrayReference}(${restValue}, "${format ?? "base64"}") - : ${restValue}`; - } - return restValue; - case "combined": - if (isNormalUnion(type)) { - return `${restValue}`; - } else if (isSpecialHandledUnion(type)) { - const deserializeFunctionName = getDeserializeFunctionName( - type, - "deserialize" - ); - return `${deserializeFunctionName}(${restValue})`; - } else { - return `${restValue} as any`; - } - case "enum": - if (!type.isFixed && !type.isNonExhaustive) { - return `${restValue} as ${type.name}`; - } - return restValue; - case "model": - if (type.discriminator) { - const discriminatorProp = type.properties?.filter( - (p) => p.restApiName === type.discriminator - ); - if ( - discriminatorProp?.length === 1 && - discriminatorProp[0]?.type.isFixed === false && - discriminatorProp[0].type.isNonExhaustive === false - ) { - return `${restValue} as ${type.name}`; - } - } - return restValue; - default: - return restValue; - } -} - /** * This function helps converting strings into JS complex types recursively. * We need to drill down into Array elements to make sure that the element type is * deserialized correctly */ export function serializeRequestValue( + context: SdkContext, type: Type, clientValue: string, - runtimeImports: RuntimeImports, required: boolean, - typeStack: Type[] = [], format?: string ): string { - const requiredPrefix = - required === false ? `${clientValue} === undefined` : ""; - const nullablePrefix = isTypeNullable(type) ? `${clientValue} === null` : ""; - const requiredOrNullablePrefix = - requiredPrefix !== "" && nullablePrefix !== "" - ? `(${requiredPrefix} || ${nullablePrefix})` - : `${requiredPrefix}${nullablePrefix}`; + const getSdkType = useSdkTypes(); + const dependencies = useDependencies(); + const nullOrUndefinedPrefix = + isTypeNullable(type) || type.optional || !required + ? `!${clientValue}? ${clientValue}: ` + : ""; switch (type.type) { case "datetime": switch (type.format ?? format) { case "rfc7231": case "headerDefault": - return `${clientValue}${required ? "" : "?"}.toUTCString()`; + return `${nullOrUndefinedPrefix}${clientValue}.toUTCString()`; case "unixTimestamp": - return `${clientValue}${required ? "" : "?"}.getTime()`; + return `${nullOrUndefinedPrefix}${clientValue}.getTime()`; case "rfc3339": default: return `${getNullableCheck(clientValue, type)} ${clientValue}${ @@ -1318,62 +963,32 @@ export function serializeRequestValue( }.toISOString()`; } case "list": { - const prefix = - required && !isTypeNullable(type) - ? `${clientValue}` - : `${requiredOrNullablePrefix}? ${clientValue}: ${clientValue}`; - if (type.elementType?.type === "model" && !type.elementType.aliasType) { + const prefix = nullOrUndefinedPrefix + clientValue; + if (type.elementType) { const elementNullOrUndefinedPrefix = isTypeNullable(type.elementType) || type.elementType.optional - ? "!p ? p :" + ? "!p ? p : " : ""; - if (!type.elementType.name) { - // If it is an anonymous model we need to serialize inline - const { propertiesStr } = getRequestModelMapping( - type.elementType, - "p", - runtimeImports, - [...typeStack, type.elementType] - ); - - return `${prefix}.map(p => { return ${elementNullOrUndefinedPrefix}{${propertiesStr}}})`; + const serializeFunctionName = buildModelSerializer( + context, + type.elementType.tcgcType!, + false, + true + ); + if (serializeFunctionName) { + return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}${serializeFunctionName}(p)})`; + } else if ( + isAzureCoreErrorType(context.program, type.elementType.__raw) + ) { + return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}p})`; } else { - // When it is not anonymous we can hand it off to the serializer function - return `${prefix}.map(${toCamelCase( - type.elementType.name + "Serializer" - )})`; + return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}${serializeRequestValue(context, type.elementType, "p", true, type.elementType?.format)}})`; } - } else if ( - needsDeserialize(type.elementType) && - !type.elementType?.aliasType - ) { - return `${prefix}.map(p => ${serializeRequestValue( - type.elementType!, - "p", - runtimeImports, - true, - [...typeStack, type.elementType!], - type.elementType?.format - )})`; - } else if ( - type.elementType?.type === "model" && - isPolymorphicUnion(type.elementType) - ) { - let nullOrUndefinedPrefix = ""; - if (isTypeNullable(type.elementType)) { - nullOrUndefinedPrefix = `!p ? p :`; - } - const serializeFunctionName = type.elementType?.name - ? `${toCamelCase(type.elementType.name)}Serializer` - : getDeserializeFunctionName(type.elementType, "serialize"); - return `${prefix}.map(p => ${nullOrUndefinedPrefix}${serializeFunctionName}(p))`; - } else { - return clientValue; } + return clientValue; } case "byte-array": if (format !== "binary") { - const dependencies = useDependencies(); const uint8ArrayToStringReference = resolveReference( dependencies.uint8ArrayToString ); @@ -1384,18 +999,18 @@ export function serializeRequestValue( )} ${uint8ArrayToStringReference}(${clientValue}, "${ getEncodingFormat({ format }) ?? "base64" }")` - : `${clientValue} !== undefined ? ${uint8ArrayToStringReference}(${clientValue}, "${ + : `${nullOrUndefinedPrefix} ${uint8ArrayToStringReference}(${clientValue}, "${ getEncodingFormat({ format }) ?? "base64" - }"): undefined`; + }")`; } return clientValue; case "combined": if (isNormalUnion(type)) { return `${clientValue}`; } else if (isSpecialHandledUnion(type)) { - const serializeFunctionName = type.name - ? `${toCamelCase(type.name)}Serializer` - : getDeserializeFunctionName(type, "serialize"); + const sdkType = getSdkType(type.__raw!); + const serializerRefkey = refkey(sdkType, "serializer"); + const serializeFunctionName = resolveReference(serializerRefkey); return `${serializeFunctionName}(${clientValue})`; } else { return `${clientValue} as any`; @@ -1408,13 +1023,83 @@ export function serializeRequestValue( } } -function needsDeserialize(type?: Type) { - return ( - type?.type === "datetime" || - type?.type === "model" || - type?.type === "list" || - type?.type === "byte-array" +/** + * This function helps converting strings into JS complex types recursively. + * We need to drill down into Array elements to make sure that the element type is + * deserialized correctly + */ +export function deserializeResponseValue( + context: SdkContext, + type: Type, + restValue: string, + format?: string +): string { + const dependencies = useDependencies(); + const stringToUint8ArrayReference = resolveReference( + dependencies.stringToUint8Array ); + const nullOrUndefinedPrefix = + isTypeNullable(type) || type.optional + ? `!${restValue}? ${restValue}: ` + : ""; + switch (type.type) { + case "datetime": + return `${nullOrUndefinedPrefix} new Date(${restValue})`; + case "list": { + const prefix = nullOrUndefinedPrefix + restValue; + let elementNullOrUndefinedPrefix = ""; + if ( + type.elementType && + (isTypeNullable(type.elementType) || type.elementType.optional) + ) { + elementNullOrUndefinedPrefix = "!p ? p :"; + } + const deserializeFunctionName = type.elementType + ? buildModelDeserializer( + context, + type.elementType.tcgcType!, + false, + true + ) + : undefined; + if (deserializeFunctionName) { + return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}${deserializeFunctionName}(p)})`; + } else if ( + type.elementType && + isAzureCoreErrorType(context.program, type.elementType.__raw) + ) { + return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}p})`; + } else if (type.elementType) { + return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}${deserializeResponseValue(context, type.elementType, "p", type.format)}})`; + } else { + return restValue; + } + } + case "byte-array": + if (format !== "binary") { + return `typeof ${restValue} === 'string' + ? ${stringToUint8ArrayReference}(${restValue}, "${format ?? "base64"}") + : ${restValue}`; + } + return restValue; + case "combined": + if (isNormalUnion(type)) { + return `${restValue}`; + } else if (isSpecialHandledUnion(type)) { + const deserializeFunctionName = type + ? buildModelDeserializer(context, type.tcgcType!, false, true) + : undefined; + if (deserializeFunctionName) { + return `${deserializeFunctionName}(${restValue})`; + } else { + return `${restValue} as any`; + } + } else { + return `${restValue} as any`; + } + default: + return restValue; + } } export function isLroAndPagingOperation(op: Operation): boolean { @@ -1499,23 +1184,11 @@ export function getPropertyFullName( ) { let fullName = `${modularType.clientName}`; if (propertyPath) { - fullName = `${propertyPath}.${modularType.clientName}`; + fullName = `${propertyPath}["${modularType.clientName}"]`; } return fullName; } -export function isDiscriminatedUnion(type?: SdkType): type is SdkModelType { - if (!type) { - return false; - } - - return Boolean( - type.kind === "model" && - type.discriminatorProperty && - type.discriminatedSubtypes - ); -} - /** * Get an expression representing an array of expected status codes for the operation * @param operation The operation diff --git a/packages/typespec-ts/src/modular/helpers/typeHelpers.ts b/packages/typespec-ts/src/modular/helpers/typeHelpers.ts index b3e8712ce3..7084b411e2 100644 --- a/packages/typespec-ts/src/modular/helpers/typeHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/typeHelpers.ts @@ -18,14 +18,10 @@ export interface TypeMetadata { // Mapping of simple types to their TypeScript equivalents. const simpleTypeMap: Record = { Key: { - name: "KeyCredential", - originModule: "@azure/core-auth", - isRelative: false + name: "KeyCredential" }, OAuth2: { - name: "TokenCredential", - originModule: "@azure/core-auth", - isRelative: false + name: "TokenCredential" }, boolean: { name: "boolean" }, datetime: { name: "Date" }, diff --git a/packages/typespec-ts/src/modular/modularCodeModel.ts b/packages/typespec-ts/src/modular/modularCodeModel.ts index 477581374b..d06653dbc9 100644 --- a/packages/typespec-ts/src/modular/modularCodeModel.ts +++ b/packages/typespec-ts/src/modular/modularCodeModel.ts @@ -6,6 +6,8 @@ import { } from "@azure-tools/rlc-common"; import { SdkBodyParameter, + SdkClientType, + SdkHttpOperation, SdkType } from "@azure-tools/typespec-client-generator-core"; import { UsageFlags, Type as TypespecType } from "@typespec/compiler"; @@ -134,6 +136,7 @@ export interface Client { rlcClientName: string; subfolder?: string; rlcHelperDetails: HelperFunctionDetails; + tcgcClient: SdkClientType; } export type ParameterLocation = diff --git a/packages/typespec-ts/src/modular/serialization/buildDeserializerFunction.ts b/packages/typespec-ts/src/modular/serialization/buildDeserializerFunction.ts new file mode 100644 index 0000000000..6e9784183f --- /dev/null +++ b/packages/typespec-ts/src/modular/serialization/buildDeserializerFunction.ts @@ -0,0 +1,494 @@ +import { FunctionDeclarationStructure, StructureKind } from "ts-morph"; +import { + SdkArrayType, + SdkDictionaryType, + SdkModelType, + SdkType, + SdkUnionType, + UsageFlags +} from "@azure-tools/typespec-client-generator-core"; +import { toCamelCase, toPascalCase } from "../../utils/casingUtils.js"; + +import { SdkContext } from "../../utils/interfaces.js"; +import { getResponseMapping } from "../helpers/operationHelpers.js"; +import { getType } from "../buildCodeModel.js"; +import { normalizeModelName } from "../emitModels.js"; +import { NameType } from "@azure-tools/rlc-common"; +import { isAzureCoreErrorType } from "../../utils/modelUtils.js"; +import { + isDiscriminatedUnion, + isSupportedSerializeType, + ModelSerializeOptions +} from "./serializeUtils.js"; + +export function buildModelDeserializer( + context: SdkContext, + type: SdkType, + skipDiscriminatedUnion = false, + nameOnly: boolean = false +): FunctionDeclarationStructure | undefined | string { + // const modelTcgcType = getTcgcType(type) as SdkModelType; + if (!isSupportedSerializeType(type)) { + return undefined; + } + if (type.kind === "model") { + if ( + !type.usage || + (type.usage !== undefined && + (type.usage & UsageFlags.Output) !== UsageFlags.Output) + ) { + return undefined; + } + if (!type.name) { + throw new Error(`NYI Serialization of anonymous types`); + } + if (isAzureCoreErrorType(context.program, type.__raw!)) { + return undefined; + } + } + + if ( + !isDiscriminatedUnion(type) && + type.kind === "model" && + type.discriminatorProperty + ) { + return buildPolymorphicDeserializer(context, type, nameOnly); + } + + if (isDiscriminatedUnion(type) && !skipDiscriminatedUnion) { + return buildDiscriminatedUnionDeserializer(context, type, nameOnly); + } + + switch (type.kind) { + case "model": + return buildModelTypeDeserializer(context, type, { + nameOnly, + skipDiscriminatedUnionSuffix: skipDiscriminatedUnion + }); + case "union": // for non-discriminated union, we just return whatever we get + return buildUnionDeserializer(context, type, nameOnly); + case "dict": + return buildDictTypeDeserializer(context, type, nameOnly); + case "array": + return buildArrayTypeDeserializer(context, type, nameOnly); + default: + return undefined; + } +} + +function hasAdditionalProperties(type: SdkType | undefined) { + if ( + !type || + !( + "additionalProperties" in type || + (type.kind === "model" && hasAdditionalProperties(type.baseModel)) + ) + ) { + return false; + } + + if (type.additionalProperties) { + return true; + } + + if (type.baseModel) { + return hasAdditionalProperties(type.baseModel); + } + + return false; +} + +function buildPolymorphicDeserializer( + context: SdkContext, + type: SdkModelType, + nameOnly: boolean +): string; +function buildPolymorphicDeserializer( + context: SdkContext, + type: SdkModelType +): FunctionDeclarationStructure | undefined; +function buildPolymorphicDeserializer( + context: SdkContext, + type: SdkModelType, + nameOnly = false +): FunctionDeclarationStructure | undefined | string { + if (!type.name) { + throw new Error(`NYI Serialization of anonymous types`); + } + const deserializeFunctionName = `${normalizeModelName( + context, + type, + NameType.Operation + )}Deserializer`; + if (nameOnly) { + return deserializeFunctionName; + } + const deserializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: deserializeFunctionName, + isExported: true, + parameters: [ + { + name: "item", + type: "any" + } + ], + returnType: normalizeModelName(context, type), + statements: [] + }; + if (!type.discriminatorProperty) { + return; + } + const statements: string[] = []; + + const subTypes = type.discriminatedSubtypes; + if (!subTypes) { + return; + } + + const cases: string[] = []; + Object.keys(subTypes).forEach((discriminatedValue) => { + const subType = subTypes[discriminatedValue]; + if ( + !subType?.usage || + (subType?.usage !== undefined && + (subType.usage & UsageFlags.Output) !== UsageFlags.Output) + ) { + return; + } + const union = subType?.discriminatedSubtypes ? "Union" : ""; + if (!subType || subType?.name) { + throw new Error(`NYI Serialization of anonymous types`); + } + const subTypeName = `${toPascalCase(subType.name)}${union}`; + const subtypeDeserializerName = toCamelCase(`${subTypeName}Deserializer`); + + cases.push(` + case "${discriminatedValue}": + return ${subtypeDeserializerName}(item as ${subTypeName}); + `); + }); + + statements.push(` + switch (item.${type.discriminatorProperty.name}) { + ${cases.join("\n")} + default: + return item; + } + `); + deserializerFunction.statements = statements.join("\n"); + return deserializerFunction; +} + +function buildDiscriminatedUnionDeserializer( + context: SdkContext, + type: SdkModelType, + nameOnly: boolean +): string; +function buildDiscriminatedUnionDeserializer( + context: SdkContext, + type: SdkModelType +): FunctionDeclarationStructure | undefined; +function buildDiscriminatedUnionDeserializer( + context: SdkContext, + type: SdkModelType, + nameOnly = false +): FunctionDeclarationStructure | undefined | string { + if (!type.name) { + throw new Error(`NYI Serialization of anonymous types`); + } + const cases: string[] = []; + const output: string[] = []; + const deserializeFunctionName = `${normalizeModelName( + context, + type, + NameType.Operation + )}Deserializer`; + if (nameOnly) { + return deserializeFunctionName; + } + const baseDeserializerName = `${normalizeModelName( + context, + type, + NameType.Operation, + true + )}Deserializer`; + for (const key in type.discriminatedSubtypes) { + const subType = type.discriminatedSubtypes[key]!; + if ( + !subType.usage || + (subType.usage !== undefined && + (subType.usage & UsageFlags.Output) !== UsageFlags.Output) + ) { + continue; + } + const discriminatedValue = subType.discriminatorValue!; + const union = subType.discriminatedSubtypes ? "Union" : ""; + const subTypeName = `${toPascalCase(subType.name)}${union}`; + const subtypeDeserializerName = toCamelCase(`${subTypeName}Deserializer`); + + cases.push(` + case "${discriminatedValue}": + return ${subtypeDeserializerName}(item as ${subTypeName}); + `); + } + output.push(` + switch (item.${type.discriminatorProperty?.name}) { + ${cases.join("\n")} + default: + return ${baseDeserializerName}(item); + } + `); + + const deserializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: deserializeFunctionName, + isExported: true, + parameters: [ + { + name: "item", + type: "any" + } + ], + returnType: normalizeModelName(context, type), + statements: output.join("\n") + }; + return deserializerFunction; +} + +function buildUnionDeserializer( + context: SdkContext, + type: SdkUnionType, + nameOnly: boolean +): string; +function buildUnionDeserializer( + context: SdkContext, + type: SdkUnionType +): FunctionDeclarationStructure; +function buildUnionDeserializer( + context: SdkContext, + type: SdkUnionType, + nameOnly = false +): FunctionDeclarationStructure | string | undefined { + if (!type.name) { + throw new Error(`NYI Serialization of anonymous types`); + } + const deserializerFunctionName = `${normalizeModelName( + context, + type, + NameType.Operation + )}Deserializer`; + if (nameOnly) { + return deserializerFunctionName; + } + const deserializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: deserializerFunctionName, + isExported: true, + parameters: [ + { + name: "item", + type: "any" + } + ], + returnType: normalizeModelName(context, type), + statements: ["return item;"] + }; + return deserializerFunction; +} + +function buildModelTypeDeserializer( + context: SdkContext, + type: SdkModelType, + options: ModelSerializeOptions = { + nameOnly: false, + skipDiscriminatedUnionSuffix: false + } +): FunctionDeclarationStructure | string | undefined { + if (!type.name) { + throw new Error(`NYI Deserialization of anonymous types`); + } + const deserializerFunctionName = `${normalizeModelName( + context, + type, + NameType.Operation, + options.skipDiscriminatedUnionSuffix + )}Deserializer`; + if (options.nameOnly) { + return deserializerFunctionName; + } + const deserializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: deserializerFunctionName, + isExported: true, + parameters: [ + { + name: "item", + type: "any" + } + ], + returnType: normalizeModelName( + context, + type, + NameType.Interface, + options.skipDiscriminatedUnionSuffix + ), + statements: ["return item;"] + }; + const nullabilityPrefix = ""; + // getPropertySerializationPrefix({ + // clientName: "item", + // type + // }); + + // This is only handling the compatibility mode, will need to update when we handle additionalProperties property. + const additionalPropertiesSpread = hasAdditionalProperties(type) + ? "...item," + : ""; + + const propertiesStr = getResponseMapping( + context, + getType(context, type.__raw!), + "item" + ); + const propertiesDeserialization = propertiesStr.filter((p) => p.trim()); + + const output = []; + + // don't emit a serializer if there is nothing to serialize + if (propertiesDeserialization.length || additionalPropertiesSpread) { + const fnBody = `{ + ${additionalPropertiesSpread} + ${nullabilityPrefix} ${propertiesDeserialization.join(",\n")} + }`; + output.push(` + return ${fnBody} + `); + } else { + output.push(` + return item as any; + `); + } + deserializerFunction.statements = output; + return deserializerFunction; +} + +function buildDictTypeDeserializer( + context: SdkContext, + type: SdkDictionaryType, + nameOnly: boolean +): string; +function buildDictTypeDeserializer( + context: SdkContext, + type: SdkDictionaryType +): FunctionDeclarationStructure | undefined; +function buildDictTypeDeserializer( + context: SdkContext, + type: SdkDictionaryType, + nameOnly = false +): FunctionDeclarationStructure | undefined | string { + const valueDeserializer = buildModelDeserializer( + context, + type.valueType, + false, + true + ); + if (!valueDeserializer) { + return undefined; + } + if (!isSupportedSerializeType(type.valueType)) { + return undefined; + } + + if (typeof valueDeserializer !== "string") { + return undefined; + } + const valueTypeName = toCamelCase( + valueDeserializer ? valueDeserializer.replace("Deserializer", "") : "" + ); + const deserializerFunctionName = `${valueTypeName}RecordDeserializer`; + if (nameOnly) { + return deserializerFunctionName; + } + const deserializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: `${valueTypeName}RecordDeserializer`, + isExported: true, + parameters: [ + { + name: "item", + type: "Record" + } + ], + returnType: `Record`, + statements: [ + ` + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key]? item[key]: ${valueDeserializer}(item[key]) + }); + return result; + ` + ] + }; + return deserializerFunction; +} + +function buildArrayTypeDeserializer( + context: SdkContext, + type: SdkArrayType, + nameOnly: boolean +): string; +function buildArrayTypeDeserializer( + context: SdkContext, + type: SdkArrayType +): FunctionDeclarationStructure | undefined; +function buildArrayTypeDeserializer( + context: SdkContext, + type: SdkArrayType, + nameOnly = false +): FunctionDeclarationStructure | undefined | string { + const valueDeserializer = buildModelDeserializer( + context, + type.valueType, + false, + true + ); + if (!valueDeserializer) { + return undefined; + } + if (!isSupportedSerializeType(type.valueType)) { + return undefined; + } + + if (typeof valueDeserializer !== "string") { + return undefined; + } + const valueTypeName = toCamelCase( + valueDeserializer ? valueDeserializer.replace("Deserializer", "") : "" + ); + const deserializerFunctionName = `${valueTypeName}ArrayDeserializer`; + if (nameOnly) { + return deserializerFunctionName; + } + const serializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: deserializerFunctionName, + isExported: true, + parameters: [ + { + name: "result", + type: `Array<${normalizeModelName(context, type.valueType as any) ?? "any"}>` + } + ], + returnType: "any[]", + statements: [ + ` + return result.map((item) => { + return ${valueDeserializer}(item) + }); + ` + ] + }; + return serializerFunction; +} diff --git a/packages/typespec-ts/src/modular/serialization/buildSerializerFunction.ts b/packages/typespec-ts/src/modular/serialization/buildSerializerFunction.ts index 034c5cf7b3..f6b9422b26 100644 --- a/packages/typespec-ts/src/modular/serialization/buildSerializerFunction.ts +++ b/packages/typespec-ts/src/modular/serialization/buildSerializerFunction.ts @@ -1,144 +1,79 @@ -import { toCamelCase, toPascalCase } from "../../utils/casingUtils.js"; -import { Type as ModularType } from "../modularCodeModel.js"; -import { getRequestModelMapping } from "../helpers/operationHelpers.js"; - -import { Imports as RuntimeImports } from "@azure-tools/rlc-common"; -import { UsageFlags } from "@typespec/compiler"; +import { FunctionDeclarationStructure, StructureKind } from "ts-morph"; import { + SdkArrayType, + SdkDictionaryType, SdkModelType, - SdkType + SdkType, + SdkUnionType, + UsageFlags } from "@azure-tools/typespec-client-generator-core"; +import { toCamelCase, toPascalCase } from "../../utils/casingUtils.js"; + +import { SdkContext } from "../../utils/interfaces.js"; +import { getRequestModelMapping } from "../helpers/operationHelpers.js"; +import { getType } from "../buildCodeModel.js"; +import { normalizeModelName } from "../emitModels.js"; +import { NameType } from "@azure-tools/rlc-common"; +import { isAzureCoreErrorType } from "../../utils/modelUtils.js"; +import { + isDiscriminatedUnion, + isSupportedSerializeType, + ModelSerializeOptions +} from "./serializeUtils.js"; -function getTcgcType(type: ModularType): SdkType { - if (type.tcgcType?.kind === "nullable") { - return type.tcgcType.type!; - } - return type.tcgcType!; -} export function buildModelSerializer( - type: ModularType, - runtimeImports: RuntimeImports -): string | undefined { - const modelTcgcType = getTcgcType(type) as SdkModelType; - if ( - modelTcgcType.usage !== undefined && - (modelTcgcType.usage & UsageFlags.Input) !== UsageFlags.Input - ) { + context: SdkContext, + type: SdkType, + skipDiscriminatedUnion = false, + nameOnly: boolean = false +): FunctionDeclarationStructure | undefined | string { + // const modelTcgcType = getTcgcType(type) as SdkModelType; + if (!isSupportedSerializeType(type)) { return undefined; } - - if (!type.name) { - throw new Error(`NYI Serialization of anonymous types`); + if (type.kind === "model") { + if ( + !type.usage || + (type.usage !== undefined && + (type.usage & UsageFlags.Input) !== UsageFlags.Input) + ) { + return undefined; + } + if (!type.name) { + throw new Error(`NYI Serialization of anonymous types`); + } + if (isAzureCoreErrorType(context.program, type.__raw!)) { + return undefined; + } } - let serializerName = `${toCamelCase(type.name)}Serializer`; - - const output: string[] = []; - if ( !isDiscriminatedUnion(type) && - type.type === "combined" && - type.discriminator + type.kind === "model" && + type.discriminatorProperty ) { - return buildPolymorphicSerializer(type); - } - - if (isDiscriminatedUnion(type)) { - const discriminatedTgcType = getTcgcType(type) as SdkModelType; - const cases: string[] = []; - const baseSerializerName = `${toCamelCase( - discriminatedTgcType.name - )}Serializer`; - for (const key in discriminatedTgcType.discriminatedSubtypes) { - const subType = discriminatedTgcType.discriminatedSubtypes[key]!; - const discriminatedValue = subType.discriminatorValue!; - const union = subType.discriminatedSubtypes ? "Union" : ""; - const subTypeName = `${toPascalCase(subType.name)}${union}`; - const subtypeSerializerName = toCamelCase(`${subTypeName}Serializer`); - - cases.push(` - case "${discriminatedValue}": - return ${subtypeSerializerName}(item as ${subTypeName}); - `); - } - output.push(` - export function ${toCamelCase(type.name)}Serializer(item: ${toPascalCase( - type.name - )}) { - switch (item.${type.discriminator}) { - ${cases.join("\n")} - default: - return ${baseSerializerName}(item); - } - } - `); - - serializerName = baseSerializerName; - } - - if (type.type === "model" || type.type === "dict") { - const nullabilityPrefix = ""; - // getPropertySerializationPrefix({ - // clientName: "item", - // type - // }); - - // This is only handling the compatibility mode, will need to update when we handle additionalProperties property. - const additionalPropertiesSpread = hasAdditionalProperties(type.tcgcType) - ? "...item," - : ""; - - const { propertiesStr, directAssignment } = getRequestModelMapping( - type, - "item", - runtimeImports - ); - const propertiesSerialization = propertiesStr.filter((p) => p.trim()); - - // don't emit a serializer if there is nothing to serialize - if (propertiesSerialization.length || additionalPropertiesSpread) { - const spreadSerialized = directAssignment ? "..." : ""; - const fnBody = `{ - ${additionalPropertiesSpread} - ${nullabilityPrefix} ${spreadSerialized} ${propertiesSerialization.join( - ",\n" - )} - }`; - output.push(` - export function ${serializerName}(item: ${toPascalCase( - type.name - )}): Record { - return ${fnBody} - } - `); - } else { - output.push(` - export function ${serializerName}(item: ${toPascalCase(type.name)}) { - return item as any; - } - `); - } - } else if (type.type === "enum") { - output.push(` - export function ${serializerName}(item: ${toPascalCase(type.name)}) { - return item; - } - `); + return buildPolymorphicSerializer(context, type, nameOnly); } - return output.join("\n"); -} - -function isDiscriminatedUnion( - type: ModularType -): type is ModularType & { tcgcType: SdkModelType } { - const { tcgcType } = type; + if (isDiscriminatedUnion(type) && !skipDiscriminatedUnion) { + return buildDiscriminatedUnionSerializer(context, type, nameOnly); + } - return Boolean( - tcgcType?.kind === "model" && - tcgcType.discriminatorProperty && - tcgcType.discriminatedSubtypes - ); + switch (type.kind) { + case "model": + return buildModelTypeSerializer(context, type, { + nameOnly, + skipDiscriminatedUnionSuffix: skipDiscriminatedUnion + }); + case "union": // for non-discriminated union, we just return whatever we get + return buildUnionSerializer(context, type, nameOnly); + case "dict": + return buildDictTypeSerializer(context, type, nameOnly); + case "array": + return buildArrayTypeSerializer(context, type, nameOnly); + default: + return undefined; + } } function hasAdditionalProperties(type: SdkType | undefined) { @@ -157,38 +92,394 @@ function hasAdditionalProperties(type: SdkType | undefined) { return false; } -function buildPolymorphicSerializer(type: ModularType) { - if (!type.discriminator) { +function buildPolymorphicSerializer( + context: SdkContext, + type: SdkModelType, + nameOnly: boolean +): string; +function buildPolymorphicSerializer( + context: SdkContext, + type: SdkModelType +): FunctionDeclarationStructure | undefined; +function buildPolymorphicSerializer( + context: SdkContext, + type: SdkModelType, + nameOnly = false +): FunctionDeclarationStructure | undefined | string { + if (!type.name) { + throw new Error(`NYI Serialization of anonymous types`); + } + const serializeFunctionName = `${normalizeModelName( + context, + type, + NameType.Operation + )}Serializer`; + if (nameOnly) { + return serializeFunctionName; + } + const serializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: serializeFunctionName, + isExported: true, + parameters: [ + { + name: "item", + type: normalizeModelName(context, type) + } + ], + returnType: "any", + statements: [] + }; + if (!type.discriminatorProperty) { return; } - const output: string[] = []; + const statements: string[] = []; - const subTypes = type.types ?? []; + const subTypes = type.discriminatedSubtypes; + if (!subTypes) { + return; + } const cases: string[] = []; - for (const subType of subTypes) { - const discriminatedValue = subType.discriminatorValue!; - const union = subType.types ? "Union" : ""; - const subTypeName = `${toPascalCase(subType.name!)}${union}`; + Object.keys(subTypes).forEach((discriminatedValue) => { + const subType = subTypes[discriminatedValue]; + if ( + !subType?.usage || + (subType?.usage !== undefined && + (subType.usage & UsageFlags.Input) !== UsageFlags.Input) + ) { + return; + } + const union = subType?.discriminatedSubtypes ? "Union" : ""; + if (!subType || subType?.name) { + throw new Error(`NYI Serialization of anonymous types`); + } + const subTypeName = `${toPascalCase(subType.name)}${union}`; const subtypeSerializerName = toCamelCase(`${subTypeName}Serializer`); cases.push(` case "${discriminatedValue}": return ${subtypeSerializerName}(item as ${subTypeName}); `); - } + }); - output.push(` - export function ${toCamelCase(type.name!)}Serializer(item: ${toPascalCase( - type.name! - )}) { - switch (item.${type.discriminator}) { + statements.push(` + switch (item.${type.discriminatorProperty.name}) { ${cases.join("\n")} default: return item; } + `); + serializerFunction.statements = statements.join("\n"); + return serializerFunction; +} + +function buildDiscriminatedUnionSerializer( + context: SdkContext, + type: SdkModelType, + nameOnly: boolean +): string; +function buildDiscriminatedUnionSerializer( + context: SdkContext, + type: SdkModelType +): FunctionDeclarationStructure | undefined; +function buildDiscriminatedUnionSerializer( + context: SdkContext, + type: SdkModelType, + nameOnly = false +): FunctionDeclarationStructure | undefined | string { + if (!type.name) { + throw new Error(`NYI Serialization of anonymous types`); + } + const cases: string[] = []; + const output: string[] = []; + const serializeFunctionName = `${normalizeModelName( + context, + type, + NameType.Operation + )}Serializer`; + if (nameOnly) { + return serializeFunctionName; + } + const baseSerializerName = `${normalizeModelName( + context, + type, + NameType.Operation, + true + )}Serializer`; + for (const key in type.discriminatedSubtypes) { + const subType = type.discriminatedSubtypes[key]!; + if ( + !subType.usage || + (subType.usage !== undefined && + (subType.usage & UsageFlags.Input) !== UsageFlags.Input) + ) { + continue; } + const discriminatedValue = subType.discriminatorValue!; + const union = subType.discriminatedSubtypes ? "Union" : ""; + const subTypeName = `${toPascalCase(subType.name)}${union}`; + const subtypeSerializerName = toCamelCase(`${subTypeName}Serializer`); + + cases.push(` + case "${discriminatedValue}": + return ${subtypeSerializerName}(item as ${subTypeName}); `); + } + output.push(` + switch (item.${type.discriminatorProperty?.name}) { + ${cases.join("\n")} + default: + return ${baseSerializerName}(item); + } + `); + + const serializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: serializeFunctionName, + isExported: true, + parameters: [ + { + name: "item", + type: normalizeModelName(context, type) + } + ], + returnType: "any", + statements: output.join("\n") + }; + return serializerFunction; +} + +function buildUnionSerializer( + context: SdkContext, + type: SdkUnionType, + nameOnly: boolean +): string; +function buildUnionSerializer( + context: SdkContext, + type: SdkUnionType +): FunctionDeclarationStructure; +function buildUnionSerializer( + context: SdkContext, + type: SdkUnionType, + nameOnly = false +): FunctionDeclarationStructure | string { + if (!type.name) { + throw new Error(`NYI Serialization of anonymous types`); + } + const serializerFunctionName = `${normalizeModelName( + context, + type, + NameType.Operation + )}Serializer`; + if (nameOnly) { + return serializerFunctionName; + } + const serializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: `${normalizeModelName(context, type, NameType.Operation)}Serializer`, + isExported: true, + parameters: [ + { + name: "item", + type: normalizeModelName(context, type) + } + ], + returnType: "any", + statements: ["return item;"] + }; + return serializerFunction; +} + +function buildModelTypeSerializer( + context: SdkContext, + type: SdkModelType, + options: ModelSerializeOptions = { + nameOnly: false, + skipDiscriminatedUnionSuffix: false + } +): FunctionDeclarationStructure | string { + if (!type.name) { + throw new Error(`NYI Deserialization of anonymous types`); + } + const serializerFunctionName = `${normalizeModelName( + context, + type, + NameType.Operation, + options.skipDiscriminatedUnionSuffix + )}Serializer`; + if (options.nameOnly) { + return serializerFunctionName; + } + const serializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: serializerFunctionName, + isExported: true, + parameters: [ + { + name: "item", + type: normalizeModelName( + context, + type, + NameType.Interface, + options.skipDiscriminatedUnionSuffix + ) + } + ], + returnType: "any", + statements: ["return item;"] + }; + + // This is only handling the compatibility mode, will need to update when we handle additionalProperties property. + const additionalPropertiesSpread = hasAdditionalProperties(type) + ? "...item" + : ""; + + const { directAssignment, propertiesStr } = getRequestModelMapping( + context, + getType(context, type.__raw!), + "item" + ); + if (additionalPropertiesSpread) { + propertiesStr.unshift(additionalPropertiesSpread); + } + const serializeContent = + directAssignment === true + ? propertiesStr.join(",") + : `{${propertiesStr.join(",")}}`; + + const output = []; + + // don't emit a serializer if there is nothing to serialize + if (propertiesStr.length) { + output.push(` + return ${serializeContent} + `); + } else { + output.push(` + return item as any; + `); + } + serializerFunction.statements = output; + return serializerFunction; +} + +function buildDictTypeSerializer( + context: SdkContext, + type: SdkDictionaryType, + nameOnly: boolean +): string; +function buildDictTypeSerializer( + context: SdkContext, + type: SdkDictionaryType +): FunctionDeclarationStructure | undefined; +function buildDictTypeSerializer( + context: SdkContext, + type: SdkDictionaryType, + nameOnly = false +): FunctionDeclarationStructure | undefined | string { + const valueSerializer = buildModelSerializer( + context, + type.valueType, + false, + true + ); + if (!valueSerializer) { + return undefined; + } + if (!isSupportedSerializeType(type.valueType)) { + return undefined; + } + + if (typeof valueSerializer !== "string") { + return undefined; + } + const valueTypeName = toCamelCase( + valueSerializer ? valueSerializer.replace("Serializer", "") : "" + ); + const serializerFunctionName = `${valueTypeName}RecordSerializer`; + if (nameOnly) { + return serializerFunctionName; + } + const serializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: serializerFunctionName, + isExported: true, + parameters: [ + { + name: "item", + type: `Record` + } + ], + returnType: "Record", + statements: [ + ` + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key]? item[key]: ${valueSerializer}(item[key]) + }); + return result; + ` + ] + }; + return serializerFunction; +} - return output.join("\n"); +function buildArrayTypeSerializer( + context: SdkContext, + type: SdkArrayType, + nameOnly: boolean +): string; +function buildArrayTypeSerializer( + context: SdkContext, + type: SdkArrayType +): FunctionDeclarationStructure | undefined; +function buildArrayTypeSerializer( + context: SdkContext, + type: SdkArrayType, + nameOnly = false +): FunctionDeclarationStructure | undefined | string { + const valueSerializer = buildModelSerializer( + context, + type.valueType, + false, + true + ); + if (!valueSerializer) { + return undefined; + } + if (!isSupportedSerializeType(type.valueType)) { + return undefined; + } + + if (typeof valueSerializer !== "string") { + return undefined; + } + const valueTypeName = toCamelCase( + valueSerializer ? valueSerializer.replace("Serializer", "") : "" + ); + const serializerFunctionName = `${valueTypeName}ArraySerializer`; + if (nameOnly) { + return serializerFunctionName; + } + const serializerFunction: FunctionDeclarationStructure = { + kind: StructureKind.Function, + name: serializerFunctionName, + isExported: true, + parameters: [ + { + name: "result", + type: `Array<${normalizeModelName(context, type.valueType as any) ?? "any"}>` + } + ], + returnType: "any[]", + statements: [ + ` + return result.map((item) => { + return ${valueSerializer}(item) + }); + ` + ] + }; + return serializerFunction; } diff --git a/packages/typespec-ts/src/modular/serialization/serializeUtils.ts b/packages/typespec-ts/src/modular/serialization/serializeUtils.ts new file mode 100644 index 0000000000..e8fbc773bd --- /dev/null +++ b/packages/typespec-ts/src/modular/serialization/serializeUtils.ts @@ -0,0 +1,143 @@ +import { Type } from "../modularCodeModel.js"; +import { getAllAncestors } from "../helpers/operationHelpers.js"; +import { + SdkModelType, + SdkType +} from "@azure-tools/typespec-client-generator-core"; + +export function isSupportedSerializeType(type: SdkType): boolean { + return ( + type.kind === "model" || + type.kind === "dict" || + type.kind === "array" || + type.kind === "union" + ); +} + +/** + * + * In general, we have two kinds of basic special union variants. + * 1. datetime type + * 2. bytes type + * If we consider model type, we have the following three type. + * 3. model with property of datetime type. + * 4. model with property of binary array type. + * 5. model that has different property name between rest layer and modular layer. + * 6. nested model i.e. model with property that is a model with one of the above three conditions. + * If we consider array type, with all the above 6 types as the element types. + */ +const specialVariantMap = new Map(); +export function isSpecialUnionVariant( + t: Type, + variantStack: Type[] = [] +): boolean { + if (variantStack.length <= 0) { + variantStack.push(t); + } + const ancestors = getAllAncestors(t); + if (specialVariantMap.has(t)) { + variantStack.pop(); + return specialVariantMap.get(t) ?? false; + } + + if ( + t.type === "datetime" || + t.type === "byte-array" || + (t.type === "model" && + t.properties + ?.filter((p) => { + return !( + variantStack.includes(p.type) || + ancestors.includes(p.type) || + (p.type.type === "list" && + p.type.elementType && + (variantStack.includes(p.type.elementType) || + ancestors.includes(p.type.elementType))) + ); + }) + ?.some( + (p) => + p.clientName !== p.restApiName || + isSpecialUnionVariant(p.type, [...variantStack, p.type]) + )) || + isPolymorphicUnion(t) || + (t.type === "list" && + t.elementType && + !variantStack.includes(t.elementType) && + !ancestors.includes(t.elementType) && + isSpecialUnionVariant(t.elementType, [...variantStack, t.elementType])) || + (t.type === "combined" && + t.types + ?.filter((p) => { + return !(variantStack.includes(p) || ancestors.includes(p)); + }) + ?.some((p) => { + return isSpecialUnionVariant(p, [...variantStack, p]); + })) || + (t.type === "enum" && !(t.isFixed || t.isNonExhaustive)) + ) { + specialVariantMap.set(t, true); + variantStack.pop(); + return true; + } + variantStack.pop(); + specialVariantMap.set(t, false); + return false; +} + +export function isNormalUnion(t: Type): boolean { + return ( + t.type === "combined" && + !( + t.types?.some((p) => { + return isSpecialUnionVariant(p); + }) ?? false + ) + ); +} + +export function isDiscriminatedUnion( + type: SdkType +): type is SdkModelType & { discriminatorProperty: SdkType } { + if (!type) { + return false; + } + return Boolean( + type?.kind === "model" && + type.discriminatorProperty && + type.discriminatedSubtypes + ); +} + +export function isSpecialHandledUnion(t: Type): boolean { + return isDiscriminatedUnion(t.tcgcType!) || isPolymorphicUnion(t); +} + +const polymorphicUnionMap = new Map(); +export function isPolymorphicUnion(t: Type): boolean { + if (polymorphicUnionMap.has(t)) { + return polymorphicUnionMap.get(t) ?? false; + } + const ancestors = getAllAncestors(t); + if ( + t.type === "model" && + t.isPolymorphicBaseModel && + t.types + ?.filter((p) => { + return !ancestors.includes(p); + }) + ?.some((p) => { + return isSpecialUnionVariant(p); + }) + ) { + polymorphicUnionMap.set(t, true); + return true; + } + polymorphicUnionMap.set(t, false); + return false; +} + +export interface ModelSerializeOptions { + nameOnly: boolean; + skipDiscriminatedUnionSuffix: boolean; +} diff --git a/packages/typespec-ts/src/modular/type-expressions/get-credential-expression.ts b/packages/typespec-ts/src/modular/type-expressions/get-credential-expression.ts new file mode 100644 index 0000000000..a8037dd831 --- /dev/null +++ b/packages/typespec-ts/src/modular/type-expressions/get-credential-expression.ts @@ -0,0 +1,18 @@ +import { SdkCredentialType } from "@azure-tools/typespec-client-generator-core"; +import { resolveReference } from "../../framework/reference.js"; +import { useDependencies } from "../../framework/hooks/useDependencies.js"; + +export function getCredentialExpression(type: SdkCredentialType): string { + const dependencies = useDependencies(); + switch (type.scheme.type) { + case "apiKey": + case "http": + return resolveReference(dependencies.KeyCredential); + case "oauth2": + case "openIdConnect": + return resolveReference(dependencies.TokenCredential); + default: + // TODO: Add diagnostics about unknown credential type + return "any"; + } +} diff --git a/packages/typespec-ts/src/modular/type-expressions/get-enum-expression.ts b/packages/typespec-ts/src/modular/type-expressions/get-enum-expression.ts new file mode 100644 index 0000000000..a5fdf4d48d --- /dev/null +++ b/packages/typespec-ts/src/modular/type-expressions/get-enum-expression.ts @@ -0,0 +1,28 @@ +import { SdkEnumType } from "@azure-tools/typespec-client-generator-core"; +import { resolveReference } from "../../framework/reference.js"; +import { getTypeExpression, EmitTypeOptions } from "./get-type-expression.js"; +import { shouldEmitInline } from "./utils.js"; +import { SdkContext } from "../../utils/interfaces.js"; + +export function getEnumExpression( + context: SdkContext, + type: SdkEnumType, + options: EmitTypeOptions = {} +): string { + if (shouldEmitInline(type, options)) { + return !isExtensibleEnum(context, type) + ? type.values.map((v) => getTypeExpression(context, v)).join(" | ") + : getTypeExpression(context, type.valueType); + } else { + return resolveReference(type); + } +} + +export function isExtensibleEnum( + context: SdkContext, + type: SdkEnumType +): boolean { + return ( + !type.isFixed && context.rlcOptions?.experimentalExtensibleEnums === true + ); +} diff --git a/packages/typespec-ts/src/modular/type-expressions/get-model-expression.ts b/packages/typespec-ts/src/modular/type-expressions/get-model-expression.ts new file mode 100644 index 0000000000..14f2a4d26f --- /dev/null +++ b/packages/typespec-ts/src/modular/type-expressions/get-model-expression.ts @@ -0,0 +1,59 @@ +import { EmitTypeOptions, getTypeExpression } from "./get-type-expression.js"; + +import { SdkModelType } from "@azure-tools/typespec-client-generator-core"; +import { refkey } from "../../framework/refkey.js"; +import { resolveReference } from "../../framework/reference.js"; +import { shouldEmitInline } from "./utils.js"; +import { useContext } from "../../contextManager.js"; +import { SdkContext } from "../../utils/interfaces.js"; + +export interface ModelExpressionOptions extends EmitTypeOptions { + skipPolymorphicUnion?: boolean; +} + +export function getModelExpression( + context: SdkContext, + type: SdkModelType, + options: ModelExpressionOptions = {} +): string { + const externalModel = getExternalModel(type); + if (externalModel) { + return resolveReference(externalModel); + } + + if (shouldEmitInline(type, options)) { + // generate Record for empty anonymous object + if (type.properties.length === 0) { + return "Record"; + } + return `{ + ${type.properties + .map( + (p) => + `"${p.name}"${p.optional ? "?" : ""}: ${getTypeExpression(context, p.type)}` + ) + .join(",\n")} + }`; + } else { + if (!options.skipPolymorphicUnion && type.discriminatedSubtypes) { + return resolveReference(refkey(type, "polymorphicType")); + } else { + return resolveReference(type); + } + } +} + +const externalModels: Record = { + "Azure.Core.Foundations.Error": "ErrorModel" +}; + +export function getExternalModel(type: SdkModelType) { + const commonName = externalModels[type.crossLanguageDefinitionId]; + + if (!commonName) { + return undefined; + } + + const externalDependencies = useContext("dependencies"); + return externalDependencies[commonName]; +} diff --git a/packages/typespec-ts/src/modular/type-expressions/get-type-expression.ts b/packages/typespec-ts/src/modular/type-expressions/get-type-expression.ts new file mode 100644 index 0000000000..9b6598c240 --- /dev/null +++ b/packages/typespec-ts/src/modular/type-expressions/get-type-expression.ts @@ -0,0 +1,93 @@ +import { + SdkContext, + SdkType +} from "@azure-tools/typespec-client-generator-core"; +import { getCredentialExpression } from "./get-credential-expression.js"; +import { getEnumExpression } from "./get-enum-expression.js"; +import { getModelExpression } from "./get-model-expression.js"; +import { getUnionExpression } from "./get-union-expression.js"; + +export interface EmitTypeOptions { + emitInline?: boolean; +} + +export function getTypeExpression( + context: SdkContext, + type: SdkType, + options?: EmitTypeOptions +): string { + switch (type.kind) { + case "array": { + const valueType = getTypeExpression(context, type.valueType, options); + return `(${valueType})[]`; + } + case "enum": + return getEnumExpression(context, type); + case "unknown": + return "any"; + case "boolean": + return "boolean"; + case "decimal": + case "decimal128": + case "float": + case "float32": + case "float64": + case "integer": + case "int16": + case "int32": + case "int64": + case "int8": + case "uint16": + case "uint32": + case "uint64": + case "uint8": + case "numeric": + case "safeint": + return "number"; + case "endpoint": + case "plainDate": + case "plainTime": + case "string": + case "url": + // TODO - what typespec produces uri, password? + return "string"; + case "bytes": + return "Uint8Array"; + case "constant": + case "enumvalue": + if (getTypeExpression(context, type.valueType) === "string") { + return `"${type.value}"`; + } + return String(type.value); + case "duration": + return getTypeExpression(context, type.wireType, options); + case "credential": + // Credential comes from @useAuth decorator + return getCredentialExpression(type); + case "dict": { + const valueType = getTypeExpression(context, type.valueType, options); + return `Record`; + } + case "model": + return getModelExpression(context, type); + case "nullable": { + const nonNullableType = getTypeExpression(context, type.type, options); + return `(${nonNullableType}) | null`; + } + case "offsetDateTime": + return "string"; + case "tuple": { + const types = type.valueTypes + .map((v) => getTypeExpression(context, v, options)) + .join(", "); + return `[${types}]`; + } + case "union": + return getUnionExpression(context, type, options); + case "utcDateTime": + return "Date"; + + default: + return "any"; + } +} diff --git a/packages/typespec-ts/src/modular/type-expressions/get-union-expression.ts b/packages/typespec-ts/src/modular/type-expressions/get-union-expression.ts new file mode 100644 index 0000000000..7f220f145d --- /dev/null +++ b/packages/typespec-ts/src/modular/type-expressions/get-union-expression.ts @@ -0,0 +1,22 @@ +import { + SdkContext, + SdkUnionType +} from "@azure-tools/typespec-client-generator-core"; +import { resolveReference } from "../../framework/reference.js"; +import { getTypeExpression, EmitTypeOptions } from "./get-type-expression.js"; +import { shouldEmitInline } from "./utils.js"; + +export function getUnionExpression( + context: SdkContext, + type: SdkUnionType, + options: EmitTypeOptions = {} +): string { + if (shouldEmitInline(type, options)) { + const variantTypes = new Set( + type.variantTypes.map((v) => `${getTypeExpression(context, v, options)}`) + ); + return `(${[...variantTypes].join(" | ")})`; + } else { + return resolveReference(type); + } +} diff --git a/packages/typespec-ts/src/modular/type-expressions/utils.ts b/packages/typespec-ts/src/modular/type-expressions/utils.ts new file mode 100644 index 0000000000..77d32033a5 --- /dev/null +++ b/packages/typespec-ts/src/modular/type-expressions/utils.ts @@ -0,0 +1,15 @@ +import { EmitTypeOptions } from "./get-type-expression.js"; + +export function shouldEmitInline( + type: { isGeneratedName?: boolean }, + options: EmitTypeOptions = {} +): boolean { + const emitInline = options.emitInline; + + if (emitInline === undefined && "isGeneratedName" in type) { + // If not explicitly set, default to emitting inline for anonymous types + return Boolean(type.isGeneratedName); + } + + return Boolean(emitInline); +} diff --git a/packages/typespec-ts/src/transform/transform.ts b/packages/typespec-ts/src/transform/transform.ts index de0c458e27..664779a28d 100644 --- a/packages/typespec-ts/src/transform/transform.ts +++ b/packages/typespec-ts/src/transform/transform.ts @@ -55,10 +55,10 @@ export async function transformRLCModel( const libraryName = normalizeName( options.batch && (options.isModularLibrary || options.batch.length > 1) ? client.name - : options?.title ?? + : (options?.title ?? client.name ?? getDefaultService(program)?.title ?? - "", + ""), NameType.Class ); const importSet = initInternalImports(); diff --git a/packages/typespec-ts/src/transform/transformApiVersionInfo.ts b/packages/typespec-ts/src/transform/transformApiVersionInfo.ts index f4f9aec012..6bf7ed451a 100644 --- a/packages/typespec-ts/src/transform/transformApiVersionInfo.ts +++ b/packages/typespec-ts/src/transform/transformApiVersionInfo.ts @@ -36,9 +36,9 @@ export function transformApiVersionInfo( : undefined; const defaultValue = (pathVersionDetail || queryVersionDetail) && !isCrossedVersion - ? getDefaultApiVersionString(dpgContext) ?? + ? (getDefaultApiVersionString(dpgContext) ?? pathVersionDetail?.defaultValue ?? - queryVersionDetail?.defaultValue + queryVersionDetail?.defaultValue) : undefined; if (pathVersionDetail && queryVersionDetail) { diff --git a/packages/typespec-ts/src/transform/transformParameters.ts b/packages/typespec-ts/src/transform/transformParameters.ts index 4df60c4867..1541a290db 100644 --- a/packages/typespec-ts/src/transform/transformParameters.ts +++ b/packages/typespec-ts/src/transform/transformParameters.ts @@ -258,7 +258,7 @@ function transformBodyParameters( const bodyType = (parameters.bodyType ?? parameters.bodyParameter?.type) && inputBodyType ? inputBodyType - : parameters.bodyType ?? parameters.bodyParameter?.type; + : (parameters.bodyType ?? parameters.bodyParameter?.type); if (!bodyType || isVoidType(bodyType)) { return; } diff --git a/packages/typespec-ts/src/transform/transformSchemas.ts b/packages/typespec-ts/src/transform/transformSchemas.ts index 07127ec19d..ef76b1edc5 100644 --- a/packages/typespec-ts/src/transform/transformSchemas.ts +++ b/packages/typespec-ts/src/transform/transformSchemas.ts @@ -1,17 +1,15 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { SchemaContext } from "@azure-tools/rlc-common"; +import { HttpOperation, getServers } from "@typespec/http"; +import { KnownMediaType, extractMediaTypes } from "../utils/mediaTypes.js"; +import { Model, Type } from "@typespec/compiler"; import { + SdkClient, getHttpOperationWithCache, listOperationGroups, - listOperationsInOperationGroup, - SdkClient + listOperationsInOperationGroup } from "@azure-tools/typespec-client-generator-core"; -import { Model, Type } from "@typespec/compiler"; -import { getServers, HttpOperation } from "@typespec/http"; -import { SdkContext } from "../utils/interfaces.js"; -import { extractMediaTypes, KnownMediaType } from "../utils/mediaTypes.js"; import { getBodyType, getDefaultService, @@ -20,10 +18,14 @@ import { isAzureCoreErrorType, trimUsage } from "../utils/modelUtils.js"; + +import { SchemaContext } from "@azure-tools/rlc-common"; +import { SdkContext } from "../utils/interfaces.js"; import { useContext } from "../contextManager.js"; export function transformSchemas(client: SdkClient, dpgContext: SdkContext) { const program = dpgContext.program; + const metatree = useContext("rlcMetaTree"); const schemas: Map = new Map< string, SchemaContext[] @@ -120,7 +122,6 @@ export function transformSchemas(client: SdkClient, dpgContext: SdkContext) { } transformHostParameters(); usageMap.forEach((context, tspModel) => { - const metatree = useContext("rlcMetaTree"); const model = getSchemaForType(dpgContext, tspModel, { usage: context, isRequestBody: requestBodySet.has(tspModel), diff --git a/packages/typespec-ts/src/utils/modelUtils.ts b/packages/typespec-ts/src/utils/modelUtils.ts index bb21fe9733..037e1183e6 100644 --- a/packages/typespec-ts/src/utils/modelUtils.ts +++ b/packages/typespec-ts/src/utils/modelUtils.ts @@ -1424,8 +1424,8 @@ function getPriorityName(schema: Schema, usage?: SchemaContext[]): string { return usage && usage.includes(SchemaContext.Input) && !usage.includes(SchemaContext.Output) - ? schema.typeName ?? schema.name - : schema.outputTypeName ?? schema.typeName ?? schema.name; + ? (schema.typeName ?? schema.name) + : (schema.outputTypeName ?? schema.typeName ?? schema.name); } function getEnumStringDescription(type: any) { @@ -1602,23 +1602,45 @@ export function isAzureCoreErrorType(program: Program, t?: Type): boolean { !["error", "errorresponse", "innererror"].includes( effective.name.toLowerCase() ) - ) + ) { return false; + } return isAzureCoreFoundationsNamespace(effective); } // Check if the type in the Azure.Core.Foundations has an LRO type in core export function isAzureCoreLroType(t?: Type): boolean { - if (t?.kind !== "Enum" || !["operationstate"].includes(t.name.toLowerCase())) + if ( + !( + ((t?.kind === "Enum" || t?.kind === "Union") && + ["operationstate"].includes((t.name ?? "").toLowerCase())) || + (t?.kind === "Model" && + ["resourceoperationstatus", "operationstatus"].includes( + t.name.toLowerCase() + )) + ) + ) { return false; - return isAzureCoreFoundationsNamespace(t); + } + return ( + isAzureCoreFoundationsNamespace(t) || + isAzureCoreFoundationsNamespace(t, true) + ); } -function isAzureCoreFoundationsNamespace(t?: Type): boolean { - const namespaces = ".Azure.Core.Foundations".split("."); +function isAzureCoreFoundationsNamespace( + t?: Type, + skipFoundation: boolean = false +): boolean { + const namespaces = ( + skipFoundation ? ".Azure.Core" : ".Azure.Core.Foundations" + ).split("."); while ( namespaces.length > 0 && - (t?.kind === "Model" || t?.kind === "Enum" || t?.kind === "Namespace") && + (t?.kind === "Model" || + t?.kind === "Enum" || + t?.kind === "Union" || + t?.kind === "Namespace") && t.namespace?.name === namespaces.pop() ) { t = t.namespace; diff --git a/packages/typespec-ts/static/static-helpers/serialization/serializers.ts b/packages/typespec-ts/static/static-helpers/serialization/serializers.ts new file mode 100644 index 0000000000..7db0a9dbf5 --- /dev/null +++ b/packages/typespec-ts/static/static-helpers/serialization/serializers.ts @@ -0,0 +1,60 @@ +import { EncodingType, uint8ArrayToString } from "@typespec/ts-http-runtime"; +export const serializeRecord = withNullChecks( + ( + item: Record, + serializer?: (item: any) => any + ): Record => { + return Object.keys(item).reduce((acc, key) => { + if (isPassthroughElement(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; + }, {}); + } +); + +export const serializePassthrough = withNullChecks((item: T): T => item); + +export const serializeArray = withNullChecks( + (items: T[], serializer: (item: T) => unknown): unknown[] => { + return items.map((item) => { + if (isPassthroughElement(item)) { + return item; + } + return serializer(item); + }); + } +); + +export const serializeUtcDateTime = withNullChecks((date: Date): string => { + // todo support encoding? + return date.toISOString(); +}); + +export const serializeBytes = withNullChecks( + (bytes: Uint8Array, encoding: EncodingType): string => { + return uint8ArrayToString(bytes, encoding); + } +); + +export function withNullChecks(fn: (input: any, ...args: any) => unknown) { + return function (input: any | null | undefined, ...args: any) { + if (input === null || input === undefined) { + return input; + } + + return fn(input, ...args); + }; +} + +export function isPassthroughElement(t: any) { + return ["number", "string", "boolean", "null"].includes(typeof t); +} diff --git a/packages/typespec-ts/test-next/integration/hooks/sdkTypes.test.ts b/packages/typespec-ts/test-next/integration/hooks/sdkTypes.test.ts index ec59990e55..b8e6c25495 100644 --- a/packages/typespec-ts/test-next/integration/hooks/sdkTypes.test.ts +++ b/packages/typespec-ts/test-next/integration/hooks/sdkTypes.test.ts @@ -85,8 +85,7 @@ describe("SdkTypes hook", () => { } ` sdkContext = await createSdkContextFromTypespec(spec, {}); - sdkPackage = sdkContext.sdkPackage; - provideSdkTypes(sdkPackage); + provideSdkTypes(sdkContext); provideContext("emitContext", {tcgcContext: sdkContext, compilerContext: sdkContext.emitContext as any}) }); diff --git a/packages/typespec-ts/test-next/unit/static-helpers/serialization.test.ts b/packages/typespec-ts/test-next/unit/static-helpers/serialization.test.ts new file mode 100644 index 0000000000..b646764bde --- /dev/null +++ b/packages/typespec-ts/test-next/unit/static-helpers/serialization.test.ts @@ -0,0 +1,140 @@ +import { describe, it, expect, vi } from "vitest"; +import { + serializeRecord, + serializePassthrough, + serializeArray, + serializeUtcDateTime, + serializeBytes, + withNullChecks, + isPassthroughElement +} from "../../../static/static-helpers/serialization/serializers.js"; +import { EncodingType } from "@typespec/ts-http-runtime"; + +describe("serializeRecord", () => { + it("should serialize a record using the provided serializer", () => { + const input = { a: 1, b: 2 }; + const serializer = (item: number) => item.toString(); + const result = serializeRecord(input, serializer); + expect(result).toEqual({ a: 1, b: 2 }); + }); + + it("should handle null and undefined correctly", () => { + const input = { a: 1, b: null, c: undefined }; + const serializer = (item: number | null) => item?.toString() ?? "null"; + const result = serializeRecord(input, serializer); + expect(result).toEqual({ a: 1, b: "null" }); + }); + + it("should use passthrough for passthrough elements", () => { + const input = { a: 1, b: "string", c: new Date("2023-08-01") }; + const result = serializeRecord(input); + expect(result).toEqual(input); + }); + + it("should warn and passthrough unhandled types", () => { + const input = { a: {}, b: [] }; + console.warn = vi.fn(); // Mock console.warn + const result = serializeRecord(input); + expect(result).toEqual(input); + expect(console.warn).toHaveBeenCalledWith( + "Don't know how to serialize [object Object]" + ); + expect(console.warn).toHaveBeenCalledWith("Don't know how to serialize "); + }); +}); + +describe("serializePassthrough", () => { + it("should return the input as-is", () => { + const input = { a: 1, b: "test" }; + const result = serializePassthrough(input); + expect(result).toBe(input); + }); + + it("should handle null and undefined correctly", () => { + const nullResult = serializePassthrough(null); + const undefinedResult = serializePassthrough(undefined); + expect(nullResult).toBeNull(); + expect(undefinedResult).toBeUndefined(); + }); +}); + +describe("serializeArray", () => { + it("should serialize an array using the provided serializer", () => { + const input = [1, 2, 3]; + const serializer = (item: number) => item.toString(); + const result = serializeArray(input, serializer); + expect(result).toEqual([1, 2, 3]); + }); + + it("should use passthrough for passthrough elements", () => { + const input = [1, "string", new Date("2023-08-01")]; + const result = serializeArray(input, (item) => item); + expect(result).toEqual(input); + }); + + it("should handle empty arrays correctly", () => { + const input: any[] = []; + const serializer = (item: any) => item.toString(); + const result = serializeArray(input, serializer); + expect(result).toEqual([]); + }); +}); + +describe("serializeUtcDateTime", () => { + it("should serialize a Date object to UTC string", () => { + const input = new Date("2023-08-01T00:00:00Z"); + const result = serializeUtcDateTime(input); + expect(result).toBe("2023-08-01T00:00:00.000Z"); + }); + + it("should handle null and undefined correctly", () => { + const nullResult = serializeUtcDateTime(null); + const undefinedResult = serializeUtcDateTime(undefined); + expect(nullResult).toBeNull(); + expect(undefinedResult).toBeUndefined(); + }); +}); + +describe("serializeBytes", () => { + it("should serialize a Uint8Array to a string with given encoding", () => { + const input = new Uint8Array([72, 101, 108, 108, 111]); // 'Hello' + const encoding: EncodingType = "utf-8"; + const result = serializeBytes(input, encoding); + expect(result).toBe("Hello"); + }); + + it("should handle null and undefined correctly", () => { + const nullResult = serializeBytes(null, "utf-8"); + const undefinedResult = serializeBytes(undefined, "utf-8"); + expect(nullResult).toBeNull(); + expect(undefinedResult).toBeUndefined(); + }); +}); + +describe("withNullChecks", () => { + it("should return null or undefined if input is null or undefined", () => { + const fn = withNullChecks((input: number) => input + 1); + expect(fn(null)).toBeNull(); + expect(fn(undefined)).toBeUndefined(); + }); + + it("should apply the function if input is not null or undefined", () => { + const fn = withNullChecks((input: number) => input + 1); + expect(fn(1)).toBe(2); + }); +}); + +describe("isPassthroughElement", () => { + it("should return true for numbers, strings, booleans, null, and dates", () => { + expect(isPassthroughElement(1)).toBe(true); + expect(isPassthroughElement("string")).toBe(true); + expect(isPassthroughElement(true)).toBe(true); + }); + + it("should return false for other types", () => { + expect(isPassthroughElement({})).toBe(false); + expect(isPassthroughElement([])).toBe(false); + expect(isPassthroughElement(() => {})).toBe(false); + expect(isPassthroughElement(null)).toBe(false); + }); +}); diff --git a/packages/typespec-ts/test/integration/generated/special-words/src/index.d.ts b/packages/typespec-ts/test/integration/generated/special-words/src/index.d.ts index 9e14a3e6fd..41df3a827a 100644 --- a/packages/typespec-ts/test/integration/generated/special-words/src/index.d.ts +++ b/packages/typespec-ts/test/integration/generated/special-words/src/index.d.ts @@ -79,10 +79,9 @@ export declare interface From { name: string; } -declare interface Global_2 { +export declare interface GlobalModel { name: string; } -export { Global_2 as Global } export declare interface If { name: string; @@ -379,7 +378,7 @@ export declare interface ModelsWithGlobal204Response extends HttpResponse { } export declare interface ModelsWithGlobalBodyParam { - body: Global_2; + body: GlobalModel; } export declare type ModelsWithGlobalParameters = ModelsWithGlobalBodyParam & RequestParameters; @@ -764,15 +763,15 @@ export declare interface OperationsFrom204Response extends HttpResponse { export declare type OperationsFromParameters = RequestParameters; -export declare interface OperationsGlobal { - get(options?: OperationsGlobalParameters): StreamableMethod; +export declare interface OperationsGlobalModel { + get(options?: OperationsGlobalModelParameters): StreamableMethod; } -export declare interface OperationsGlobal204Response extends HttpResponse { +export declare interface OperationsGlobalModel204Response extends HttpResponse { status: "204"; } -export declare type OperationsGlobalParameters = RequestParameters; +export declare type OperationsGlobalModelParameters = RequestParameters; export declare interface OperationsIf { get(options?: OperationsIfParameters): StreamableMethod; @@ -1595,7 +1594,7 @@ export declare interface Routes { (path: "/special-words/operations/finally"): OperationsFinally; (path: "/special-words/operations/for"): OperationsFor; (path: "/special-words/operations/from"): OperationsFrom; - (path: "/special-words/operations/global"): OperationsGlobal; + (path: "/special-words/operations/global"): OperationsGlobalModel; (path: "/special-words/operations/if"): OperationsIf; (path: "/special-words/operations/import"): OperationsImport; (path: "/special-words/operations/in"): OperationsIn; diff --git a/packages/typespec-ts/test/modularIntegration/azureArmResources.spec.ts b/packages/typespec-ts/test/modularIntegration/azureArmResources.spec.ts index 28f96f9565..2a56ce50ce 100644 --- a/packages/typespec-ts/test/modularIntegration/azureArmResources.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/azureArmResources.spec.ts @@ -113,7 +113,6 @@ describe("Azure Arm Resources Rest Client", () => { for await (const user of result) { items.push(user); } - console.log(items); assert.strictEqual(items[0]?.id, validSingletonResource.id); assert.strictEqual(items[0]?.name, validSingletonResource.name); assert.strictEqual(items[0]?.type, validSingletonResource.type); diff --git a/packages/typespec-ts/test/modularIntegration/clientNaming.spec.ts b/packages/typespec-ts/test/modularIntegration/clientNaming.spec.ts index 9dd326ffcc..a2f4c08c52 100644 --- a/packages/typespec-ts/test/modularIntegration/clientNaming.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/clientNaming.spec.ts @@ -24,7 +24,7 @@ describe("NameAndEncodedName Client", () => { it("should work with property language", async () => { try { - const result = await client.language({ tSName: true }); + const result = await client.language({ TSName: true }); assert.isUndefined(result); } catch (err) { assert.fail(err as string); diff --git a/packages/typespec-ts/test/modularIntegration/clientStructureMultiClient.spec.ts b/packages/typespec-ts/test/modularIntegration/clientStructureMultiClient.spec.ts index 28ada5d3b6..2a39064332 100644 --- a/packages/typespec-ts/test/modularIntegration/clientStructureMultiClient.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/clientStructureMultiClient.spec.ts @@ -1,17 +1,17 @@ import { - AClient, - BClient + ClientAClient, + ClientBClient } from "./generated/client/structure/multi-client/src/index.js"; import { assert } from "chai"; describe("Client Structure Multi-Client Rest Client", () => { - let clientA: AClient; - let clientB: BClient; + let clientA: ClientAClient; + let clientB: ClientBClient; beforeEach(() => { - clientA = new AClient("http://localhost:3002", "multi-client", { + clientA = new ClientAClient("http://localhost:3002", "multi-client", { allowInsecureConnection: true }); - clientB = new BClient("http://localhost:3002", "multi-client", { + clientB = new ClientBClient("http://localhost:3002", "multi-client", { allowInsecureConnection: true }); }); diff --git a/packages/typespec-ts/test/modularIntegration/customClientRequestId.spec.ts b/packages/typespec-ts/test/modularIntegration/customClientRequestId.spec.ts index 5a0d64c917..d64c4f1d5d 100644 --- a/packages/typespec-ts/test/modularIntegration/customClientRequestId.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/customClientRequestId.spec.ts @@ -1,11 +1,11 @@ import { PipelinePolicy } from "@azure/core-rest-pipeline"; -import { XmsRequestIdClient } from "./generated/azure/special-headers/client-request-id/src/index.js"; +import { XmsClientRequestIdClient } from "./generated/azure/special-headers/client-request-id/src/index.js"; import { assert } from "chai"; describe("XmsRequestIdClient Classical Client", () => { - let client: XmsRequestIdClient; + let client: XmsClientRequestIdClient; beforeEach(() => { - client = new XmsRequestIdClient({ + client = new XmsClientRequestIdClient({ endpoint: "http://localhost:3002", allowInsecureConnection: true }); @@ -38,7 +38,7 @@ describe("XmsRequestIdClient Classical Client", () => { }, name: "preventCachingPolicy" }; - client = new XmsRequestIdClient({ + client = new XmsClientRequestIdClient({ allowInsecureConnection: true, endpoint: "http://localhost:3002", additionalPolicies: [ @@ -55,7 +55,7 @@ describe("XmsRequestIdClient Classical Client", () => { it("should override with x-test-client-request-id header", async () => { try { - client = new XmsRequestIdClient({ + client = new XmsClientRequestIdClient({ allowInsecureConnection: true, telemetryOptions: { clientRequestIdHeaderName: "x-test-request-id" diff --git a/packages/typespec-ts/test/modularIntegration/dictionaryTypes.spec.ts b/packages/typespec-ts/test/modularIntegration/dictionaryTypes.spec.ts index 9ac18c5bc8..666c9bf10a 100644 --- a/packages/typespec-ts/test/modularIntegration/dictionaryTypes.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/dictionaryTypes.spec.ts @@ -91,10 +91,12 @@ describe("DictionaryClient Modular Client", () => { const result = await client.modelValue.get(); assert.deepEqual(result, { k1: { - property: "hello" + property: "hello", + children: undefined }, k2: { - property: "world" + property: "world", + children: undefined } }); }); @@ -131,7 +133,7 @@ describe("DictionaryClient Modular Client", () => { k1: { property: "hello", children: {} }, k2: { property: "world", - children: { "k2.1": { property: "inner world" } } + children: { "k2.1": { children: undefined, property: "inner world" } } } }); }); diff --git a/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts index c00d9e4d8b..407329f39b 100644 --- a/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts @@ -244,7 +244,7 @@ describe("EncodeBytesClient Modular Client", () => { describe("response body", () => { const pngFile = readFileSync( resolve("../../packages/typespec-ts/temp/assets/image.png") - ).toString(); + ).toString("utf-8"); it(`should get bytes with base64 encoding by default`, async () => { try { const result = await client.responseBody.default(); diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/access/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/access/src/index.d.ts index e448657f40..b0e05b9dbd 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/access/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/access/src/index.d.ts @@ -3,8 +3,8 @@ import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; export declare interface AbstractModel { - name: string; kind: string; + name: string; } export declare type AbstractModelUnion = RealModel | AbstractModel; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/basic/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/basic/src/index.d.ts index 39837a0c13..e311b27b45 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/basic/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/basic/src/index.d.ts @@ -79,6 +79,4 @@ export declare interface UserOrder { detail: string; } -export declare type Versions = "2022-12-01-preview"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/rpc/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/rpc/src/index.d.ts index 38a69d2fbd..9c0f4a1999 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/rpc/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/rpc/src/index.d.ts @@ -37,6 +37,4 @@ export declare interface RpcClientOptionalParams extends ClientOptions { apiVersion?: string; } -export declare type Versions = "2022-12-01-preview"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/standard/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/standard/src/index.d.ts index d500ddaa82..b2102474bb 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/standard/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/standard/src/index.d.ts @@ -49,6 +49,4 @@ export declare interface User { role: string; } -export declare type Versions = "2022-12-01-preview"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/model/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/model/src/index.d.ts index fb8e970a87..25134248f9 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/model/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/model/src/index.d.ts @@ -27,6 +27,4 @@ export declare interface PostOptionalParams extends OperationOptions { export declare interface PutOptionalParams extends OperationOptions { } -export declare type Versions = "2022-12-01-preview"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/page/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/page/src/index.d.ts index 787ad87e22..5d217d24bc 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/page/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/page/src/index.d.ts @@ -74,6 +74,4 @@ export declare interface UserOrder { detail: string; } -export declare type Versions = "2022-12-01-preview"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/scalar/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/scalar/src/index.d.ts index 24beeaa524..11c421eb04 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/scalar/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/scalar/src/index.d.ts @@ -35,6 +35,4 @@ export declare class ScalarClient { export declare interface ScalarClientOptionalParams extends ClientOptions { } -export declare type Versions = "2022-12-01-preview"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/traits/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/traits/src/index.d.ts index 7380a791b9..cd16e01594 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/traits/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/traits/src/index.d.ts @@ -2,8 +2,6 @@ import { ClientOptions } from '@azure-rest/core-client'; import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; -export declare type RepeatabilityResult = "accepted" | "rejected"; - export declare interface RepeatableActionOptionalParams extends OperationOptions { repeatabilityRequestId?: string; repeatabilityFirstSent?: Date; @@ -42,6 +40,4 @@ export declare interface UserActionResponse { userActionResult: string; } -export declare type Versions = "2022-12-01-preview"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/example/basic/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/example/basic/src/index.d.ts index 15f38874b8..1ecb020f74 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/example/basic/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/example/basic/src/index.d.ts @@ -38,6 +38,4 @@ export declare interface Model { enumProperty?: Enum; } -export declare type Versions = "2022-12-01-preview"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/index.d.ts index ae44b697ba..511996621f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/index.d.ts @@ -101,6 +101,4 @@ export declare interface UserAssignedIdentity { readonly clientId?: string; } -export declare type Versions = "2023-12-01-preview"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/resources/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/resources/src/index.d.ts index d8a4481667..54af1866f2 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/resources/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/resources/src/index.d.ts @@ -47,7 +47,7 @@ export declare interface NestedProxyResource extends ProxyResource { } export declare interface NestedProxyResourceProperties { - readonly provisioningState?: ProvisioningState; + readonly provisioningState?: ProvisioningState_1; description?: string; } @@ -94,6 +94,10 @@ export declare interface PageSettings { export declare type ProvisioningState = ResourceProvisioningState | "Provisioning" | "Updating" | "Deleting" | "Accepted"; +export declare type ProvisioningState_1 = ResourceProvisioningState | "Provisioning" | "Updating" | "Deleting" | "Accepted"; + +export declare type ProvisioningState_2 = ResourceProvisioningState | "Provisioning" | "Updating" | "Deleting" | "Accepted"; + export declare interface ProxyResource extends Resource { } @@ -170,7 +174,7 @@ export declare interface TopLevelTrackedResource extends TrackedResource { } export declare interface TopLevelTrackedResourceProperties { - readonly provisioningState?: ProvisioningState; + readonly provisioningState?: ProvisioningState_2; description?: string; } @@ -213,6 +217,4 @@ export declare interface TrackedResource extends Resource { location: string; } -export declare type Versions = "2023-12-01-preview"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/special-headers/client-request-id/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/special-headers/client-request-id/src/index.d.ts index 612245f692..24a9e93eff 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/special-headers/client-request-id/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/special-headers/client-request-id/src/index.d.ts @@ -6,14 +6,14 @@ export declare interface GetOptionalParams extends OperationOptions { clientRequestId?: string; } -export declare class XmsRequestIdClient { +export declare class XmsClientRequestIdClient { private _client; readonly pipeline: Pipeline; - constructor(options?: XmsRequestIdClientOptionalParams); + constructor(options?: XmsClientRequestIdClientOptionalParams); get(options?: GetOptionalParams): Promise; } -export declare interface XmsRequestIdClientOptionalParams extends ClientOptions { +export declare interface XmsClientRequestIdClientOptionalParams extends ClientOptions { } export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/client/naming/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/client/naming/src/index.d.ts index 6588f5f6d6..b8c6c3a6e1 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/client/naming/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/client/naming/src/index.d.ts @@ -39,7 +39,7 @@ export declare interface CompatibleWithEncodedNameOptionalParams extends Operati export declare type ExtensibleEnum = "value1" | "value2"; export declare interface LanguageClientNameModel { - tSName: boolean; + TSName: boolean; } export declare interface LanguageOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/client/structure/client-operation-group/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/client/structure/client-operation-group/src/index.d.ts index 8a900ce95d..a642def8f0 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/client/structure/client-operation-group/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/client/structure/client-operation-group/src/index.d.ts @@ -50,13 +50,11 @@ export declare interface OneOptionalParams extends OperationOptions { export declare class SecondClient { private _client; readonly pipeline: Pipeline; - constructor(endpointParam: string, clientParam: SecondClientClientType, options?: SecondClientOptionalParams); + constructor(endpointParam: string, clientParam: ClientType, options?: SecondClientOptionalParams); five(options?: FiveOptionalParams): Promise; readonly group5: Group5Operations; } -export declare type SecondClientClientType = "default" | "multi-client" | "renamed-operation" | "two-operation-group"; - export declare interface SecondClientOptionalParams extends ClientOptions { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/client/structure/multi-client/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/client/structure/multi-client/src/index.d.ts index 84ef841fa1..9eb84b921a 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/client/structure/multi-client/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/client/structure/multi-client/src/index.d.ts @@ -2,30 +2,28 @@ import { ClientOptions } from '@azure-rest/core-client'; import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; -export declare class AClient { +export declare class ClientAClient { private _client; readonly pipeline: Pipeline; - constructor(endpointParam: string, clientParam: ClientType, options?: AClientOptionalParams); + constructor(endpointParam: string, clientParam: ClientType, options?: ClientAClientOptionalParams); renamedOne(options?: RenamedOneOptionalParams): Promise; renamedThree(options?: RenamedThreeOptionalParams): Promise; renamedFive(options?: RenamedFiveOptionalParams): Promise; } -export declare interface AClientOptionalParams extends ClientOptions { +export declare interface ClientAClientOptionalParams extends ClientOptions { } -export declare class BClient { +export declare class ClientBClient { private _client; readonly pipeline: Pipeline; - constructor(endpointParam: string, clientParam: BClientClientType, options?: BClientOptionalParams); + constructor(endpointParam: string, clientParam: ClientType, options?: ClientBClientOptionalParams); renamedTwo(options?: RenamedTwoOptionalParams): Promise; renamedFour(options?: RenamedFourOptionalParams): Promise; renamedSix(options?: RenamedSixOptionalParams): Promise; } -export declare type BClientClientType = "default" | "multi-client" | "renamed-operation" | "two-operation-group"; - -export declare interface BClientOptionalParams extends ClientOptions { +export declare interface ClientBClientOptionalParams extends ClientOptions { } export declare type ClientType = "default" | "multi-client" | "renamed-operation" | "two-operation-group"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/parameters/spread/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/parameters/spread/src/index.d.ts index df8ee5f88a..3a4ec6f23f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/parameters/spread/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/parameters/spread/src/index.d.ts @@ -31,14 +31,6 @@ export declare interface BodyParameter { name: string; } -export declare interface CompositeRequestMix { - prop: string; -} - -export declare interface InnerModel { - name: string; -} - export declare interface ModelOperations { spreadAsRequestBody: (name: string, options?: ModelSpreadAsRequestBodyOptionalParams) => Promise; spreadCompositeRequestOnlyWithBody: (body: BodyParameter, options?: ModelSpreadCompositeRequestOnlyWithBodyOptionalParams) => Promise; diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/src/index.d.ts index 8431c781c5..bb6b0d9c72 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/src/index.d.ts @@ -32,6 +32,4 @@ export declare interface ResiliencyServiceDrivenClientOptionalParams extends Cli apiVersion?: string; } -export declare type Versions = "v1" | "v2"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/src/index.d.ts index 4dccbb2573..7fd3e13b3d 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/src/index.d.ts @@ -25,6 +25,4 @@ export declare interface ResiliencyServiceDrivenClientOptionalParams extends Cli apiVersion?: string; } -export declare type Versions = "v1"; - export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/server/endpoint/not-defined/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/server/endpoint/not-defined/src/index.d.ts index 9c9830ec3e..26662d6d1e 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/server/endpoint/not-defined/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/server/endpoint/not-defined/src/index.d.ts @@ -5,7 +5,7 @@ import { Pipeline } from '@azure/core-rest-pipeline'; export declare class NotDefinedClient { private _client; readonly pipeline: Pipeline; - constructor(endpoint: string, options?: NotDefinedClientOptionalParams); + constructor(endpointParam: string, options?: NotDefinedClientOptionalParams); valid(options?: ValidOptionalParams): Promise; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/server/path/multiple/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/server/path/multiple/src/index.d.ts index 2325e7e43a..b26635ddeb 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/server/path/multiple/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/server/path/multiple/src/index.d.ts @@ -11,7 +11,7 @@ export declare class MultipleClient { } export declare interface MultipleClientOptionalParams extends ClientOptions { - apiVersion?: Versions; + apiVersion?: string; } export declare interface NoOperationParamsOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/server/versions/versioned/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/server/versions/versioned/src/index.d.ts index f25e7ff3d6..7656c6703e 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/server/versions/versioned/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/server/versions/versioned/src/index.d.ts @@ -13,10 +13,9 @@ export declare class VersionedClient { } export declare interface VersionedClientOptionalParams extends ClientOptions { + apiVersion?: string; } -export declare type Versions = "2021-01-01-preview" | "2022-12-01-preview"; - export declare interface WithoutApiVersionOptionalParams extends OperationOptions { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/special-words/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/special-words/src/index.d.ts index 720b964e08..6fd479057a 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/special-words/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/special-words/src/index.d.ts @@ -74,10 +74,9 @@ export declare interface From { name: string; } -declare interface Global_2 { +export declare interface GlobalModel { name: string; } -export { Global_2 as Global } export declare interface If { name: string; @@ -125,7 +124,7 @@ export declare interface ModelsOperations { withFinally: (body: Finally, options?: ModelsWithFinallyOptionalParams) => Promise; withFor: (body: For, options?: ModelsWithForOptionalParams) => Promise; withFrom: (body: From, options?: ModelsWithFromOptionalParams) => Promise; - withGlobal: (body: Global_2, options?: ModelsWithGlobalOptionalParams) => Promise; + withGlobal: (body: GlobalModel, options?: ModelsWithGlobalOptionalParams) => Promise; withIf: (body: If, options?: ModelsWithIfOptionalParams) => Promise; withImport: (body: Import, options?: ModelsWithImportOptionalParams) => Promise; withIn: (body: In, options?: ModelsWithInOptionalParams) => Promise; @@ -536,7 +535,7 @@ export declare interface Return { } export declare interface SameAsModel { - sameAsModel: string; + SameAsModel: string; } export declare class SpecialWordsClient { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/nested-discriminator/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/nested-discriminator/src/index.d.ts index 61cbe33b89..32d27f131c 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/nested-discriminator/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/nested-discriminator/src/index.d.ts @@ -3,8 +3,8 @@ import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; export declare interface Fish { - age: number; kind: string; + age: number; } export declare type FishUnion = SharkUnion | Salmon | Fish; diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/single-discriminator/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/single-discriminator/src/index.d.ts index 2c4613a617..a462a79cbc 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/single-discriminator/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/single-discriminator/src/index.d.ts @@ -10,8 +10,8 @@ export declare interface Bird { export declare type BirdUnion = SeaGull | Sparrow | Goose | Eagle | Bird; export declare interface Dinosaur { - size: number; kind: string; + size: number; } export declare type DinosaurUnion = TRex | Dinosaur; diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/union/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/union/src/index.d.ts index 3a8c79d748..8f2ba23e83 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/union/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/union/src/index.d.ts @@ -12,7 +12,7 @@ export declare interface Dog { export declare interface EnumsOnlyCases { lr: Lr | Ud; - ud: Ud | Ud; + ud: Ud; } export declare interface EnumsOnlyGetOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/modelInheritanceNestedDiscriminator.spec.ts b/packages/typespec-ts/test/modularIntegration/modelInheritanceNestedDiscriminator.spec.ts index 31aa6eac6d..d87543f2e5 100644 --- a/packages/typespec-ts/test/modularIntegration/modelInheritanceNestedDiscriminator.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/modelInheritanceNestedDiscriminator.spec.ts @@ -102,8 +102,8 @@ describe("NestedDiscriminatorClient Rest Client", () => { try { const result = await client.getRecursiveModel(); assert.strictEqual( - JSON.stringify(result), - JSON.stringify(validRecursiveBody) + JSON.stringify(result, Object.keys(result).sort()), + JSON.stringify(validRecursiveBody, Object.keys(validRecursiveBody).sort()) ); if (result.kind === "salmon") { assert.strictEqual( diff --git a/packages/typespec-ts/test/modularIntegration/specialWords.spec.ts b/packages/typespec-ts/test/modularIntegration/specialWords.spec.ts index c33cc2b578..acc7bba74d 100644 --- a/packages/typespec-ts/test/modularIntegration/specialWords.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/specialWords.spec.ts @@ -14,7 +14,7 @@ describe("Special Words Client", () => { it("should post modelProperties sameAsModel", async () => { try { const result = await client.modelProperties.sameAsModel({ - sameAsModel: "ok" + SameAsModel: "ok" }); assert.equal(result, undefined); } catch (err) { diff --git a/packages/typespec-ts/test/modularUnit/anonymousModel.spec.ts b/packages/typespec-ts/test/modularUnit/anonymousModel.spec.ts index 346fe0a845..8077be92b9 100644 --- a/packages/typespec-ts/test/modularUnit/anonymousModel.spec.ts +++ b/packages/typespec-ts/test/modularUnit/anonymousModel.spec.ts @@ -4,6 +4,7 @@ import { emitModularOperationsFromTypeSpec } from "../util/emitUtil.js"; import { assertEqualContent } from "../util/testUtil.js"; +import { NameType, normalizeName } from "@azure-tools/rlc-common"; describe("anonymous model", () => { describe("in request", async () => { @@ -31,19 +32,21 @@ describe("anonymous model", () => { export interface Bar { prop1: string; prop2: number; - }` + }`, + true ); const serializer = modelFile?.getFunction("barSerializer")?.getText(); await assertEqualContent( serializer!, ` - export function barSerializer(item: Bar): Record { + export function barSerializer(item: Bar): any { return { prop1: item["prop1"], prop2: item["prop2"], } - };` + };`, + true ); const operationFiles = @@ -56,9 +59,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -140,25 +143,28 @@ describe("anonymous model", () => { await assertEqualContent( modelFile?.getInterface("Bar")?.getFullText()!, ` + /** model interface Bar */ export interface Bar { prop1: string; prop2: number; - }` + }`, + true ); await assertEqualContent( modelFile?.getFunction("barSerializer")?.getFullText()!, ` - export function barSerializer(item: Bar): Record { + export function barSerializer(item: Bar): any { return { prop1: item["prop1"], prop2: item["prop2"], } - }` + }`, + true ); const optionFile = await emitModularModelsFromTypeSpec( tspContent, - true + { needOptions: true } ); assert.ok(optionFile); await assertEqualContent( @@ -182,9 +188,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, @@ -265,27 +271,30 @@ describe("anonymous model", () => { await assertEqualContent( modelFile?.getInterface("Bar")?.getFullText()!, ` + /** model interface Bar */ export interface Bar { prop1: string; prop2: number; - }` + }`, + true ); const serializer = modelFile?.getFunction("barSerializer")?.getText(); await assertEqualContent( serializer!, ` - export function barSerializer(item: Bar): Record { + export function barSerializer(item: Bar): any { return { prop1: item["prop1"], prop2: item["prop2"], } - };` + };`, + true ); const optionFile = await emitModularModelsFromTypeSpec( tspContent, - true + { needOptions: true } ); assert.ok(optionFile); await assertEqualContent( @@ -309,9 +318,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -389,15 +398,18 @@ describe("anonymous model", () => { await assertEqualContent( modelFile?.getInterface("Bar")?.getFullText()!, ` + /** model interface Bar */ export interface Bar { prop1: string; prop2: number; - }` + }`, + true ); await assertEqualContent( modelFile?.getInterface("Foo")?.getFullText()!, ` + /** model interface Foo */ export interface Foo { prop1: string; prop2: number; @@ -410,26 +422,28 @@ describe("anonymous model", () => { await assertEqualContent( modelFile?.getFunction("barSerializer")?.getText()!, ` - export function barSerializer(item: Bar): Record { + export function barSerializer(item: Bar): any { return { prop1: item["prop1"], prop2: item["prop2"], } - };` + };`, + true ); await assertEqualContent( modelFile?.getFunction("fooSerializer")?.getText()!, ` - export function fooSerializer(item: Foo): Record { + export function fooSerializer(item: Foo): any { return { prop1: item["prop1"], prop2: item["prop2"], prop3: item["prop3"].toISOString(), prop4: item["prop4"], - prop5: barSerializer(item.prop5), + prop5: barSerializer(item["prop5"]), } - };` + };`, + true ); const operationFiles = @@ -442,9 +456,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, @@ -458,13 +472,7 @@ describe("anonymous model", () => { .post({ ...operationOptionsToRequestParameters(options), queryParameters: { queryParam: queryParam }, - body: { - prop1: body["prop1"], - prop2: body["prop2"], - prop3: body["prop3"].toISOString(), - prop4: body["prop4"], - prop5: barSerializer(body.prop5), - }, + body: fooSerializer(body), }); } export async function _readDeserialize(result: PathUncheckedResponse): Promise { @@ -499,7 +507,8 @@ describe("anonymous model", () => { op read(@path pathParam: string, @query queryParam: string, @body body: {}): OkResponse; `; const modelFile = await emitModularModelsFromTypeSpec(tspContent); - assert.isUndefined(modelFile); + assert.ok(modelFile); + assertEqualContent(modelFile?.getFullText()!, ``); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -510,9 +519,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, @@ -526,7 +535,7 @@ describe("anonymous model", () => { .post({ ...operationOptionsToRequestParameters(options), queryParameters: { queryParam: queryParam }, - body: body + body: _readRequestSerializer(body), }); } export async function _readDeserialize(result: PathUncheckedResponse): Promise { @@ -566,20 +575,23 @@ describe("anonymous model", () => { await assertEqualContent( modelFile?.getInterface("Bar")?.getFullText()!, ` + /** model interface Bar */ export interface Bar { prop1: string; prop2: number; - }` + }`, + true ); await assertEqualContent( modelFile?.getFunction("barSerializer")?.getFullText()!, ` - export function barSerializer(item: Bar): Record { + export function barSerializer(item: Bar): any { return { prop1: item["prop1"], prop2: item["prop2"], } - }` + }`, + true ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); @@ -591,9 +603,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, @@ -607,7 +619,7 @@ describe("anonymous model", () => { .post({ ...operationOptionsToRequestParameters(options), queryParameters: { queryParam: queryParam }, - body: { prop1: test["prop1"], prop2: barSerializer(test.prop2) }, + body: _readRequestSerializer(test), }); } export async function _readDeserialize(result: PathUncheckedResponse): Promise { @@ -651,20 +663,20 @@ describe("anonymous model", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { color: Record; - }` + }`, ); const serializer = modelFile?.getFunction("testSerializer")?.getText(); await assertEqualContent( serializer!, ` - export function testSerializer(item: Test): Record { - return { - color: item["color"], - } - };` + export function testSerializer(item: Test): any { + return { color: _testColorSerializer(item["color"]) }; + };`, + true ); const operationFiles = @@ -677,9 +689,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, @@ -690,7 +702,7 @@ describe("anonymous model", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { color: body["color"] }, + body: testSerializer(body), }); } export async function _readDeserialize(result: PathUncheckedResponse): Promise { @@ -726,20 +738,21 @@ describe("anonymous model", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { color: { foo?: string }; - }` + }`, + true ); const serializer = modelFile?.getFunction("testSerializer")?.getText(); await assertEqualContent( serializer!, ` - export function testSerializer(item: Test): Record { - return { - color: {foo: item.color["foo"]}, - } - };` + export function testSerializer(item: Test): any { + return { color: _testColorSerializer(item["color"]) }; + };`, + true ); const operationFiles = @@ -752,9 +765,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, @@ -765,7 +778,7 @@ describe("anonymous model", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { color: { foo: body.color["foo"] } }, + body: testSerializer(body), }); } export async function _readDeserialize(result: PathUncheckedResponse): Promise { @@ -793,7 +806,8 @@ describe("anonymous model", () => { describe("happens at body parameter", async () => { async function verifyReturnTypeAsEmpty( operationDetail: string, - returnType: string + returnType: string, + deserializer?: string ) { await assertEqualContent( operationDetail, @@ -801,9 +815,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, @@ -818,7 +832,7 @@ describe("anonymous model", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return result.body ${returnType.startsWith("Record") ? "as any" : ""}; + return ${deserializer ?? normalizeName(returnType, NameType.Operation)}Deserializer(result.body); } export async function read( context: Client, @@ -838,14 +852,17 @@ describe("anonymous model", () => { op read(): { @body _: {}; }; `; // No models.ts file generated - assert.isUndefined(await emitModularModelsFromTypeSpec(tspContent)); + const modelsFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelsFile); + assertEqualContent(modelsFile?.getFullText()!, ``); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.equal(operationFiles?.length, 1); // Generate the operations.ts file with empty model await verifyReturnTypeAsEmpty( operationFiles?.[0]?.getFullText()!, - "Record" + "Record", + "_readResponse" ); }); @@ -859,7 +876,12 @@ describe("anonymous model", () => { await assertEqualContent( modelFile?.getFullText()!, ` + /** model interface PublishResult */ export interface PublishResult {} + + export function publishResultDeserializer(item: any): PublishResult { + return item as any; + } ` ); const operationFiles = @@ -878,7 +900,9 @@ describe("anonymous model", () => { op read(): { foo?: {bar: string | null}}; `; // No models.ts file generated - assert.isUndefined(await emitModularModelsFromTypeSpec(tspContent)); + const modelsFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelsFile); + assertEqualContent(modelsFile?.getFullText()!, ``); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.equal(operationFiles?.length, 1); @@ -889,9 +913,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, @@ -908,9 +932,7 @@ describe("anonymous model", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - foo: !result.body.foo ? undefined : { bar: result.body.foo?.["bar"] }, - }; + return _readResponseDeserializer(result.body); } export async function read( context: Client, @@ -945,17 +967,101 @@ describe("anonymous model", () => { await assertEqualContent( modelFile?.getFullText()!, ` - export interface ReturnBody { - emptyAnomyous: Record; - emptyAnomyousArray: Record[]; - emptyAnomyousDict: Record>; - emptyModel: EmptyModel; - emptyModelArray: EmptyModel[]; - emptyModelDict: Record; - } - - export interface EmptyModel {} - ` + /** model interface ReturnBody */ + export interface ReturnBody { + emptyAnomyous: Record; + emptyAnomyousArray: Record[]; + emptyAnomyousDict: Record>; + emptyModel: EmptyModel; + emptyModelArray: EmptyModel[]; + emptyModelDict: Record; + } + + export function returnBodyDeserializer(item: any): ReturnBody { + return { + emptyAnomyous: _returnBodyEmptyAnomyousDeserializer(item["emptyAnomyous"]), + emptyAnomyousArray: returnBodyEmptyAnomyousArrayArrayDeserializer( + item["emptyAnomyousArray"], + ), + emptyAnomyousDict: returnBodyEmptyAnomyousDictRecordDeserializer( + item["emptyAnomyousDict"], + ), + emptyModel: emptyModelDeserializer(item["emptyModel"]), + emptyModelArray: emptyModelArrayDeserializer(item["emptyModelArray"]), + emptyModelDict: emptyModelRecordDeserializer(item["emptyModelDict"]), + }; + } + + /** model interface _ReturnBodyEmptyAnomyous */ + export interface _ReturnBodyEmptyAnomyous {} + + export function _returnBodyEmptyAnomyousDeserializer( + item: any, + ): _ReturnBodyEmptyAnomyous { + return item as any; + } + + /** model interface _ReturnBodyEmptyAnomyousArray */ + export interface _ReturnBodyEmptyAnomyousArray {} + + export function _returnBodyEmptyAnomyousArrayDeserializer( + item: any, + ): _ReturnBodyEmptyAnomyousArray { + return item as any; + } + + export function returnBodyEmptyAnomyousArrayArrayDeserializer( + result: Array<_ReturnBodyEmptyAnomyousArray>, + ): any[] { + return result.map((item) => { + return _returnBodyEmptyAnomyousArrayDeserializer(item); + }); + } + + /** model interface _ReturnBodyEmptyAnomyousDict */ + export interface _ReturnBodyEmptyAnomyousDict {} + + export function _returnBodyEmptyAnomyousDictDeserializer( + item: any, + ): _ReturnBodyEmptyAnomyousDict { + return item as any; + } + + export function returnBodyEmptyAnomyousDictRecordDeserializer( + item: Record, + ): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _returnBodyEmptyAnomyousDictDeserializer(item[key]); + }); + return result; + } + + /** model interface EmptyModel */ + export interface EmptyModel {} + + export function emptyModelDeserializer(item: any): EmptyModel { + return item as any; + } + + export function emptyModelArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return emptyModelDeserializer(item); + }); + } + + export function emptyModelRecordDeserializer( + item: Record, + ): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] ? item[key] : emptyModelDeserializer(item[key]); + }); + return result; + } + ` ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); @@ -966,9 +1072,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -988,16 +1094,7 @@ describe("anonymous model", () => { throw createRestError(result); } - return { - emptyAnomyous: result.body["emptyAnomyous"], - emptyAnomyousArray: result.body["emptyAnomyousArray"], - emptyAnomyousDict: result.body["emptyAnomyousDict"], - emptyModel: {}, - emptyModelArray: result.body["emptyModelArray"].map((p: any) => { - return {}; - }), - emptyModelDict: result.body["emptyModelDict"], - }; + return returnBodyDeserializer(result.body); } export async function read( @@ -1032,21 +1129,153 @@ describe("anonymous model", () => { await assertEqualContent( modelFile?.getFullText()!, ` - export interface Foz { - baz: { - foo: number[]; - bas: string; - bar?: SimpleModel[]; - nonemptyAnomyous: { a: string }; - nonemptyAnomyousArray: { b?: Record }[]; - nonemptyAnomyousDict: Record; - }; - } - - export interface SimpleModel { - test: string; - } - ` + /** model interface Foz */ + export interface Foz { + baz: { + foo: number[]; + bas: string; + bar?: SimpleModel[]; + nonemptyAnomyous: { + a: string; + }; + nonemptyAnomyousArray: { + b?: Record; + }[]; + nonemptyAnomyousDict: Record< + string, + { + c: number[]; + } + >; + }; + } + + export function fozDeserializer(item: any): Foz { + return { + baz: _fozBazDeserializer(item["baz"]), + }; + } + + /** model interface _FozBaz */ + export interface _FozBaz { + foo: number[]; + bas: string; + bar?: SimpleModel[]; + nonemptyAnomyous: { + a: string; + }; + nonemptyAnomyousArray: { + b?: Record; + }[]; + nonemptyAnomyousDict: Record< + string, + { + c: number[]; + } + >; + } + + export function _fozBazDeserializer(item: any): _FozBaz { + return { + foo: item["foo"].map((p: any) => { + return p; + }), + bas: item["bas"], + bar: !item["test"] + ? item["test"] + : simpleModelArrayDeserializer(item["test"]), + nonemptyAnomyous: _fozBazNonemptyAnomyousDeserializer( + item["nonemptyAnomyous"], + ), + nonemptyAnomyousArray: fozBazNonemptyAnomyousArrayArrayDeserializer( + item["nonemptyAnomyousArray"], + ), + nonemptyAnomyousDict: fozBazNonemptyAnomyousDictRecordDeserializer( + item["nonemptyAnomyousDict"], + ), + }; + } + + /** model interface SimpleModel */ + export interface SimpleModel { + test: string; + } + + export function simpleModelDeserializer(item: any): SimpleModel { + return { + test: item["test"], + }; + } + + export function simpleModelArrayDeserializer( + result: Array, + ): any[] { + return result.map((item) => { + return simpleModelDeserializer(item); + }); + } + + /** model interface _FozBazNonemptyAnomyous */ + export interface _FozBazNonemptyAnomyous { + a: string; + } + + export function _fozBazNonemptyAnomyousDeserializer( + item: any, + ): _FozBazNonemptyAnomyous { + return { + a: item["a"], + }; + } + + /** model interface _FozBazNonemptyAnomyousArray */ + export interface _FozBazNonemptyAnomyousArray { + b?: Record; + } + + export function _fozBazNonemptyAnomyousArrayDeserializer( + item: any, + ): _FozBazNonemptyAnomyousArray { + return { + b: item["b"], + }; + } + + export function fozBazNonemptyAnomyousArrayArrayDeserializer( + result: Array<_FozBazNonemptyAnomyousArray>, + ): any[] { + return result.map((item) => { + return _fozBazNonemptyAnomyousArrayDeserializer(item); + }); + } + + /** model interface _FozBazNonemptyAnomyousDict */ + export interface _FozBazNonemptyAnomyousDict { + c: number[]; + } + + export function _fozBazNonemptyAnomyousDictDeserializer( + item: any, + ): _FozBazNonemptyAnomyousDict { + return { + c: item["c"].map((p: any) => { + return p; + }), + }; + } + + export function fozBazNonemptyAnomyousDictRecordDeserializer( + item: Record, + ): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _fozBazNonemptyAnomyousDictDeserializer(item[key]); + }); + return result; + } + ` ); const operationFiles = @@ -1058,9 +1287,9 @@ describe("anonymous model", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -1078,23 +1307,7 @@ describe("anonymous model", () => { throw createRestError(result); } - return { - baz: { - foo: result.body.baz["foo"], - bas: result.body.baz["bas"], - bar: - result.body.baz["test"] === undefined - ? result.body.baz["test"] - : result.body.baz["test"].map((p: any) => { - return { test: p["test"] }; - }), - nonemptyAnomyous: { a: result.body.baz.nonemptyAnomyous["a"] }, - nonemptyAnomyousArray: result.body.baz["nonemptyAnomyousArray"].map((p: any) => { - return { b: p["b"] }; - },), - nonemptyAnomyousDict: result.body.baz["nonemptyAnomyousDict"], - }, - }; + return fozDeserializer(result.body); } export async function read( diff --git a/packages/typespec-ts/test/modularUnit/apiOperations.spec.ts b/packages/typespec-ts/test/modularUnit/apiOperations.spec.ts index d21fa35725..4a23ff7fdc 100644 --- a/packages/typespec-ts/test/modularUnit/apiOperations.spec.ts +++ b/packages/typespec-ts/test/modularUnit/apiOperations.spec.ts @@ -1,6 +1,7 @@ import { emitModularClientContextFromTypeSpec, emitModularClientFromTypeSpec, + emitModularModelsFromTypeSpec, emitModularOperationsFromTypeSpec } from "../util/emitUtil.js"; @@ -26,9 +27,9 @@ describe("api operations in Modular", () => { `import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _uploadFileViaBodySend( context: Client, @@ -84,9 +85,9 @@ describe("api operations in Modular", () => { `import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _uploadFileViaBodySend( context: Client, @@ -133,6 +134,31 @@ describe("api operations in Modular", () => { } ): void; `; + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + await assertEqualContent( + modelFile?.getInterface("_UploadFileRequest")?.getFullText()!, + ` + /** model interface _UploadFileRequest */ + export interface _UploadFileRequest { + name: string; + file: Uint8Array; + } + ` + ); + + const serializer = modelFile?.getFunction("_uploadFileRequestSerializer")?.getText(); + await assertEqualContent( + serializer!, + ` + export function _uploadFileRequestSerializer(item: _UploadFileRequest): any { + return { + name: item["name"], + file: uint8ArrayToString(item["file"], "base64"), + }; + } + ` + ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -142,11 +168,11 @@ describe("api operations in Modular", () => { `import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; - import { uint8ArrayToString } from "@azure/core-util"; + export function _uploadFileSend( context: Client, body: { name: string; file: Uint8Array }, @@ -157,10 +183,7 @@ describe("api operations in Modular", () => { .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - name: body["name"], - file: uint8ArrayToString(body["file"], "base64"), - }, + body: _uploadFileRequestSerializer(body), }); } export async function _uploadFileDeserialize( @@ -196,6 +219,27 @@ describe("api operations in Modular", () => { } ): void; `; + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + await assertEqualContent(modelFile?.getFullText()!, + ` + import { uint8ArrayToString } from "@azure/core-util"; + + /** model interface _UploadFilesRequest */ + export interface _UploadFilesRequest { + files: Uint8Array[]; + } + + export function _uploadFilesRequestSerializer(item: _UploadFilesRequest): any { + return { + files: item["files"].map((p: any) => { + return uint8ArrayToString(p, "base64"); + }), + }; + } + `, + true + ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -205,11 +249,11 @@ describe("api operations in Modular", () => { `import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; - import { uint8ArrayToString } from "@azure/core-util"; + export function _uploadFilesSend( context: Client, body: { files: Uint8Array[] }, @@ -220,9 +264,7 @@ describe("api operations in Modular", () => { .post({ ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - files: body["files"].map((p) => uint8ArrayToString(p, "base64")), - }, + body: _uploadFilesRequestSerializer(body), }); } export async function _uploadFilesDeserialize( @@ -266,9 +308,9 @@ describe("api operations in Modular", () => { `import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _downloadFileSend( context: Client, @@ -285,7 +327,7 @@ describe("api operations in Modular", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return result.body as any; + return result.body; } export async function downloadFile( context: Client, @@ -319,9 +361,9 @@ describe("api operations in Modular", () => { `import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _downloadFileSend( context: Client, @@ -338,7 +380,7 @@ describe("api operations in Modular", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return result.body as any; + return result.body; } export async function downloadFile( context: Client, @@ -363,6 +405,33 @@ describe("api operations in Modular", () => { }; }; `; + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + await assertEqualContent( + modelFile?.getFullText()!, + ` + import { stringToUint8Array } from "@azure/core-util"; + + /** model interface _DownloadFileResponse */ + export interface _DownloadFileResponse { + name: string; + file: Uint8Array; + } + + export function _downloadFileResponseDeserializer( + item: any, + ): _DownloadFileResponse { + return { + name: item["name"], + file: + typeof item["file"] === "string" + ? stringToUint8Array(item["file"], "base64") + : item["file"], + }; + } + `, + true + ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -372,11 +441,10 @@ describe("api operations in Modular", () => { `import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; - import { stringToUint8Array } from "@azure/core-util"; export function _downloadFileSend( context: Client, options: DownloadFileOptionalParams = { requestOptions: {} } @@ -392,13 +460,7 @@ describe("api operations in Modular", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - name: result.body["name"], - file: - typeof result.body["file"] === "string" - ? stringToUint8Array(result.body["file"], "base64") - : result.body["file"], - }; + return _downloadFileResponseDeserializer(result.body); } export async function downloadFile( context: Client, @@ -425,6 +487,32 @@ describe("api operations in Modular", () => { }; }; `; + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + await assertEqualContent( + modelFile?.getFullText()!, + ` + import { stringToUint8Array } from "@azure/core-util"; + + /** model interface _DownloadFileResponse */ + export interface _DownloadFileResponse { + name: string; + file: Uint8Array[]; + } + + export function _downloadFileResponseDeserializer( + item: any, + ): _DownloadFileResponse { + return { + name: item["name"], + file: item["file"].map((p: any) => { + return typeof p === "string" ? stringToUint8Array(p, "base64") : p; + }), + }; + } + `, + true + ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -434,11 +522,10 @@ describe("api operations in Modular", () => { `import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; - import { stringToUint8Array } from "@azure/core-util"; export function _downloadFileSend( context: Client, options: DownloadFileOptionalParams = { requestOptions: {} } @@ -454,12 +541,7 @@ describe("api operations in Modular", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - name: result.body["name"], - file: result.body["file"].map((p: any) => - typeof p === "string" ? stringToUint8Array(p, "base64") : p, - ), - }; + return _downloadFileResponseDeserializer(result.body); } export async function downloadFile( context: Client, @@ -492,9 +574,9 @@ describe("api operations in Modular", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _testSend( @@ -532,8 +614,8 @@ describe("api operations in Modular", () => { await assertEqualContent( clientContext?.getFullText()!, ` - import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; + import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; export interface TestingContext extends Client {} @@ -541,7 +623,7 @@ describe("api operations in Modular", () => { export interface TestingClientOptionalParams extends ClientOptions {} export function createTesting( - endpoint: string, + endpointParam: string, apiVersion: string, options: TestingClientOptionalParams = {}, ): TestingContext { @@ -555,7 +637,7 @@ describe("api operations in Modular", () => { loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info } }; const clientContext = getClient( - options.endpoint ?? options.baseUrl ?? endpoint, + options.endpoint ?? options.baseUrl ?? String(endpointParam), undefined, updatedOptions, ); @@ -584,7 +666,6 @@ describe("api operations in Modular", () => { await assertEqualContent( classicClient?.getFullText()!, ` - import { TokenCredential, KeyCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; export { TestingClientOptionalParams } from "./api/testingContext.js"; @@ -595,7 +676,7 @@ describe("api operations in Modular", () => { public readonly pipeline: Pipeline; constructor( - endpoint: string, + endpointParam: string, apiVersion: string, options: TestingClientOptionalParams = {}, ) { @@ -603,7 +684,7 @@ describe("api operations in Modular", () => { const userAgentPrefix = prefixFromOptions ? \`\${prefixFromOptions} azsdk-js-client\` : "azsdk-js-client"; - this._client = createTesting(endpoint, apiVersion, { + this._client = createTesting(endpointParam, apiVersion, { ...options, userAgentOptions: { userAgentPrefix }, }); @@ -628,11 +709,13 @@ describe("api operations in Modular", () => { `; const operationFiles = await emitModularOperationsFromTypeSpec( tspContent, - false, - true, - false, - false, - true + { + mustEmptyDiagnostic: false, + needNamespaces: true, + needAzureCore: false, + withRawContent: false, + withVersionedApiVersion: true + } ); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -642,9 +725,9 @@ describe("api operations in Modular", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _testSend( @@ -678,15 +761,17 @@ describe("api operations in Modular", () => { ); const clientContext = await emitModularClientContextFromTypeSpec( tspContent, - false, - true + { + withRawContent: false, + withVersionedApiVersion: true + } ); assert.ok(clientContext); await assertEqualContent( clientContext?.getFullText()!, ` - import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; + import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; export interface TestingContext extends Client {} @@ -696,7 +781,7 @@ describe("api operations in Modular", () => { } export function createTesting( - endpoint: string, + endpointParam: string, options: TestingClientOptionalParams = {}, ): TestingContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; @@ -709,7 +794,7 @@ describe("api operations in Modular", () => { loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, }; const clientContext = getClient( - options.endpoint ?? options.baseUrl ?? endpoint, + options.endpoint ?? options.baseUrl ?? String(endpointParam), undefined, updatedOptions, ); @@ -736,14 +821,15 @@ describe("api operations in Modular", () => { ); const classicClient = await emitModularClientFromTypeSpec( tspContent, - false, - true + { + withRawContent: false, + withVersionedApiVersion: true + } ); assert.ok(classicClient); await assertEqualContent( classicClient?.getFullText()!, ` - import { TokenCredential, KeyCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; export { TestingClientOptionalParams } from "./api/testingContext.js"; @@ -754,14 +840,14 @@ describe("api operations in Modular", () => { public readonly pipeline: Pipeline; constructor( - endpoint: string, + endpointParam: string, options: TestingClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? \`\${prefixFromOptions} azsdk-js-client\` : "azsdk-js-client"; - this._client = createTesting(endpoint, { + this._client = createTesting(endpointParam, { ...options, userAgentOptions: { userAgentPrefix }, }); @@ -776,7 +862,8 @@ describe("api operations in Modular", () => { ); }); - it("should generate apiVersion if there's no client level apiVersion", async () => { + // TODO see issue tracked https://github.com/Azure/typespec-azure/issues/1595 + it("should not generate apiVersion if there's no client level apiVersion", async () => { const tspContent = ` model ApiVersionParameter { @query @@ -789,8 +876,10 @@ describe("api operations in Modular", () => { `; const operationFiles = await emitModularOperationsFromTypeSpec( tspContent, - false, - true + { + mustEmptyDiagnostic: false, + needNamespaces: true, + } ); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -800,9 +889,9 @@ describe("api operations in Modular", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _testSend( @@ -872,19 +961,19 @@ describe("api operations in Modular", () => { await assertEqualContent( clientContext?.getFullText()!, ` - import { ClientOptions, Client, getClient } from "@azure-rest/core-client"; import { logger } from "../logger.js"; + import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; export interface TestingContext extends Client {} /** Optional parameters for the client. */ export interface TestingClientOptionalParams extends ClientOptions {} - export function createTesting(endpoint: string, options: TestingClientOptionalParams = {}): TestingContext { + export function createTesting(endpointParam: string, options: TestingClientOptionalParams = {}): TestingContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? \`\${prefixFromOptions} azsdk-js-api\` : "azsdk-js-api"; const { apiVersion: _, ...updatedOptions } = { ...options,userAgentOptions: { userAgentPrefix },loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info },} - const clientContext = getClient(options.endpoint ?? options.baseUrl ?? endpoint, undefined, updatedOptions); + const clientContext = getClient(options.endpoint ?? options.baseUrl ?? String(endpointParam), undefined, updatedOptions); clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); if (options.apiVersion) { logger.warning("This client does not support client api-version, please change it at the operation level"); @@ -898,7 +987,6 @@ describe("api operations in Modular", () => { await assertEqualContent( classicClient?.getFullText()!, ` - import { TokenCredential, KeyCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; export { TestingClientOptionalParams } from "./api/testingContext.js"; @@ -909,14 +997,14 @@ describe("api operations in Modular", () => { public readonly pipeline: Pipeline; constructor( - endpoint: string, + endpointParam: string, options: TestingClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? \`\${prefixFromOptions} azsdk-js-client\` : "azsdk-js-client"; - this._client = createTesting(endpoint, { + this._client = createTesting(endpointParam, { ...options, userAgentOptions: { userAgentPrefix }, }); diff --git a/packages/typespec-ts/test/modularUnit/clientContext.spec.ts b/packages/typespec-ts/test/modularUnit/clientContext.spec.ts index ccb6bdcfa2..2454b2ceb2 100644 --- a/packages/typespec-ts/test/modularUnit/clientContext.spec.ts +++ b/packages/typespec-ts/test/modularUnit/clientContext.spec.ts @@ -2,7 +2,8 @@ import assert from "assert"; import { emitModularClientContextFromTypeSpec } from "../util/emitUtil.js"; import { assertEqualContent } from "../util/testUtil.js"; -describe("modular client context type", () => { +// TODO issue tracked https://github.com/Azure/typespec-azure/issues/1598 +describe.skip("modular client context type", () => { it("handle with no default values in server", async () => { const tspContent = ` import "@typespec/http"; @@ -52,7 +53,9 @@ describe("modular client context type", () => { `; const clientContext = await emitModularClientContextFromTypeSpec( tspContent, - true + { + withRawContent: true + } ); assert.ok(clientContext); await assertEqualContent( @@ -145,7 +148,9 @@ describe("modular client context type", () => { @post op one(): void; `, - true + { + withRawContent: true + } ); assert.ok(clientContext); await assertEqualContent( diff --git a/packages/typespec-ts/test/modularUnit/enumUnion.spec.ts b/packages/typespec-ts/test/modularUnit/enumUnion.spec.ts index c4ea660720..51e8e4c4cb 100644 --- a/packages/typespec-ts/test/modularUnit/enumUnion.spec.ts +++ b/packages/typespec-ts/test/modularUnit/enumUnion.spec.ts @@ -36,8 +36,10 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true + } ); assert.ok(schemaOutput); await assertEqualContent( @@ -53,10 +55,12 @@ describe("header parameters", () => { ); const paramOutput = await emitModularOperationsFromTypeSpec( tspDefinition, - false, - false, - false, - true + { + mustEmptyDiagnostic: false, + needNamespaces: false, + needAzureCore: false, + withRawContent: true, + } ); assert.ok(paramOutput); assert.strictEqual(paramOutput?.length, 1); @@ -66,9 +70,9 @@ describe("header parameters", () => { import { DemoServiceContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _getSend( @@ -136,8 +140,10 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true, + } ); assert.ok(schemaOutput); await assertEqualContent( @@ -180,8 +186,10 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true, + } ); assert.ok(schemaOutput); await assertEqualContent( @@ -226,8 +234,10 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true, + } ); assert.ok(schemaOutput); await assertEqualContent( @@ -237,6 +247,18 @@ describe("header parameters", () => { export type JsonContentType = "application/json; serialization=Avro" | "application/json; serialization=json"; /** Alias for SchemaContentTypeValues */ export type SchemaContentTypeValues = JsonContentType | "text/plain; charset=utf-8" | "text/vnd.ms.protobuf" | string; + + export function schemaContentTypeValuesSerializer( + item: SchemaContentTypeValues, + ): any { + return item; + } + + export function schemaContentTypeValuesDeserializer( + item: any, + ): SchemaContentTypeValues { + return item; + } ` ); }); @@ -272,8 +294,10 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true, + } ); assert.ok(schemaOutput); @@ -284,6 +308,18 @@ describe("header parameters", () => { export type JsonContentType = "application/json; serialization=Avro" | "application/json; serialization=json"; /** Alias for SchemaContentTypeValues */ export type SchemaContentTypeValues = JsonContentType | "text/plain; charset=utf-8" | "text/vnd.ms.protobuf" | string; + + export function schemaContentTypeValuesSerializer( + item: SchemaContentTypeValues, + ): any { + return item; + } + + export function schemaContentTypeValuesDeserializer( + item: any, + ): SchemaContentTypeValues { + return item; + } ` ); }); @@ -316,8 +352,10 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true, + } ); assert.ok(schemaOutput); await assertEqualContent( @@ -362,8 +400,10 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true, + } ); assert.ok(schemaOutput); await assertEqualContent( @@ -373,6 +413,18 @@ describe("header parameters", () => { export type JsonContentType = "application/json; serialization=Avro" | "application/json; serialization=json"; /** Alias for SchemaContentTypeValues */ export type SchemaContentTypeValues = JsonContentType | "text/plain; charset=utf-8" | "text/vnd.ms.protobuf" | string; + + export function schemaContentTypeValuesSerializer( + item: SchemaContentTypeValues, + ): any { + return item; + } + + export function schemaContentTypeValuesDeserializer( + item: any, + ): SchemaContentTypeValues { + return item; + } ` ); }); @@ -408,8 +460,10 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true, + } ); assert.ok(schemaOutput); @@ -420,6 +474,18 @@ describe("header parameters", () => { export type JsonContentType = "application/json; serialization=Avro" | "application/json; serialization=json"; /** Alias for SchemaContentTypeValues */ export type SchemaContentTypeValues = JsonContentType | "text/plain; charset=utf-8" | "text/vnd.ms.protobuf" | string; + + export function schemaContentTypeValuesSerializer( + item: SchemaContentTypeValues, + ): any { + return item; + } + + export function schemaContentTypeValuesDeserializer( + item: any, + ): SchemaContentTypeValues { + return item; + } ` ); }); @@ -448,17 +514,20 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true, + } ); assert.isUndefined(schemaOutput); - const paramOutput = await emitModularOperationsFromTypeSpec( tspDefinition, - true, - false, - false, - true + { + mustEmptyDiagnostic: true, + needNamespaces: false, + needAzureCore: false, + withRawContent: true, + } ); assert.ok(paramOutput); assert.strictEqual(paramOutput?.length, 1); @@ -469,9 +538,9 @@ describe("header parameters", () => { import { DemoServiceContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _getSend( context: Client, @@ -529,17 +598,21 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true, + } ); assert.isUndefined(schemaOutput); const paramOutput = await emitModularOperationsFromTypeSpec( tspDefinition, - true, - false, - false, - true + { + mustEmptyDiagnostic: true, + needNamespaces: false, + needAzureCore: false, + withRawContent: true, + } ); assert.ok(paramOutput); assert.strictEqual(paramOutput?.length, 1); @@ -550,9 +623,9 @@ describe("header parameters", () => { import { DemoServiceContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _getSend( context: Client, @@ -623,8 +696,10 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true + } ); assert.ok(schemaOutput); await assertEqualContent( @@ -665,8 +740,10 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true + } ); assert.ok(schemaOutput); await assertEqualContent( @@ -710,8 +787,10 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true + } ); assert.ok(schemaOutput); await assertEqualContent( @@ -760,28 +839,37 @@ describe("header parameters", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true, - false, - false, - false + { + needOptions: false, + withRawContent: true, + needAzureCore: false, + compatibilityMode: false, + mustEmptyDiagnostic: false, + } ); assert.ok(schemaOutput); await assertEqualContent( schemaOutput?.getFullText()!, ` - /** Type of EnumTest */ - export type EnumTest = 1 | 2 | 3 | 4; + /** model interface Foo */ + export interface Foo {} - export interface Foo { - } - - export function fooSerializer(item: Foo) { + export function fooSerializer(item: Foo): any { return item as any; } - + + /** Type of EnumTest */ + export type EnumTest = 1 | 2 | 3 | 4; /** Alias for MixedTypes */ export type MixedTypes = EnumTest | string | Foo; + + export function mixedTypesSerializer(item: MixedTypes): any { + return item; + } + + export function mixedTypesDeserializer(item: any): MixedTypes { + return item; + } ` ); }); @@ -801,6 +889,7 @@ describe("model type", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { color: "red" | "blue"; }` @@ -810,11 +899,10 @@ describe("model type", () => { await assertEqualContent( serializer!, ` - export function testSerializer(item: Test): Record { - return { - color: item["color"], - } - };` + export function testSerializer(item: Test): any { + return { color: item["color"] }; + };`, + true ); }); @@ -833,6 +921,7 @@ describe("model type", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { color: "red"; } @@ -859,6 +948,7 @@ describe("model type", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { content: "red" | null; }` @@ -868,11 +958,12 @@ describe("model type", () => { await assertEqualContent( serializer!, ` - export function testSerializer(item: Test): Record { + export function testSerializer(item: Test): any { return { content: item["content"], } - };` + };`, + true ); }); @@ -887,6 +978,7 @@ describe("model type", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { content: string | null; }` @@ -896,11 +988,12 @@ describe("model type", () => { await assertEqualContent( serializer!, ` - export function testSerializer(item: Test): Record { + export function testSerializer(item: Test): any { return { content: item["content"], } - };` + };`, + true ); }); }); @@ -917,6 +1010,7 @@ describe("model type", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { color: 1 | 2; }` @@ -926,11 +1020,10 @@ describe("model type", () => { await assertEqualContent( serializer!, ` - export function testSerializer(item: Test): Record { - return { - color: item["color"], - } - };` + export function testSerializer(item: Test): any { + return { color: item["color"] }; + };`, + true ); }); @@ -949,6 +1042,7 @@ describe("model type", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { color: 1; } @@ -979,6 +1073,7 @@ describe("model type", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { color: Color | null; } @@ -999,14 +1094,17 @@ describe("model type", () => { } op read(@body body: Test): void; `, - undefined, - undefined, - true + { + needOptions: false, + withRawContent: false, + needAzureCore: true, + } ); assert.ok(modelFile); await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { color: Color | null; } @@ -1062,17 +1160,20 @@ describe("model type", () => { } op read(@body body: Test): void; `, - false, - false, - false, - false, - true, - true + { + needOptions: false, + withRawContent: false, + needAzureCore: false, + compatibilityMode: false, + mustEmptyDiagnostic: true, + experimentalExtensibleEnums: true + } ); assert.ok(modelFile); await assertEqualContent( modelFile!.getInterface("Test")!.getFullText()!, ` + /** model interface Test */ export interface Test { color: ImageSize; } @@ -1083,15 +1184,30 @@ describe("model type", () => { ` /** Known values of {@link ImageSize} that the service accepts. */ export enum KnownImageSize { - /** size256x256 */ + /** + * Very small image size of 256x256 pixels. + * Only supported with dall-e-2 models. + */ size256x256 = "256x256", - /** size512x512 */ + /** + * A smaller image size of 512x512 pixels. + * Only supported with dall-e-2 models. + */ size512x512 = "512x512", - /** size1024x1024 */ + /** + * A standard, square image size of 1024x1024 pixels. + * Supported by both dall-e-2 and dall-e-3 models. + */ size1024x1024 = "1024x1024", - /** size1792x1024 */ + /** + * A wider image size of 1024x1792 pixels. + * Only supported with dall-e-3 models. + */ size1792x1024 = "1792x1024", - /** size1024x1792 */ + /** + * A taller image size of 1792x1024 pixels. + * Only supported with dall-e-3 models. + */ size1024x1792 = "1024x1792", } ` @@ -1118,6 +1234,7 @@ describe("model type", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { color: Lr | Ud; } @@ -1158,6 +1275,7 @@ describe("model type", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { color: LeftAndRight | UpAndDown; } @@ -1189,6 +1307,7 @@ describe("model type", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { content: 1 | null; }` @@ -1198,11 +1317,12 @@ describe("model type", () => { await assertEqualContent( serializer!, ` - export function testSerializer(item: Test): Record { + export function testSerializer(item: Test): any { return { content: item["content"], } - };` + };`, + true ); }); @@ -1217,6 +1337,7 @@ describe("model type", () => { await assertEqualContent( modelFile!.getInterface("Test")?.getFullText()!, ` + /** model interface Test */ export interface Test { content: number | null; }` @@ -1226,11 +1347,12 @@ describe("model type", () => { await assertEqualContent( serializer!, ` - export function testSerializer(item: Test): Record { + export function testSerializer(item: Test): any { return { content: item["content"], } - };` + };`, + true ); }); }); diff --git a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts index c210764678..b8a478ebd0 100644 --- a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts +++ b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts @@ -37,35 +37,39 @@ async function verifyModularPropertyType( @route("/models") @get op getModel(@body input: InputOutputModel): InputOutputModel;`, - needAzureCore + { needAzureCore } ); assert.ok(modelsFile); await assertEqualContent( modelsFile?.getFullText()!, ` ${additionalImports} - + /** model interface InputOutputModel */ export interface InputOutputModel { prop: ${inputType}; } - export function inputOutputModelSerializer(item: InputOutputModel): Record { + export function inputOutputModelSerializer(item: InputOutputModel): any { + return { prop: item["prop"] }; + } + + export function inputOutputModelDeserializer(item: any): InputOutputModel { return { - prop: item["prop"] - } + prop: item["prop"], + }; } ${additionalInputContent}` ); } describe("modular model type", () => { - it("shouldn't generate models if there is no operations", async () => { + it("should not generate models if there is no operations", async () => { const schemaOutput = await emitModularModelsFromTypeSpec(` model Test { prop: string; } `); - assert.ok(!schemaOutput); + assert.isUndefined(schemaOutput); }); }); @@ -131,9 +135,9 @@ describe("model property type", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _createStreamingSend( context: Client, @@ -184,6 +188,7 @@ describe("modular encode test for property type datetime", () => { await assertEqualContent( modelFile?.getInterface("Foo")?.getFullText()!, ` + /** model interface Foo */ export interface Foo { prop1: string; prop2: string; @@ -196,7 +201,7 @@ describe("modular encode test for property type datetime", () => { await assertEqualContent( serializer!, ` - export function fooSerializer(item: Foo): Record { + export function fooSerializer(item: Foo): any { return { prop1: item["prop1"], prop2: item["prop2"], @@ -205,7 +210,19 @@ describe("modular encode test for property type datetime", () => { }; }` ); - + const deserializer = modelFile?.getFunction("fooDeserializer")?.getText(); + await assertEqualContent( + deserializer!, + ` + export function fooDeserializer(item: any): Foo { + return { + prop1: item["prop1"], + prop2: item["prop2"], + prop3: new Date(item["prop3"]), + prop4: item["prop4"], + }; + }` + ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -215,9 +232,9 @@ describe("modular encode test for property type datetime", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -229,12 +246,7 @@ describe("modular encode test for property type datetime", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { - prop1: body["prop1"], - prop2: body["prop2"], - prop3: body["prop3"].toISOString(), - prop4: body["prop4"], - }, + body: fooSerializer(body), }); } @@ -243,12 +255,7 @@ describe("modular encode test for property type datetime", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - prop1: result.body["prop1"], - prop2: result.body["prop2"], - prop3: new Date(result.body["prop3"]), - prop4: result.body["prop4"], - }; + return fooDeserializer(result.body); } export async function read( @@ -276,9 +283,9 @@ describe("modular encode test for property type datetime", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -332,6 +339,7 @@ describe("modular encode test for property type datetime", () => { await assertEqualContent( modelFile?.getInterface("Foo")?.getFullText()!, ` + /** model interface Foo */ export interface Foo { prop1: Date; prop2: string; @@ -342,12 +350,13 @@ describe("modular encode test for property type datetime", () => { await assertEqualContent( serializer!, ` - export function fooSerializer(item: Foo): Record { + export function fooSerializer(item: Foo): any { return { prop1: item["prop1"].toISOString(), prop2: item["prop2"], }; - }` + }`, + true ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); @@ -359,9 +368,9 @@ describe("modular encode test for property type datetime", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -373,10 +382,7 @@ describe("modular encode test for property type datetime", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { - prop1: body["prop1"].toISOString(), - prop2: body["prop2"], - }, + body: fooSerializer(body), }); } @@ -385,10 +391,7 @@ describe("modular encode test for property type datetime", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - prop1: new Date(result.body["prop1"]), - prop2: result.body["prop2"], - }; + return fooDeserializer(result.body); } export async function read( @@ -418,6 +421,7 @@ describe("modular encode test for property type datetime", () => { await assertEqualContent( modelFile?.getInterface("Foo")?.getFullText()!, ` + /** model interface Foo */ export interface Foo { prop1: Date; prop2: string; @@ -428,12 +432,13 @@ describe("modular encode test for property type datetime", () => { await assertEqualContent( serializer!, ` - export function fooSerializer(item: Foo): Record { + export function fooSerializer(item: Foo): any { return { prop1: item["prop1"].toUTCString(), prop2: item["prop2"], }; - }` + }`, + true ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); @@ -445,9 +450,9 @@ describe("modular encode test for property type datetime", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -459,10 +464,7 @@ describe("modular encode test for property type datetime", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { - prop1: body["prop1"].toUTCString(), - prop2: body["prop2"], - }, + body: fooSerializer(body), }); } @@ -471,10 +473,7 @@ describe("modular encode test for property type datetime", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - prop1: new Date(result.body["prop1"]), - prop2: result.body["prop2"], - }; + return fooDeserializer(result.body); } export async function read( @@ -502,6 +501,7 @@ describe("modular encode test for property type datetime", () => { await assertEqualContent( modelFile?.getInterface("Foo")?.getFullText()!, ` + /** model interface Foo */ export interface Foo { prop1: Date; }` @@ -511,11 +511,12 @@ describe("modular encode test for property type datetime", () => { await assertEqualContent( serializer!, ` - export function fooSerializer(item: Foo): Record { + export function fooSerializer(item: Foo): any { return { prop1: item["prop1"].getTime(), }; - }` + }`, + true ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); @@ -527,9 +528,9 @@ describe("modular encode test for property type datetime", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -541,9 +542,7 @@ describe("modular encode test for property type datetime", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { - prop1: body["prop1"].getTime() - }, + body: fooSerializer(body), }); } @@ -552,9 +551,7 @@ describe("modular encode test for property type datetime", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - prop1: new Date(result.body["prop1"]), - }; + return fooDeserializer(result.body); } export async function read( @@ -583,6 +580,7 @@ describe("modular encode test for property type duration", () => { await assertEqualContent( modelFile?.getInterface("Foo")?.getFullText()!, ` + /** model interface Foo */ export interface Foo { prop1: string; }` @@ -596,9 +594,9 @@ describe("modular encode test for property type duration", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -610,9 +608,7 @@ describe("modular encode test for property type duration", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { - prop1: body["prop1"], - }, + body: fooSerializer(body), }); } @@ -621,9 +617,7 @@ describe("modular encode test for property type duration", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - prop1: result.body["prop1"], - }; + return fooDeserializer(result.body); } export async function read( @@ -651,6 +645,7 @@ describe("modular encode test for property type duration", () => { await assertEqualContent( modelFile?.getInterface("Foo")?.getFullText()!, ` + /** model interface Foo */ export interface Foo { prop1: string; }` @@ -663,10 +658,10 @@ describe("modular encode test for property type duration", () => { ` import { TestingContext as Client } from "./index.js"; import { - StreamableMethod, - operationOptionsToRequestParameters, + StreamableMethod, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -678,9 +673,7 @@ describe("modular encode test for property type duration", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { - prop1: body["prop1"], - }, + body: fooSerializer(body), }); } @@ -689,9 +682,7 @@ describe("modular encode test for property type duration", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - prop1: result.body["prop1"], - }; + return fooDeserializer(result.body); } export async function read( @@ -721,6 +712,7 @@ describe("modular encode test for property type duration", () => { await assertEqualContent( modelFile?.getInterface("Foo")?.getFullText()!, ` + /** model interface Foo */ export interface Foo { prop1: number; prop2: number; @@ -735,9 +727,9 @@ describe("modular encode test for property type duration", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -749,10 +741,7 @@ describe("modular encode test for property type duration", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { - prop1: body["prop1"], - prop2: body["prop2"], - }, + body: fooSerializer(body), }); } @@ -761,10 +750,7 @@ describe("modular encode test for property type duration", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - prop1: result.body["prop1"], - prop2: result.body["prop2"], - }; + return fooDeserializer(result.body); } export async function read( @@ -793,20 +779,38 @@ describe("modular encode test for property type bytes", () => { await assertEqualContent( modelFile?.getInterface("Foo")?.getFullText()!, ` + /** model interface Foo */ export interface Foo { prop1: Uint8Array; - }` + }`, + true ); const serializer = modelFile?.getFunction("fooSerializer")?.getText(); await assertEqualContent( serializer!, ` - export function fooSerializer(item: Foo): Record { + export function fooSerializer(item: Foo): any { return { prop1: uint8ArrayToString(item["prop1"], "base64"), } - };` + }`, + true + ); + + const deserializer = modelFile?.getFunction("fooDeserializer")?.getText(); + await assertEqualContent( + deserializer!, + ` + export function fooDeserializer(item: any): Foo { + return { + prop1: + typeof item["prop1"] === "string" + ? stringToUint8Array(item["prop1"], "base64") + : item["prop1"], + }; + }`, + true ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); @@ -818,11 +822,10 @@ describe("modular encode test for property type bytes", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; - import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; export function _readSend( context: Client, @@ -833,9 +836,7 @@ describe("modular encode test for property type bytes", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { - prop1: uint8ArrayToString(body["prop1"], "base64"), - }, + body: fooSerializer(body), }); } @@ -844,12 +845,7 @@ describe("modular encode test for property type bytes", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - prop1: - typeof result.body["prop1"] === "string" - ? stringToUint8Array(result.body["prop1"], "base64") - : result.body["prop1"], - }; + return fooDeserializer(result.body); } export async function read( @@ -877,10 +873,38 @@ describe("modular encode test for property type bytes", () => { await assertEqualContent( modelFile?.getInterface("Foo")?.getFullText()!, ` + /** model interface Foo */ export interface Foo { prop1: Uint8Array; }` ); + + const serializer = modelFile?.getFunction("fooSerializer")?.getText(); + await assertEqualContent( + serializer!, + ` + export function fooSerializer(item: Foo): any { + return { + prop1: uint8ArrayToString(item["prop1"], "base64"), + } + }`, + true + ); + + const deserializer = modelFile?.getFunction("fooDeserializer")?.getText(); + await assertEqualContent( + deserializer!, + ` + export function fooDeserializer(item: any): Foo { + return { + prop1: + typeof item["prop1"] === "string" + ? stringToUint8Array(item["prop1"], "base64") + : item["prop1"], + }; + }`, + true + ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -890,11 +914,10 @@ describe("modular encode test for property type bytes", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; - import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; export function _readSend( context: Client, @@ -905,9 +928,7 @@ describe("modular encode test for property type bytes", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { - prop1: uint8ArrayToString(body["prop1"], "base64"), - }, + body: fooSerializer(body) }); } @@ -916,12 +937,7 @@ describe("modular encode test for property type bytes", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - prop1: - typeof result.body["prop1"] === "string" - ? stringToUint8Array(result.body["prop1"], "base64") - : result.body["prop1"], - }; + return fooDeserializer(result.body); } export async function read( @@ -949,10 +965,38 @@ describe("modular encode test for property type bytes", () => { await assertEqualContent( modelFile?.getInterface("Foo")?.getFullText()!, ` + /** model interface Foo */ export interface Foo { prop1: Uint8Array; }` ); + + const serializer = modelFile?.getFunction("fooSerializer")?.getText(); + await assertEqualContent( + serializer!, + ` + export function fooSerializer(item: Foo): any { + return { + prop1: uint8ArrayToString(item["prop1"], "base64url"), + } + }`, + true + ); + + const deserializer = modelFile?.getFunction("fooDeserializer")?.getText(); + await assertEqualContent( + deserializer!, + ` + export function fooDeserializer(item: any): Foo { + return { + prop1: + typeof item["prop1"] === "string" + ? stringToUint8Array(item["prop1"], "base64url") + : item["prop1"], + }; + }`, + true + ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -962,12 +1006,11 @@ describe("modular encode test for property type bytes", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; - import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; - + export function _readSend( context: Client, body: Foo, @@ -977,9 +1020,7 @@ describe("modular encode test for property type bytes", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { - prop1: uint8ArrayToString(body["prop1"], "base64url"), - }, + body: fooSerializer(body), }); } @@ -988,12 +1029,7 @@ describe("modular encode test for property type bytes", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - prop1: - typeof result.body["prop1"] === "string" - ? stringToUint8Array(result.body["prop1"], "base64url") - : result.body["prop1"], - }; + return fooDeserializer(result.body); } export async function read( @@ -1030,20 +1066,60 @@ describe("inheritance & polymorphism", () => { await assertEqualContent( modelFile?.getFullText()!, ` + /** model interface Cat */ + export interface Cat extends Pet { + kind: "cat"; + meow: number; + } + + export function catDeserializer(item: any): Cat { + return { + name: item["name"], + weight: item["weight"], + kind: item["kind"], + meow: item["meow"], + }; + } + + /** model interface Pet */ export interface Pet { name: string; weight?: number; } - - export interface Cat extends Pet { - kind: "cat"; - meow: number; + + export function petDeserializer(item: any): Pet { + return { + name: item["name"], + weight: item["weight"], + }; } + /** model interface Dog */ export interface Dog extends Pet { kind: "dog"; bark: string; - }` + } + + export function dogDeserializer(item: any): Dog { + return { + name: item["name"], + weight: item["weight"], + kind: item["kind"], + bark: item["bark"], + }; + } + + /** Alias for _ReadResponse */ + export type _ReadResponse = Cat | Dog; + + export function _readResponseSerializer(item: _ReadResponse): any { + return item; + } + + export function _readResponseDeserializer(item: any): _ReadResponse { + return item; + } + ` ); }); @@ -1068,14 +1144,32 @@ describe("inheritance & polymorphism", () => { await assertEqualContent( modelFile?.getFullText()!, ` - export interface Pet { - name: string; - weight?: number; - } - + /** model interface Cat */ export interface Cat extends Pet { kind: "cat"; meow: number; + } + + export function catDeserializer(item: any): Cat { + return { + name: item["name"], + weight: item["weight"], + kind: item["kind"], + meow: item["meow"], + }; + } + + /** model interface Pet */ + export interface Pet { + name: string; + weight?: number; + } + + export function petDeserializer(item: any): Pet { + return { + name: item["name"], + weight: item["weight"], + }; }` ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); @@ -1087,9 +1181,9 @@ describe("inheritance & polymorphism", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -1107,12 +1201,7 @@ describe("inheritance & polymorphism", () => { throw createRestError(result); } - return { - name: result.body["name"], - weight: result.body["weight"], - kind: result.body["kind"], - meow: result.body["meow"], - }; + return catDeserializer(result.body); } export async function read( @@ -1145,17 +1234,42 @@ describe("inheritance & polymorphism", () => { await assertEqualContent( modelFile?.getFullText()!, ` - export interface Animal { - name: string; + /** model interface Cat */ + export interface Cat extends Pet { + kind: "cat"; + meow: number; } + export function catDeserializer(item: any): Cat { + return { + weight: item["weight"], + name: item["name"], + kind: item["kind"], + meow: item["meow"], + }; + } + + /** model interface Pet */ export interface Pet extends Animal { weight?: number; } + + export function petDeserializer(item: any): Pet { + return { + name: item["name"], + weight: item["weight"], + }; + } + + /** model interface Animal */ + export interface Animal { + name: string; + } - export interface Cat extends Pet { - kind: "cat"; - meow: number; + export function animalDeserializer(item: any): Animal { + return { + name: item["name"], + }; } ` ); @@ -1168,9 +1282,9 @@ describe("inheritance & polymorphism", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -1188,12 +1302,7 @@ describe("inheritance & polymorphism", () => { throw createRestError(result); } - return { - weight: result.body["weight"], - name: result.body["name"], - kind: result.body["kind"], - meow: result.body["meow"], - }; + return catDeserializer(result.body); } export async function read( @@ -1207,6 +1316,7 @@ describe("inheritance & polymorphism", () => { ); }); + // TODO: Pending on https://github.com/Azure/typespec-azure/issues/1605 to be fixed it("should handle inheritance model with discriminator in operations", async () => { const tspContent = ` @discriminator("kind") @@ -1230,25 +1340,49 @@ describe("inheritance & polymorphism", () => { await assertEqualContent( modelFile?.getFullText()!, ` + /** model interface Cat */ + export interface Cat extends Pet { + kind: "cat"; + meow: number; + } + + export function catDeserializer(item: any): Cat { + return { + kind: item["kind"], + name: item["name"], + weight: item["weight"], + meow: item["meow"], + }; + } + + /** model interface Pet */ export interface Pet { - /** the discriminator possible values: cat, dog */ kind: string; name: string; weight?: number; } - - export interface Cat extends Pet { - kind: "cat"; - meow: number; - } - - export interface Dog extends Pet { - kind: "dog"; - bark: string; + + export function petDeserializer(item: any): Pet { + return { + kind: item["kind"], + name: item["name"], + weight: item["weight"], + }; } /** Alias for PetUnion */ - export type PetUnion = Cat | Dog | Pet;` + export type PetUnion = Cat | Pet; + + export function petUnionDeserializer(item: any): PetUnion { + switch (item.kind) { + case "cat": + return catDeserializer(item as Cat); + + default: + return petDeserializer(item); + } + } + ` ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -1258,10 +1392,10 @@ describe("inheritance & polymorphism", () => { ` import { TestingContext as Client } from "./index.js"; import { - StreamableMethod, - operationOptionsToRequestParameters, + StreamableMethod, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -1279,12 +1413,7 @@ describe("inheritance & polymorphism", () => { throw createRestError(result); } - return { - kind: result.body["kind"], - name: result.body["name"], - weight: result.body["weight"], - meow: result.body["meow"], - }; + return catDeserializer(result.body); } export async function read( @@ -1321,25 +1450,67 @@ describe("inheritance & polymorphism", () => { await assertEqualContent( modelFile?.getFullText()!, ` + /** model interface Pet */ export interface Pet { - /** the discriminator possible values: cat, dog */ kind: string; name: string; weight?: number; } + + export function petDeserializer(item: any): Pet { + return { + kind: item["kind"], + name: item["name"], + weight: item["weight"], + }; + } + /** Alias for PetUnion */ + export type PetUnion = Cat | Dog | Pet; + + export function petUnionDeserializer(item: any): PetUnion { + switch (item.kind) { + case "cat": + return catDeserializer(item as Cat); + + case "dog": + return dogDeserializer(item as Dog); + + default: + return petDeserializer(item); + } + } + + /** model interface Cat */ export interface Cat extends Pet { kind: "cat"; meow: number; } - + + export function catDeserializer(item: any): Cat { + return { + kind: item["kind"], + name: item["name"], + weight: item["weight"], + meow: item["meow"], + }; + } + + /** model interface Dog */ export interface Dog extends Pet { kind: "dog"; bark: string; } - - /** Alias for PetUnion */ - export type PetUnion = Cat | Dog | Pet;` + + export function dogDeserializer(item: any): Dog { + return { + kind: item["kind"], + name: item["name"], + weight: item["weight"], + bark: item["bark"], + }; + } + ` ); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -1350,9 +1521,9 @@ describe("inheritance & polymorphism", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -1370,7 +1541,7 @@ describe("inheritance & polymorphism", () => { throw createRestError(result); } - return result.body; + return petUnionDeserializer(result.body); } export async function read( @@ -1452,9 +1623,9 @@ describe("inheritance & polymorphism", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -1523,9 +1694,9 @@ describe("inheritance & polymorphism", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -1612,9 +1783,9 @@ describe("inheritance & polymorphism", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -1680,8 +1851,10 @@ describe("inheritance & polymorphism", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true + } ); assert.ok(schemaOutput); await assertEqualContent( @@ -1697,10 +1870,12 @@ describe("inheritance & polymorphism", () => { ); const paramOutput = await emitModularOperationsFromTypeSpec( tspDefinition, - false, - false, - false, - true + { + mustEmptyDiagnostic: false, + needNamespaces: false, + needAzureCore: false, + withRawContent: true, + } ); assert.ok(paramOutput); assert.strictEqual(paramOutput?.length, 1); @@ -1710,9 +1885,9 @@ describe("inheritance & polymorphism", () => { import { DemoServiceContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _getSend( @@ -1780,8 +1955,10 @@ describe("inheritance & polymorphism", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true + } ); assert.ok(schemaOutput); await assertEqualContent( @@ -1817,17 +1994,21 @@ describe("inheritance & polymorphism", () => { `; const schemaOutput = await emitModularModelsFromTypeSpec( tspDefinition, - false, - true + { + needOptions: false, + withRawContent: true + } ); assert.isUndefined(schemaOutput); const paramOutput = await emitModularOperationsFromTypeSpec( tspDefinition, - true, - false, - false, - true + { + mustEmptyDiagnostic: true, + needNamespaces: false, + needAzureCore: false, + withRawContent: true, + } ); assert.ok(paramOutput); assert.strictEqual(paramOutput?.length, 1); @@ -1838,9 +2019,9 @@ describe("inheritance & polymorphism", () => { import { DemoServiceContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _getSend( context: Client, @@ -1896,6 +2077,7 @@ describe("`is`", () => { await assertEqualContent( modelFile!.getInterface("A")?.getFullText()!, ` + /** model interface A */ export interface A { prop1: string; prop2: string; @@ -1906,12 +2088,13 @@ describe("`is`", () => { await assertEqualContent( serializer!, ` - export function aSerializer(item: A): Record { + export function aSerializer(item: A): any { return { prop1: item["prop1"], prop2: item["prop2"], }; - }` + }`, + true ); }); }); @@ -1933,28 +2116,32 @@ describe("`extends`", () => { await assertEqualContent( modelFile!.getInterface("B")?.getFullText()!, ` + /** model interface B */ export interface B { prop1: string; prop2: string; } - ` + `, + true ); const serializerB = modelFile?.getFunction("bSerializer")?.getText(); await assertEqualContent( serializerB!, ` - export function bSerializer(item: B): Record { + export function bSerializer(item: B): any { return { prop1: item["prop1"], prop2: item["prop2"], }; - }` + }`, + true ); await assertEqualContent( modelFile!.getInterface("A")?.getFullText()!, ` + /** model interface A */ export interface A extends B {}` ); @@ -1962,12 +2149,13 @@ describe("`extends`", () => { await assertEqualContent( serializerA!, ` - export function aSerializer(item: A): Record { + export function aSerializer(item: A): any { return { prop1: item["prop1"], prop2: item["prop2"], }; - }` + }`, + true ); }); }); @@ -1985,14 +2173,16 @@ describe("visibility", () => { await assertEqualContent( modelFile!.getFullText()!, ` + /** model interface A */ export interface A { readonly exactVersion?: string; } - export function aSerializer(item: A) { + export function aSerializer(item: A): any { return item as any; } - ` + `, + true ); }); @@ -2008,20 +2198,23 @@ describe("visibility", () => { await assertEqualContent( modelFile!.getInterface("A")?.getFullText()!, ` + /** model interface A */ export interface A { exactVersion?: string; - }` + }`, + true ); const serializer = modelFile?.getFunction("aSerializer")?.getText(); await assertEqualContent( serializer!, ` - export function aSerializer(item: A): Record { + export function aSerializer(item: A): any { return { exactVersion: item["exactVersion"], }; - }` + }`, + true ); }); }); @@ -2038,21 +2231,22 @@ describe("spread record", () => { } op post(@body body: Vegetables): { @body body: Vegetables }; `, - false, - false, - false, - true + { + compatibilityMode: true + } ); assert.ok(modelFile); assert.isTrue(modelFile?.getFilePath()?.endsWith("/models/models.ts")); await assertEqualContent( modelFile!.getInterface("Vegetables")?.getFullText()!, ` + /** model interface Vegetables */ export interface Vegetables extends Record{ carrots: number; beans: number; } - ` + `, + true ); const serializer = modelFile @@ -2061,13 +2255,14 @@ describe("spread record", () => { await assertEqualContent( serializer!, ` - export function vegetablesSerializer(item: Vegetables): Record { + export function vegetablesSerializer(item: Vegetables): any { return { ...item, carrots: item["carrots"], beans: item["beans"], }; - }` + }`, + true ); }); @@ -2107,38 +2302,41 @@ describe("spread record", () => { } op post(@body body: A): { @body body: A }; `, - false, - false, - false, - true + { + compatibilityMode: true + } ); assert.ok(modelFile); assert.isTrue(modelFile?.getFilePath()?.endsWith("/models/models.ts")); await assertEqualContent( modelFile!.getInterface("A")?.getFullText()!, ` + /** model interface A */ export interface A extends Base, Record { prop: number; } - ` + `, + true ); const serializerA = modelFile?.getFunction("aSerializer")?.getText(); await assertEqualContent( serializerA!, ` - export function aSerializer(item: A): Record { + export function aSerializer(item: A): any { return { ...item, foo: item["foo"], prop: item["prop"], }; - }` + }`, + true ); await assertEqualContent( modelFile!.getInterface("Base")?.getFullText()!, ` + /** model interface Base */ export interface Base { foo: number; } @@ -2149,12 +2347,13 @@ describe("spread record", () => { await assertEqualContent( serializerBase!, ` - export function baseSerializer(item: Base): Record { + export function baseSerializer(item: Base): any { return { foo: item["foo"], }; } - ` + `, + true ); }); }); diff --git a/packages/typespec-ts/test/modularUnit/operations.spec.ts b/packages/typespec-ts/test/modularUnit/operations.spec.ts index 4a028664d3..a9e8fe79d0 100644 --- a/packages/typespec-ts/test/modularUnit/operations.spec.ts +++ b/packages/typespec-ts/test/modularUnit/operations.spec.ts @@ -18,7 +18,7 @@ describe("operations", () => { operationFiles?.[0]?.getFullText()!, ` import { TestingContext as Client } from "./index.js"; - import { StreamableMethod, operationOptionsToRequestParameters, PathUncheckedResponse, createRestError } from "@azure-rest/core-client"; + import { StreamableMethod, PathUncheckedResponse, createRestError, operationOptionsToRequestParameters } from "@azure-rest/core-client"; export function _readSend(context: Client, options: ReadOptionalParams = { requestOptions: {} }): StreamableMethod { return context.path("/", ).post({...operationOptionsToRequestParameters(options)}) ; @@ -53,7 +53,7 @@ describe("operations", () => { operationFiles?.[0]?.getFullText()!, ` import { TestingContext as Client } from "./index.js"; - import { StreamableMethod, operationOptionsToRequestParameters, PathUncheckedResponse, createRestError } from "@azure-rest/core-client"; + import { StreamableMethod, PathUncheckedResponse, createRestError, operationOptionsToRequestParameters } from "@azure-rest/core-client"; export function _readSend(context: Client, options: ReadOptionalParams = { requestOptions: {} }): StreamableMethod { return context.path("/", ).get({...operationOptionsToRequestParameters(options)}) ; @@ -129,8 +129,8 @@ describe("operations", () => { operationFiles?.[0]?.getFullText()!, ` import { TestingContext as Client } from "./index.js"; - import { StreamableMethod, operationOptionsToRequestParameters, PathUncheckedResponse, createRestError } from "@azure-rest/core-client"; import { buildCsvCollection } from "../static-helpers/serialization/build-csv-collection.js"; + import { StreamableMethod, PathUncheckedResponse, createRestError, operationOptionsToRequestParameters } from "@azure-rest/core-client"; import { uint8ArrayToString } from "@azure/core-util"; export function _readSend( context: Client, @@ -142,36 +142,43 @@ describe("operations", () => { prop1: string, prop2: number, options: ReadOptionalParams = { requestOptions: {} }): StreamableMethod { - return context.path("/", ).post({...operationOptionsToRequestParameters(options), + return context.path("/").post({ + ...operationOptionsToRequestParameters(options), headers: { "required-header": requiredHeader, ...(options?.optionalHeader !== undefined ? { "optional-header": options?.optionalHeader } : {}), - ...(options?.nullableOptionalHeader !== undefined && options?.nullableOptionalHeader !== null + ...(options?.nullableOptionalHeader !== undefined && + options?.nullableOptionalHeader !== null ? { "nullable-optional-header": options?.nullableOptionalHeader } : {}), "bytes-header": uint8ArrayToString(bytesHeader, "base64"), value: uint8ArrayToString(value, "base64"), "csv-array-header": buildCsvCollection( - csvArrayHeader.map((p) => uint8ArrayToString(p, "base64url")) + csvArrayHeader.map((p: any) => { + return uint8ArrayToString(p, "base64url"); + }), ), "utc-date-header": utcDateHeader.toUTCString(), ...(options?.optionalDateHeader !== undefined ? { - "optional-date-header": - options?.optionalDateHeader?.toUTCString(), + "optional-date-header": !options?.optionalDateHeader + ? options?.optionalDateHeader + : options?.optionalDateHeader.toUTCString(), } : {}), - ...(options?.nullableDateHeader !== undefined && options?.nullableDateHeader !== null + ...(options?.nullableDateHeader !== undefined && + options?.nullableDateHeader !== null ? { - "nullable-date-header": - options?.nullableDateHeader?.toUTCString(), + "nullable-date-header": !options?.nullableDateHeader + ? options?.nullableDateHeader + : options?.nullableDateHeader.toUTCString(), } : {}), }, - body: { prop1: prop1, prop2: prop2 }, - }); + body: { prop1: prop1, prop2: prop2 }, + }); } export async function _readDeserialize(result: PathUncheckedResponse): Promise { @@ -206,7 +213,7 @@ describe("operations", () => { op read( @header nullableRequiredHeader: string | null): OkResponse; `; - await emitModularOperationsFromTypeSpec(tspContent, true); + await emitModularOperationsFromTypeSpec(tspContent, {mustEmptyDiagnostic: true}); assert.fail("Should throw diagnostic warnings"); } catch (e) { const diagnostics = e as Diagnostic[]; @@ -225,7 +232,9 @@ describe("operations", () => { `; const operationFiles = await emitModularOperationsFromTypeSpec( tspContent, - false + { + mustEmptyDiagnostic: false + } ); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -233,7 +242,7 @@ describe("operations", () => { operationFiles?.[0]?.getFullText()!, ` import { TestingContext as Client } from "./index.js"; - import { StreamableMethod, operationOptionsToRequestParameters, PathUncheckedResponse, createRestError } from "@azure-rest/core-client"; + import { StreamableMethod, PathUncheckedResponse, createRestError, operationOptionsToRequestParameters } from "@azure-rest/core-client"; export function _readSend(context: Client, nullableRequiredHeader: (string | null), options: ReadOptionalParams = { requestOptions: {} }): StreamableMethod { return context.path("/", ).get({...operationOptionsToRequestParameters(options), @@ -277,14 +286,12 @@ describe("operations", () => { operationFiles?.[0]?.getFullText()!, ` import { TestingContext as Client } from "./index.js"; - import { StreamableMethod, operationOptionsToRequestParameters, PathUncheckedResponse, createRestError } from "@azure-rest/core-client"; + import { StreamableMethod, PathUncheckedResponse, createRestError, operationOptionsToRequestParameters } from "@azure-rest/core-client"; export function _readSend(context: Client, bars?: Bar[], options: ReadOptionalParams = { requestOptions: {} }): StreamableMethod { return context.path("/").post({ ...operationOptionsToRequestParameters(options), - body: (bars ?? []).map((p) => { - return { prop1: p["prop1"], prop2: p["prop2"],}; - }), + body: !bars ? bars : barArraySerializer(bars), }); } @@ -300,7 +307,8 @@ describe("operations", () => { export async function read(context: Client, bars?: Bar[], options: ReadOptionalParams = { requestOptions: {} }): Promise { const result = await _readSend(context, bars, options); return _readDeserialize(result); - }` + }`, + true ); }); it.skip("should handle `undefined` for named model array as request body", async () => { @@ -469,9 +477,9 @@ describe("operations", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -483,21 +491,7 @@ describe("operations", () => { .path("/") .post({ ...operationOptionsToRequestParameters(options), - body: { - optionalBars: - body["optionalBars"] === undefined - ? body["optionalBars"] - : body["optionalBars"].map(barSerializer), - requiredBars: body["requiredBars"].map(barSerializer), - nullableBars: - body["nullableBars"] === undefined || body["nullableBars"] === null - ? body["nullableBars"] - : body["nullableBars"].map(barSerializer), - nullableRequiredBars: - body["nullableRequiredBars"] === null - ? body["nullableRequiredBars"] - : body["nullableRequiredBars"].map(barSerializer), - }, + body: fooSerializer(body), }); } @@ -546,9 +540,9 @@ describe("operations", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, - createRestError + createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -565,30 +559,7 @@ describe("operations", () => { if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return { - optionalBars: - result.body["optionalBars"] === undefined - ? result.body["optionalBars"] - : result.body["optionalBars"].map((p: any) => { - return { prop1: p["prop1"], prop2: p["prop2"] }; - }), - requiredBars: result.body["requiredBars"].map((p: any) => { - return { prop1: p["prop1"], prop2: p["prop2"] }; - }), - nullableBars: - result.body["nullableBars"] === undefined || - result.body["nullableBars"] === null - ? result.body["nullableBars"] - : result.body["nullableBars"].map((p: any) => { - return { prop1: p["prop1"], prop2: p["prop2"] }; - }), - nullableRequiredBars: - result.body["nullableRequiredBars"] === null - ? result.body["nullableRequiredBars"] - : result.body["nullableRequiredBars"].map((p: any) => { - return { prop1: p["prop1"], prop2: p["prop2"] }; - }), - }; + return fooDeserializer(result.body); } export async function read( @@ -622,9 +593,9 @@ describe("operations", () => { `; const operationFiles = await emitModularOperationsFromTypeSpec( tspContent, - true, - true, - true + { + needAzureCore: true + } ); assert.ok(operationFiles); @@ -634,11 +605,12 @@ describe("operations", () => { operationFiles?.[0]?.getFullText()!, ` import { TestingContext as Client } from "./index.js"; - import { StreamableMethod, operationOptionsToRequestParameters, PathUncheckedResponse, createRestError } from "@azure-rest/core-client"; - import { + import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../static-helpers/pagingHelpers.js"; + import { StreamableMethod, PathUncheckedResponse, createRestError, operationOptionsToRequestParameters } from "@azure-rest/core-client"; + export function _testSend(context: Client, options: TestOptionalParams = { requestOptions: {} }): StreamableMethod { return context.path("/", ).post({...operationOptionsToRequestParameters(options), }) ; @@ -649,9 +621,7 @@ describe("operations", () => { if(!expectedStatuses.includes(result.status)){ throw createRestError(result); } - return { - "lists": result.body["lists"] - } + return _barDeserializer(result.body); } export function test(context: Client, options: TestOptionalParams = { requestOptions: {} }): PagedAsyncIterableIterator { @@ -684,7 +654,9 @@ describe("operations", () => { `; try { - await emitModularOperationsFromTypeSpec(tspContent, true, true, true); + await emitModularOperationsFromTypeSpec(tspContent, { + needAzureCore: true + }); assert.fail("Should throw diagnostic warnings"); } catch (e) { const diagnostics = e as Diagnostic[]; @@ -697,9 +669,10 @@ describe("operations", () => { } const operationFiles = await emitModularOperationsFromTypeSpec( tspContent, - false, - true, - true + { + mustEmptyDiagnostic: false, + needAzureCore: true + } ); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -707,7 +680,7 @@ describe("operations", () => { operationFiles?.[0]?.getFullText()!, ` import { TestingContext as Client } from "./index.js"; - import { StreamableMethod, operationOptionsToRequestParameters, PathUncheckedResponse, createRestError } from "@azure-rest/core-client"; + import { StreamableMethod, PathUncheckedResponse, createRestError, operationOptionsToRequestParameters } from "@azure-rest/core-client"; export function _testSend(context: Client, options: TestOptionalParams = { requestOptions: {} }): StreamableMethod { return context.path("/", ).post({...operationOptionsToRequestParameters(options), }) ; @@ -718,9 +691,7 @@ describe("operations", () => { if(!expectedStatuses.includes(result.status)){ throw createRestError(result); } - return { - "lists": result.body["lists"] - } + return barDeserializer(result.body); } export async function test(context: Client, options: TestOptionalParams = { requestOptions: {} }): Promise { @@ -757,9 +728,9 @@ describe("operations", () => { const operationFiles = await emitModularOperationsFromTypeSpec( tspContent, - true, - true, - true + { + needAzureCore: true + } ); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -767,11 +738,12 @@ describe("operations", () => { operationFiles?.[0]?.getFullText()!, ` import { TestingContext as Client } from "./index.js"; - import { StreamableMethod, operationOptionsToRequestParameters, PathUncheckedResponse, createRestError } from "@azure-rest/core-client"; - import { + import { PagedAsyncIterableIterator, buildPagedAsyncIterator, } from "../static-helpers/pagingHelpers.js"; + import { StreamableMethod, PathUncheckedResponse, createRestError, operationOptionsToRequestParameters } from "@azure-rest/core-client"; + export function _testSend(context: Client, options: TestOptionalParams = { requestOptions: {} }): StreamableMethod { return context.path("/", ).post({...operationOptionsToRequestParameters(options), }) ; @@ -782,11 +754,7 @@ describe("operations", () => { if(!expectedStatuses.includes(result.status)){ throw createRestError(result); } - return { - "lists": result.body["lists"], - nextLink: result.body["nextLink"], - message: result.body["message"] - } + return _childDeserializer(result.body); } export function test(context: Client, options: TestOptionalParams = { requestOptions: {} }): PagedAsyncIterableIterator { diff --git a/packages/typespec-ts/test/modularUnit/scenarios.spec.ts b/packages/typespec-ts/test/modularUnit/scenarios.spec.ts index 50b3fcb1d7..94307209b1 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios.spec.ts +++ b/packages/typespec-ts/test/modularUnit/scenarios.spec.ts @@ -29,14 +29,16 @@ type EmitterFunction = ( */ const OUTPUT_CODE_BLOCK_TYPES: Record = { // Snapshot of a particular interface named {name} in the models file - "(ts|typescript) models interface {name}": async (tsp, { name }) => { - const result = await emitModularModelsFromTypeSpec(tsp); + "(ts|typescript) models interface {name}": async (tsp, { name }, namedUnknownArgs) => { + const configs = namedUnknownArgs ? (namedUnknownArgs["configs"] as Record): {}; + const result = await emitModularModelsFromTypeSpec(tsp, configs); return result!.getInterfaceOrThrow(name ?? "No name specified!").getText(); }, // Snapshot of a particular function named {name} in the models file - "(ts|typescript) models function {name}": async (tsp, { name }) => { - const result = await emitModularModelsFromTypeSpec(tsp); + "(ts|typescript) models function {name}": async (tsp, { name }, namedUnknownArgs) => { + const configs = namedUnknownArgs ? (namedUnknownArgs["configs"] as Record): {}; + const result = await emitModularModelsFromTypeSpec(tsp, configs); if (result === undefined) { return "// (file was not generated)"; @@ -46,8 +48,9 @@ const OUTPUT_CODE_BLOCK_TYPES: Record = { }, // Snapshot of the entire models file - "(ts|typescript) models": async (tsp) => { - const result = await emitModularModelsFromTypeSpec(tsp); + "(ts|typescript) models": async (tsp, {}, namedUnknownArgs) => { + const configs = namedUnknownArgs ? (namedUnknownArgs["configs"] as Record): {}; + const result = await emitModularModelsFromTypeSpec(tsp, configs); if (result === undefined) { return "// (file was not generated)"; @@ -61,7 +64,9 @@ const OUTPUT_CODE_BLOCK_TYPES: Record = { tsp, { name } ) => { - const result = await emitModularModelsFromTypeSpec(tsp, true); + const result = await emitModularModelsFromTypeSpec(tsp, { + needOptions: true + }); if (result === undefined) { return "// (file was not generated)"; @@ -72,7 +77,9 @@ const OUTPUT_CODE_BLOCK_TYPES: Record = { // Snapshot of the entire models file "(ts|typescript) models:withOptions": async (tsp) => { - const result = await emitModularModelsFromTypeSpec(tsp, true); + const result = await emitModularModelsFromTypeSpec(tsp, { + needOptions: true + }); if (result === undefined) { return "// (file was not generated)"; diff --git a/packages/typespec-ts/test/modularUnit/scenarios/example/example.md b/packages/typespec-ts/test/modularUnit/scenarios/example/example.md index 0bf9216431..06bfa93f4d 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/example/example.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/example/example.md @@ -38,9 +38,16 @@ These are the models that are generated. The language tag `ts models` is used to the test host that the content of the code block represents the entire generated `models.ts` file. ```ts models +/** model interface Example */ export interface Example { id: string; } + +export function exampleDeserializer(item: any): Example { + return { + id: item["id"], + }; +} ``` You can also extract a specific model interface using `ts models interface `: @@ -74,9 +81,9 @@ You can extract the entire operations file using `ts operations`: import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -97,9 +104,7 @@ export async function _readDeserialize( throw createRestError(result); } - return { - id: result.body["id"], - }; + return exampleDeserializer(result.body); } export async function read( diff --git a/packages/typespec-ts/test/modularUnit/scenarios/models/deserialization/additionalProperties.md b/packages/typespec-ts/test/modularUnit/scenarios/models/deserialization/additionalProperties.md new file mode 100644 index 0000000000..4f5886064b --- /dev/null +++ b/packages/typespec-ts/test/modularUnit/scenarios/models/deserialization/additionalProperties.md @@ -0,0 +1,43 @@ +# Should generate deserializer for additional properties + +## TypeSpec + +This is tsp definition. + +```tsp +model SimpleModel { + ...Record; + propA: string; + propB: string; +} + +@route("/serialize") +interface D { + op bar(): { @body body: SimpleModel }; +} +``` + +This is the tsp configuration. +```yaml +compatibilityMode: true +``` + +## Provide generated models and its serializer + +Generated Models. + +```ts models +/** model interface SimpleModel */ +export interface SimpleModel extends Record { + propA: string; + propB: string; +} + +export function simpleModelDeserializer(item: any): SimpleModel { + return { + ...item, + propA: item["propA"], + propB: item["propB"], + }; +} +``` \ No newline at end of file diff --git a/packages/typespec-ts/test/modularUnit/scenarios/models/deserialization/anonymousModel.md b/packages/typespec-ts/test/modularUnit/scenarios/models/deserialization/anonymousModel.md new file mode 100644 index 0000000000..c8d626767c --- /dev/null +++ b/packages/typespec-ts/test/modularUnit/scenarios/models/deserialization/anonymousModel.md @@ -0,0 +1,77 @@ +# Should generate deserializer for anonymous models +Will prompt all operations into top-level. + +## TypeSpec + +This is tsp definition. + +```tsp +model SimpleModel { + prop: { + propA: string; + propB: { + propAA: string; + propBB: boolean + } + } +} + +@route("/serialize") +interface D { + op bar(): { @body body: SimpleModel }; +} +``` + +## Provide generated models and its serializer + +Generated Models. + +```ts models +/** model interface SimpleModel */ +export interface SimpleModel { + prop: { + propA: string; + propB: { + propAA: string; + propBB: boolean; + }; + }; +} + +export function simpleModelDeserializer(item: any): SimpleModel { + return { + prop: _simpleModelPropDeserializer(item["prop"]), + }; +} + +/** model interface _SimpleModelProp */ +export interface _SimpleModelProp { + propA: string; + propB: { + propAA: string; + propBB: boolean; + }; +} + +export function _simpleModelPropDeserializer(item: any): _SimpleModelProp { + return { + propA: item["propA"], + propB: _simpleModelPropPropBDeserializer(item["propB"]), + }; +} + +/** model interface _SimpleModelPropPropB */ +export interface _SimpleModelPropPropB { + propAA: string; + propBB: boolean; +} + +export function _simpleModelPropPropBDeserializer( + item: any, +): _SimpleModelPropPropB { + return { + propAA: item["propAA"], + propBB: item["propBB"], + }; +} +``` \ No newline at end of file diff --git a/packages/typespec-ts/test/modularUnit/scenarios/models/deserialization/propertyType.md b/packages/typespec-ts/test/modularUnit/scenarios/models/deserialization/propertyType.md new file mode 100644 index 0000000000..e6981f68ab --- /dev/null +++ b/packages/typespec-ts/test/modularUnit/scenarios/models/deserialization/propertyType.md @@ -0,0 +1,584 @@ +# Should generate deserializer for property types +Will prompt all operations into top-level. + +## TypeSpec + +This is tsp definition. + +```tsp +model SimpleModel { + propString: string; + propboolean: boolean; + propNumber: int32; + propStringOptional?: string; + propSimpleUnion: string | boolean | int32; + propSimpleUnionOptional?: string | boolean | int32; + propStringLiteral: "A"; + propBooleanLiteral: false; + propNumberLiteral: 1; + propStringLiteralOptional?: "A"; + propStringUnion: "A" | "B"; + propStringUnionOptioanl: "A" | "B"; + propStringUnionNullable: "A" | "B" | null; + propStringUnionAsExtensible: "A" | "B" | string; + propStringUnionAsExtensibleOptional?: "A" | "B" | string; + propStringUnionAsExtensibleNullable: "A" | "B" | string | null; + propStringUnionAsExtensibleOptionalAndNullable?: "A" | "B" | string | null; + propMixedTypeLiteral: "A" | false | 1; + propStringArray: string[]; + propBooleanArray: boolean[]; + propNumberArray: int32[]; + propSimpleUnionArray: (string | boolean | int32)[]; + propStringArrayOptional?: string[]; + propSimpleUnionArrayOptional?: (string | boolean | int32)[]; + propRecordOfString: Record; + propRecordOfBoolean: Record; + propRecordOfNumber: Record; + propRecordOfSimpleUnion: Record; + propRecordOfStringOptional?: Record; + propRecordOfStringArray: Record; + propArrayOfRecordOfString: Record[]; + propArrayOfRecordOfStringOptional?: Record[]; + propRecordOfUnionArray: Record<(string | boolean | int32)[]>; + propRecordOfUnionArrayOptional?: Record<(string | boolean | int32)[]>; + propArrayOfRecordOfUnion: Record[]; + propArrayOfRecordOfUnionOptional?: Record[]; + @encodedName("application/json", "prop_encoded") + propEncoded: string; +} + +@route("/serialize") +interface D { + op bar(): { @body body: SimpleModel }; +} +``` + +This is the tspconfig.yaml. + +```yaml +experimentalExtensibleEnums: true +``` + +## Provide generated models and its serializer + +Generated Models. + +```ts models +/** model interface SimpleModel */ +export interface SimpleModel { + propString: string; + propboolean: boolean; + propNumber: number; + propStringOptional?: string; + propSimpleUnion: string | boolean | number; + propSimpleUnionOptional?: string | boolean | number; + propStringLiteral: "A"; + propBooleanLiteral: false; + propNumberLiteral: 1; + propStringLiteralOptional?: "A"; + propStringUnion: "A" | "B"; + propStringUnionOptioanl: "A" | "B"; + propStringUnionNullable: ("A" | "B") | null; + propStringUnionAsExtensible: string; + propStringUnionAsExtensibleOptional?: string; + propStringUnionAsExtensibleNullable: string | null; + propStringUnionAsExtensibleOptionalAndNullable?: string | null; + propMixedTypeLiteral: "A" | false | 1; + propStringArray: string[]; + propBooleanArray: boolean[]; + propNumberArray: number[]; + propSimpleUnionArray: (string | boolean | number)[]; + propStringArrayOptional?: string[]; + propSimpleUnionArrayOptional?: (string | boolean | number)[]; + propRecordOfString: Record; + propRecordOfBoolean: Record; + propRecordOfNumber: Record; + propRecordOfSimpleUnion: Record; + propRecordOfStringOptional?: Record; + propRecordOfStringArray: Record; + propArrayOfRecordOfString: Record[]; + propArrayOfRecordOfStringOptional?: Record[]; + propRecordOfUnionArray: Record; + propRecordOfUnionArrayOptional?: Record< + string, + (string | boolean | number)[] + >; + propArrayOfRecordOfUnion: Record[]; + propArrayOfRecordOfUnionOptional?: Record< + string, + string | boolean | number + >[]; + propEncoded: string; +} + +export function simpleModelDeserializer(item: any): SimpleModel { + return { + propString: item["propString"], + propboolean: item["propboolean"], + propNumber: item["propNumber"], + propStringOptional: item["propStringOptional"], + propSimpleUnion: _simpleModelPropSimpleUnionDeserializer( + item["propSimpleUnion"], + ), + propSimpleUnionOptional: !item["propSimpleUnionOptional"] + ? item["propSimpleUnionOptional"] + : _simpleModelPropSimpleUnionOptionalDeserializer( + item["propSimpleUnionOptional"], + ), + propStringLiteral: item["propStringLiteral"], + propBooleanLiteral: item["propBooleanLiteral"], + propNumberLiteral: item["propNumberLiteral"], + propStringLiteralOptional: item["propStringLiteralOptional"], + propStringUnion: item["propStringUnion"], + propStringUnionOptioanl: item["propStringUnionOptioanl"], + propStringUnionNullable: item["propStringUnionNullable"], + propStringUnionAsExtensible: item["propStringUnionAsExtensible"], + propStringUnionAsExtensibleOptional: + item["propStringUnionAsExtensibleOptional"], + propStringUnionAsExtensibleNullable: + item["propStringUnionAsExtensibleNullable"], + propStringUnionAsExtensibleOptionalAndNullable: + item["propStringUnionAsExtensibleOptionalAndNullable"], + propMixedTypeLiteral: _simpleModelPropMixedTypeLiteralDeserializer( + item["propMixedTypeLiteral"], + ), + propStringArray: item["propStringArray"].map((p: any) => { + return p; + }), + propBooleanArray: item["propBooleanArray"].map((p: any) => { + return p; + }), + propNumberArray: item["propNumberArray"].map((p: any) => { + return p; + }), + propSimpleUnionArray: simpleModelPropSimpleUnionArrayArrayDeserializer( + item["propSimpleUnionArray"], + ), + propStringArrayOptional: !item["propStringArrayOptional"] + ? item["propStringArrayOptional"] + : item["propStringArrayOptional"].map((p: any) => { + return p; + }), + propSimpleUnionArrayOptional: !item["propSimpleUnionArrayOptional"] + ? item["propSimpleUnionArrayOptional"] + : simpleModelPropSimpleUnionArrayOptionalArrayDeserializer( + item["propSimpleUnionArrayOptional"], + ), + propRecordOfString: item["propRecordOfString"], + propRecordOfBoolean: item["propRecordOfBoolean"], + propRecordOfNumber: item["propRecordOfNumber"], + propRecordOfSimpleUnion: + simpleModelPropRecordOfSimpleUnionRecordDeserializer( + item["propRecordOfSimpleUnion"], + ), + propRecordOfStringOptional: item["propRecordOfStringOptional"], + propRecordOfStringArray: item["propRecordOfStringArray"], + propArrayOfRecordOfString: item["propArrayOfRecordOfString"].map( + (p: any) => { + return p; + }, + ), + propArrayOfRecordOfStringOptional: !item[ + "propArrayOfRecordOfStringOptional" + ] + ? item["propArrayOfRecordOfStringOptional"] + : item["propArrayOfRecordOfStringOptional"].map((p: any) => { + return p; + }), + propRecordOfUnionArray: + simpleModelPropRecordOfUnionArrayArrayRecordDeserializer( + item["propRecordOfUnionArray"], + ), + propRecordOfUnionArrayOptional: !item["propRecordOfUnionArrayOptional"] + ? item["propRecordOfUnionArrayOptional"] + : simpleModelPropRecordOfUnionArrayOptionalArrayRecordDeserializer( + item["propRecordOfUnionArrayOptional"], + ), + propArrayOfRecordOfUnion: + simpleModelPropArrayOfRecordOfUnionRecordArrayDeserializer( + item["propArrayOfRecordOfUnion"], + ), + propArrayOfRecordOfUnionOptional: !item["propArrayOfRecordOfUnionOptional"] + ? item["propArrayOfRecordOfUnionOptional"] + : simpleModelPropArrayOfRecordOfUnionOptionalRecordArrayDeserializer( + item["propArrayOfRecordOfUnionOptional"], + ), + propEncoded: item["prop_encoded"], + }; +} + +/** Alias for _SimpleModelPropSimpleUnion */ +export type _SimpleModelPropSimpleUnion = string | boolean | number; + +export function _simpleModelPropSimpleUnionSerializer( + item: _SimpleModelPropSimpleUnion, +): any { + return item; +} + +export function _simpleModelPropSimpleUnionDeserializer( + item: any, +): _SimpleModelPropSimpleUnion { + return item; +} + +/** Alias for _SimpleModelPropSimpleUnionOptional */ +export type _SimpleModelPropSimpleUnionOptional = string | boolean | number; + +export function _simpleModelPropSimpleUnionOptionalSerializer( + item: _SimpleModelPropSimpleUnionOptional, +): any { + return item; +} + +export function _simpleModelPropSimpleUnionOptionalDeserializer( + item: any, +): _SimpleModelPropSimpleUnionOptional { + return item; +} + +/** Alias for _SimpleModelPropMixedTypeLiteral */ +export type _SimpleModelPropMixedTypeLiteral = "A" | false | 1; + +export function _simpleModelPropMixedTypeLiteralSerializer( + item: _SimpleModelPropMixedTypeLiteral, +): any { + return item; +} + +export function _simpleModelPropMixedTypeLiteralDeserializer( + item: any, +): _SimpleModelPropMixedTypeLiteral { + return item; +} + +/** Alias for _SimpleModelPropSimpleUnionArray */ +export type _SimpleModelPropSimpleUnionArray = string | boolean | number; + +export function _simpleModelPropSimpleUnionArraySerializer( + item: _SimpleModelPropSimpleUnionArray, +): any { + return item; +} + +export function _simpleModelPropSimpleUnionArrayDeserializer( + item: any, +): _SimpleModelPropSimpleUnionArray { + return item; +} + +export function simpleModelPropSimpleUnionArrayArraySerializer( + result: Array<_SimpleModelPropSimpleUnionArray>, +): any[] { + return result.map((item) => { + return _simpleModelPropSimpleUnionArraySerializer(item); + }); +} + +export function simpleModelPropSimpleUnionArrayArrayDeserializer( + result: Array<_SimpleModelPropSimpleUnionArray>, +): any[] { + return result.map((item) => { + return _simpleModelPropSimpleUnionArrayDeserializer(item); + }); +} + +/** Alias for _SimpleModelPropSimpleUnionArrayOptional */ +export type _SimpleModelPropSimpleUnionArrayOptional = + | string + | boolean + | number; + +export function _simpleModelPropSimpleUnionArrayOptionalSerializer( + item: _SimpleModelPropSimpleUnionArrayOptional, +): any { + return item; +} + +export function _simpleModelPropSimpleUnionArrayOptionalDeserializer( + item: any, +): _SimpleModelPropSimpleUnionArrayOptional { + return item; +} + +export function simpleModelPropSimpleUnionArrayOptionalArraySerializer( + result: Array<_SimpleModelPropSimpleUnionArrayOptional>, +): any[] { + return result.map((item) => { + return _simpleModelPropSimpleUnionArrayOptionalSerializer(item); + }); +} + +export function simpleModelPropSimpleUnionArrayOptionalArrayDeserializer( + result: Array<_SimpleModelPropSimpleUnionArrayOptional>, +): any[] { + return result.map((item) => { + return _simpleModelPropSimpleUnionArrayOptionalDeserializer(item); + }); +} + +/** Alias for _SimpleModelPropRecordOfSimpleUnion */ +export type _SimpleModelPropRecordOfSimpleUnion = string | boolean | number; + +export function _simpleModelPropRecordOfSimpleUnionSerializer( + item: _SimpleModelPropRecordOfSimpleUnion, +): any { + return item; +} + +export function _simpleModelPropRecordOfSimpleUnionDeserializer( + item: any, +): _SimpleModelPropRecordOfSimpleUnion { + return item; +} + +export function simpleModelPropRecordOfSimpleUnionRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropRecordOfSimpleUnionSerializer(item[key]); + }); + return result; +} + +export function simpleModelPropRecordOfSimpleUnionRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropRecordOfSimpleUnionDeserializer(item[key]); + }); + return result; +} + +/** Alias for _SimpleModelPropRecordOfUnionArray */ +export type _SimpleModelPropRecordOfUnionArray = string | boolean | number; + +export function _simpleModelPropRecordOfUnionArraySerializer( + item: _SimpleModelPropRecordOfUnionArray, +): any { + return item; +} + +export function _simpleModelPropRecordOfUnionArrayDeserializer( + item: any, +): _SimpleModelPropRecordOfUnionArray { + return item; +} + +export function simpleModelPropRecordOfUnionArrayArraySerializer( + result: Array<_SimpleModelPropRecordOfUnionArray>, +): any[] { + return result.map((item) => { + return _simpleModelPropRecordOfUnionArraySerializer(item); + }); +} + +export function simpleModelPropRecordOfUnionArrayArrayDeserializer( + result: Array<_SimpleModelPropRecordOfUnionArray>, +): any[] { + return result.map((item) => { + return _simpleModelPropRecordOfUnionArrayDeserializer(item); + }); +} + +export function simpleModelPropRecordOfUnionArrayArrayRecordSerializer( + item: Record>, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : simpleModelPropRecordOfUnionArrayArraySerializer(item[key]); + }); + return result; +} + +export function simpleModelPropRecordOfUnionArrayArrayRecordDeserializer( + item: Record, +): Record> { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : simpleModelPropRecordOfUnionArrayArrayDeserializer(item[key]); + }); + return result; +} + +/** Alias for _SimpleModelPropRecordOfUnionArrayOptional */ +export type _SimpleModelPropRecordOfUnionArrayOptional = + | string + | boolean + | number; + +export function _simpleModelPropRecordOfUnionArrayOptionalSerializer( + item: _SimpleModelPropRecordOfUnionArrayOptional, +): any { + return item; +} + +export function _simpleModelPropRecordOfUnionArrayOptionalDeserializer( + item: any, +): _SimpleModelPropRecordOfUnionArrayOptional { + return item; +} + +export function simpleModelPropRecordOfUnionArrayOptionalArraySerializer( + result: Array<_SimpleModelPropRecordOfUnionArrayOptional>, +): any[] { + return result.map((item) => { + return _simpleModelPropRecordOfUnionArrayOptionalSerializer(item); + }); +} + +export function simpleModelPropRecordOfUnionArrayOptionalArrayDeserializer( + result: Array<_SimpleModelPropRecordOfUnionArrayOptional>, +): any[] { + return result.map((item) => { + return _simpleModelPropRecordOfUnionArrayOptionalDeserializer(item); + }); +} + +export function simpleModelPropRecordOfUnionArrayOptionalArrayRecordSerializer( + item: Record>, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : simpleModelPropRecordOfUnionArrayOptionalArraySerializer(item[key]); + }); + return result; +} + +export function simpleModelPropRecordOfUnionArrayOptionalArrayRecordDeserializer( + item: Record, +): Record> { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : simpleModelPropRecordOfUnionArrayOptionalArrayDeserializer(item[key]); + }); + return result; +} + +/** Alias for _SimpleModelPropArrayOfRecordOfUnion */ +export type _SimpleModelPropArrayOfRecordOfUnion = string | boolean | number; + +export function _simpleModelPropArrayOfRecordOfUnionSerializer( + item: _SimpleModelPropArrayOfRecordOfUnion, +): any { + return item; +} + +export function _simpleModelPropArrayOfRecordOfUnionDeserializer( + item: any, +): _SimpleModelPropArrayOfRecordOfUnion { + return item; +} + +export function simpleModelPropArrayOfRecordOfUnionRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropArrayOfRecordOfUnionSerializer(item[key]); + }); + return result; +} + +export function simpleModelPropArrayOfRecordOfUnionRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropArrayOfRecordOfUnionDeserializer(item[key]); + }); + return result; +} + +export function simpleModelPropArrayOfRecordOfUnionRecordArraySerializer( + result: Array>, +): any[] { + return result.map((item) => { + return simpleModelPropArrayOfRecordOfUnionRecordSerializer(item); + }); +} + +export function simpleModelPropArrayOfRecordOfUnionRecordArrayDeserializer( + result: Array>, +): any[] { + return result.map((item) => { + return simpleModelPropArrayOfRecordOfUnionRecordDeserializer(item); + }); +} + +/** Alias for _SimpleModelPropArrayOfRecordOfUnionOptional */ +export type _SimpleModelPropArrayOfRecordOfUnionOptional = + | string + | boolean + | number; + +export function _simpleModelPropArrayOfRecordOfUnionOptionalSerializer( + item: _SimpleModelPropArrayOfRecordOfUnionOptional, +): any { + return item; +} + +export function _simpleModelPropArrayOfRecordOfUnionOptionalDeserializer( + item: any, +): _SimpleModelPropArrayOfRecordOfUnionOptional { + return item; +} + +export function simpleModelPropArrayOfRecordOfUnionOptionalRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropArrayOfRecordOfUnionOptionalSerializer(item[key]); + }); + return result; +} + +export function simpleModelPropArrayOfRecordOfUnionOptionalRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropArrayOfRecordOfUnionOptionalDeserializer(item[key]); + }); + return result; +} + +export function simpleModelPropArrayOfRecordOfUnionOptionalRecordArraySerializer( + result: Array>, +): any[] { + return result.map((item) => { + return simpleModelPropArrayOfRecordOfUnionOptionalRecordSerializer(item); + }); +} + +export function simpleModelPropArrayOfRecordOfUnionOptionalRecordArrayDeserializer( + result: Array>, +): any[] { + return result.map((item) => { + return simpleModelPropArrayOfRecordOfUnionOptionalRecordDeserializer(item); + }); +} +``` \ No newline at end of file diff --git a/packages/typespec-ts/test/modularUnit/scenarios/models/models.md b/packages/typespec-ts/test/modularUnit/scenarios/models/models.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/additionalProperties.md b/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/additionalProperties.md new file mode 100644 index 0000000000..f8646dec90 --- /dev/null +++ b/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/additionalProperties.md @@ -0,0 +1,39 @@ +# Should generate serializer for additional properties + +## TypeSpec + +This is tsp definition. + +```tsp +model SimpleModel { + ...Record; + propA: string; + propB: string; +} + +@route("/serialize") +interface D { + op bar(@body body: SimpleModel): void; +} +``` + +This is the tsp configuration. +```yaml +compatibilityMode: true +``` + +## Provide generated models and its serializer + +Generated Models. + +```ts models +/** model interface SimpleModel */ +export interface SimpleModel extends Record { + propA: string; + propB: string; +} + +export function simpleModelSerializer(item: SimpleModel): any { + return { ...item, propA: item["propA"], propB: item["propB"] }; +} +``` \ No newline at end of file diff --git a/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/anonymousModel.md b/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/anonymousModel.md new file mode 100644 index 0000000000..566eca4b33 --- /dev/null +++ b/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/anonymousModel.md @@ -0,0 +1,72 @@ +# Should generate serializer for anonymous models +Will prompt all operations into top-level. + +## TypeSpec + +This is tsp definition. + +```tsp +model SimpleModel { + prop: { + propA: string; + propB: { + propAA: string; + propBB: boolean + } + } +} + +@route("/serialize") +interface D { + op bar(@body body: SimpleModel): void; +} +``` + +## Provide generated models and its serializer + +Generated Models. + +```ts models +/** model interface SimpleModel */ +export interface SimpleModel { + prop: { + propA: string; + propB: { + propAA: string; + propBB: boolean; + }; + }; +} + +export function simpleModelSerializer(item: SimpleModel): any { + return { prop: _simpleModelPropSerializer(item["prop"]) }; +} + +/** model interface _SimpleModelProp */ +export interface _SimpleModelProp { + propA: string; + propB: { + propAA: string; + propBB: boolean; + }; +} + +export function _simpleModelPropSerializer(item: _SimpleModelProp): any { + return { + propA: item["propA"], + propB: _simpleModelPropPropBSerializer(item["propB"]), + }; +} + +/** model interface _SimpleModelPropPropB */ +export interface _SimpleModelPropPropB { + propAA: string; + propBB: boolean; +} + +export function _simpleModelPropPropBSerializer( + item: _SimpleModelPropPropB, +): any { + return { propAA: item["propAA"], propBB: item["propBB"] }; +} +``` \ No newline at end of file diff --git a/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/propertyType.md b/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/propertyType.md new file mode 100644 index 0000000000..2eeb4c6e58 --- /dev/null +++ b/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/propertyType.md @@ -0,0 +1,577 @@ +# Should generate serializer for property types +Will prompt all operations into top-level. + +## TypeSpec + +This is tsp definition. + +```tsp +model SimpleModel { + propString: string; + propboolean: boolean; + propNumber: int32; + propStringOptional?: string; + propSimpleUnion: string | boolean | int32; + propSimpleUnionOptional?: string | boolean | int32; + propStringLiteral: "A"; + propBooleanLiteral: false; + propNumberLiteral: 1; + propStringLiteralOptional?: "A"; + propStringUnion: "A" | "B"; + propStringUnionOptioanl: "A" | "B"; + propStringUnionNullable: "A" | "B" | null; + propStringUnionAsExtensible: "A" | "B" | string; + propStringUnionAsExtensibleOptional?: "A" | "B" | string; + propStringUnionAsExtensibleNullable: "A" | "B" | string | null; + propStringUnionAsExtensibleOptionalAndNullable?: "A" | "B" | string | null; + propMixedTypeLiteral: "A" | false | 1; + propStringArray: string[]; + propBooleanArray: boolean[]; + propNumberArray: int32[]; + propSimpleUnionArray: (string | boolean | int32)[]; + propStringArrayOptional?: string[]; + propSimpleUnionArrayOptional?: (string | boolean | int32)[]; + propRecordOfString: Record; + propRecordOfBoolean: Record; + propRecordOfNumber: Record; + propRecordOfSimpleUnion: Record; + propRecordOfStringOptional?: Record; + propRecordOfStringArray: Record; + propArrayOfRecordOfString: Record[]; + propArrayOfRecordOfStringOptional?: Record[]; + propRecordOfUnionArray: Record<(string | boolean | int32)[]>; + propRecordOfUnionArrayOptional?: Record<(string | boolean | int32)[]>; + propArrayOfRecordOfUnion: Record[]; + propArrayOfRecordOfUnionOptional?: Record[]; + @encodedName("application/json", "prop_encoded") + propEncoded: string; +} + +@route("/serialize") +interface D { + op bar(@body body: SimpleModel): void; +} +``` + +## Provide generated models and its serializer + +Generated Models. + +```ts models +/** model interface SimpleModel */ +export interface SimpleModel { + propString: string; + propboolean: boolean; + propNumber: number; + propStringOptional?: string; + propSimpleUnion: string | boolean | number; + propSimpleUnionOptional?: string | boolean | number; + propStringLiteral: "A"; + propBooleanLiteral: false; + propNumberLiteral: 1; + propStringLiteralOptional?: "A"; + propStringUnion: "A" | "B"; + propStringUnionOptioanl: "A" | "B"; + propStringUnionNullable: ("A" | "B") | null; + propStringUnionAsExtensible: "A" | "B"; + propStringUnionAsExtensibleOptional?: "A" | "B"; + propStringUnionAsExtensibleNullable: ("A" | "B") | null; + propStringUnionAsExtensibleOptionalAndNullable?: ("A" | "B") | null; + propMixedTypeLiteral: "A" | false | 1; + propStringArray: string[]; + propBooleanArray: boolean[]; + propNumberArray: number[]; + propSimpleUnionArray: (string | boolean | number)[]; + propStringArrayOptional?: string[]; + propSimpleUnionArrayOptional?: (string | boolean | number)[]; + propRecordOfString: Record; + propRecordOfBoolean: Record; + propRecordOfNumber: Record; + propRecordOfSimpleUnion: Record; + propRecordOfStringOptional?: Record; + propRecordOfStringArray: Record; + propArrayOfRecordOfString: Record[]; + propArrayOfRecordOfStringOptional?: Record[]; + propRecordOfUnionArray: Record; + propRecordOfUnionArrayOptional?: Record< + string, + (string | boolean | number)[] + >; + propArrayOfRecordOfUnion: Record[]; + propArrayOfRecordOfUnionOptional?: Record< + string, + string | boolean | number + >[]; + propEncoded: string; +} + +export function simpleModelSerializer(item: SimpleModel): any { + return { + propString: item["propString"], + propboolean: item["propboolean"], + propNumber: item["propNumber"], + propStringOptional: item["propStringOptional"], + propSimpleUnion: _simpleModelPropSimpleUnionSerializer( + item["propSimpleUnion"], + ), + propSimpleUnionOptional: !item["propSimpleUnionOptional"] + ? item["propSimpleUnionOptional"] + : _simpleModelPropSimpleUnionOptionalSerializer( + item["propSimpleUnionOptional"], + ), + propStringLiteral: item["propStringLiteral"], + propBooleanLiteral: item["propBooleanLiteral"], + propNumberLiteral: item["propNumberLiteral"], + propStringLiteralOptional: item["propStringLiteralOptional"], + propStringUnion: item["propStringUnion"], + propStringUnionOptioanl: item["propStringUnionOptioanl"], + propStringUnionNullable: item["propStringUnionNullable"], + propStringUnionAsExtensible: item["propStringUnionAsExtensible"], + propStringUnionAsExtensibleOptional: + item["propStringUnionAsExtensibleOptional"], + propStringUnionAsExtensibleNullable: + item["propStringUnionAsExtensibleNullable"], + propStringUnionAsExtensibleOptionalAndNullable: + item["propStringUnionAsExtensibleOptionalAndNullable"], + propMixedTypeLiteral: _simpleModelPropMixedTypeLiteralSerializer( + item["propMixedTypeLiteral"], + ), + propStringArray: item["propStringArray"].map((p: any) => { + return p; + }), + propBooleanArray: item["propBooleanArray"].map((p: any) => { + return p; + }), + propNumberArray: item["propNumberArray"].map((p: any) => { + return p; + }), + propSimpleUnionArray: simpleModelPropSimpleUnionArrayArraySerializer( + item["propSimpleUnionArray"], + ), + propStringArrayOptional: !item["propStringArrayOptional"] + ? item["propStringArrayOptional"] + : item["propStringArrayOptional"].map((p: any) => { + return p; + }), + propSimpleUnionArrayOptional: !item["propSimpleUnionArrayOptional"] + ? item["propSimpleUnionArrayOptional"] + : simpleModelPropSimpleUnionArrayOptionalArraySerializer( + item["propSimpleUnionArrayOptional"], + ), + propRecordOfString: item["propRecordOfString"], + propRecordOfBoolean: item["propRecordOfBoolean"], + propRecordOfNumber: item["propRecordOfNumber"], + propRecordOfSimpleUnion: simpleModelPropRecordOfSimpleUnionRecordSerializer( + item["propRecordOfSimpleUnion"], + ), + propRecordOfStringOptional: item["propRecordOfStringOptional"], + propRecordOfStringArray: item["propRecordOfStringArray"], + propArrayOfRecordOfString: item["propArrayOfRecordOfString"].map( + (p: any) => { + return p; + }, + ), + propArrayOfRecordOfStringOptional: !item[ + "propArrayOfRecordOfStringOptional" + ] + ? item["propArrayOfRecordOfStringOptional"] + : item["propArrayOfRecordOfStringOptional"].map((p: any) => { + return p; + }), + propRecordOfUnionArray: + simpleModelPropRecordOfUnionArrayArrayRecordSerializer( + item["propRecordOfUnionArray"], + ), + propRecordOfUnionArrayOptional: !item["propRecordOfUnionArrayOptional"] + ? item["propRecordOfUnionArrayOptional"] + : simpleModelPropRecordOfUnionArrayOptionalArrayRecordSerializer( + item["propRecordOfUnionArrayOptional"], + ), + propArrayOfRecordOfUnion: + simpleModelPropArrayOfRecordOfUnionRecordArraySerializer( + item["propArrayOfRecordOfUnion"], + ), + propArrayOfRecordOfUnionOptional: !item["propArrayOfRecordOfUnionOptional"] + ? item["propArrayOfRecordOfUnionOptional"] + : simpleModelPropArrayOfRecordOfUnionOptionalRecordArraySerializer( + item["propArrayOfRecordOfUnionOptional"], + ), + prop_encoded: item["propEncoded"], + }; +} + +/** Alias for _SimpleModelPropSimpleUnion */ +export type _SimpleModelPropSimpleUnion = string | boolean | number; + +export function _simpleModelPropSimpleUnionSerializer( + item: _SimpleModelPropSimpleUnion, +): any { + return item; +} + +export function _simpleModelPropSimpleUnionDeserializer( + item: any, +): _SimpleModelPropSimpleUnion { + return item; +} + +/** Alias for _SimpleModelPropSimpleUnionOptional */ +export type _SimpleModelPropSimpleUnionOptional = string | boolean | number; + +export function _simpleModelPropSimpleUnionOptionalSerializer( + item: _SimpleModelPropSimpleUnionOptional, +): any { + return item; +} + +export function _simpleModelPropSimpleUnionOptionalDeserializer( + item: any, +): _SimpleModelPropSimpleUnionOptional { + return item; +} + +/** Alias for _SimpleModelPropMixedTypeLiteral */ +export type _SimpleModelPropMixedTypeLiteral = "A" | false | 1; + +export function _simpleModelPropMixedTypeLiteralSerializer( + item: _SimpleModelPropMixedTypeLiteral, +): any { + return item; +} + +export function _simpleModelPropMixedTypeLiteralDeserializer( + item: any, +): _SimpleModelPropMixedTypeLiteral { + return item; +} + +/** Alias for _SimpleModelPropSimpleUnionArray */ +export type _SimpleModelPropSimpleUnionArray = string | boolean | number; + +export function _simpleModelPropSimpleUnionArraySerializer( + item: _SimpleModelPropSimpleUnionArray, +): any { + return item; +} + +export function _simpleModelPropSimpleUnionArrayDeserializer( + item: any, +): _SimpleModelPropSimpleUnionArray { + return item; +} + +export function simpleModelPropSimpleUnionArrayArraySerializer( + result: Array<_SimpleModelPropSimpleUnionArray>, +): any[] { + return result.map((item) => { + return _simpleModelPropSimpleUnionArraySerializer(item); + }); +} + +export function simpleModelPropSimpleUnionArrayArrayDeserializer( + result: Array<_SimpleModelPropSimpleUnionArray>, +): any[] { + return result.map((item) => { + return _simpleModelPropSimpleUnionArrayDeserializer(item); + }); +} + +/** Alias for _SimpleModelPropSimpleUnionArrayOptional */ +export type _SimpleModelPropSimpleUnionArrayOptional = + | string + | boolean + | number; + +export function _simpleModelPropSimpleUnionArrayOptionalSerializer( + item: _SimpleModelPropSimpleUnionArrayOptional, +): any { + return item; +} + +export function _simpleModelPropSimpleUnionArrayOptionalDeserializer( + item: any, +): _SimpleModelPropSimpleUnionArrayOptional { + return item; +} + +export function simpleModelPropSimpleUnionArrayOptionalArraySerializer( + result: Array<_SimpleModelPropSimpleUnionArrayOptional>, +): any[] { + return result.map((item) => { + return _simpleModelPropSimpleUnionArrayOptionalSerializer(item); + }); +} + +export function simpleModelPropSimpleUnionArrayOptionalArrayDeserializer( + result: Array<_SimpleModelPropSimpleUnionArrayOptional>, +): any[] { + return result.map((item) => { + return _simpleModelPropSimpleUnionArrayOptionalDeserializer(item); + }); +} + +/** Alias for _SimpleModelPropRecordOfSimpleUnion */ +export type _SimpleModelPropRecordOfSimpleUnion = string | boolean | number; + +export function _simpleModelPropRecordOfSimpleUnionSerializer( + item: _SimpleModelPropRecordOfSimpleUnion, +): any { + return item; +} + +export function _simpleModelPropRecordOfSimpleUnionDeserializer( + item: any, +): _SimpleModelPropRecordOfSimpleUnion { + return item; +} + +export function simpleModelPropRecordOfSimpleUnionRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropRecordOfSimpleUnionSerializer(item[key]); + }); + return result; +} + +export function simpleModelPropRecordOfSimpleUnionRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropRecordOfSimpleUnionDeserializer(item[key]); + }); + return result; +} + +/** Alias for _SimpleModelPropRecordOfUnionArray */ +export type _SimpleModelPropRecordOfUnionArray = string | boolean | number; + +export function _simpleModelPropRecordOfUnionArraySerializer( + item: _SimpleModelPropRecordOfUnionArray, +): any { + return item; +} + +export function _simpleModelPropRecordOfUnionArrayDeserializer( + item: any, +): _SimpleModelPropRecordOfUnionArray { + return item; +} + +export function simpleModelPropRecordOfUnionArrayArraySerializer( + result: Array<_SimpleModelPropRecordOfUnionArray>, +): any[] { + return result.map((item) => { + return _simpleModelPropRecordOfUnionArraySerializer(item); + }); +} + +export function simpleModelPropRecordOfUnionArrayArrayDeserializer( + result: Array<_SimpleModelPropRecordOfUnionArray>, +): any[] { + return result.map((item) => { + return _simpleModelPropRecordOfUnionArrayDeserializer(item); + }); +} + +export function simpleModelPropRecordOfUnionArrayArrayRecordSerializer( + item: Record>, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : simpleModelPropRecordOfUnionArrayArraySerializer(item[key]); + }); + return result; +} + +export function simpleModelPropRecordOfUnionArrayArrayRecordDeserializer( + item: Record, +): Record> { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : simpleModelPropRecordOfUnionArrayArrayDeserializer(item[key]); + }); + return result; +} + +/** Alias for _SimpleModelPropRecordOfUnionArrayOptional */ +export type _SimpleModelPropRecordOfUnionArrayOptional = + | string + | boolean + | number; + +export function _simpleModelPropRecordOfUnionArrayOptionalSerializer( + item: _SimpleModelPropRecordOfUnionArrayOptional, +): any { + return item; +} + +export function _simpleModelPropRecordOfUnionArrayOptionalDeserializer( + item: any, +): _SimpleModelPropRecordOfUnionArrayOptional { + return item; +} + +export function simpleModelPropRecordOfUnionArrayOptionalArraySerializer( + result: Array<_SimpleModelPropRecordOfUnionArrayOptional>, +): any[] { + return result.map((item) => { + return _simpleModelPropRecordOfUnionArrayOptionalSerializer(item); + }); +} + +export function simpleModelPropRecordOfUnionArrayOptionalArrayDeserializer( + result: Array<_SimpleModelPropRecordOfUnionArrayOptional>, +): any[] { + return result.map((item) => { + return _simpleModelPropRecordOfUnionArrayOptionalDeserializer(item); + }); +} + +export function simpleModelPropRecordOfUnionArrayOptionalArrayRecordSerializer( + item: Record>, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : simpleModelPropRecordOfUnionArrayOptionalArraySerializer(item[key]); + }); + return result; +} + +export function simpleModelPropRecordOfUnionArrayOptionalArrayRecordDeserializer( + item: Record, +): Record> { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : simpleModelPropRecordOfUnionArrayOptionalArrayDeserializer(item[key]); + }); + return result; +} + +/** Alias for _SimpleModelPropArrayOfRecordOfUnion */ +export type _SimpleModelPropArrayOfRecordOfUnion = string | boolean | number; + +export function _simpleModelPropArrayOfRecordOfUnionSerializer( + item: _SimpleModelPropArrayOfRecordOfUnion, +): any { + return item; +} + +export function _simpleModelPropArrayOfRecordOfUnionDeserializer( + item: any, +): _SimpleModelPropArrayOfRecordOfUnion { + return item; +} + +export function simpleModelPropArrayOfRecordOfUnionRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropArrayOfRecordOfUnionSerializer(item[key]); + }); + return result; +} + +export function simpleModelPropArrayOfRecordOfUnionRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropArrayOfRecordOfUnionDeserializer(item[key]); + }); + return result; +} + +export function simpleModelPropArrayOfRecordOfUnionRecordArraySerializer( + result: Array>, +): any[] { + return result.map((item) => { + return simpleModelPropArrayOfRecordOfUnionRecordSerializer(item); + }); +} + +export function simpleModelPropArrayOfRecordOfUnionRecordArrayDeserializer( + result: Array>, +): any[] { + return result.map((item) => { + return simpleModelPropArrayOfRecordOfUnionRecordDeserializer(item); + }); +} + +/** Alias for _SimpleModelPropArrayOfRecordOfUnionOptional */ +export type _SimpleModelPropArrayOfRecordOfUnionOptional = + | string + | boolean + | number; + +export function _simpleModelPropArrayOfRecordOfUnionOptionalSerializer( + item: _SimpleModelPropArrayOfRecordOfUnionOptional, +): any { + return item; +} + +export function _simpleModelPropArrayOfRecordOfUnionOptionalDeserializer( + item: any, +): _SimpleModelPropArrayOfRecordOfUnionOptional { + return item; +} + +export function simpleModelPropArrayOfRecordOfUnionOptionalRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropArrayOfRecordOfUnionOptionalSerializer(item[key]); + }); + return result; +} + +export function simpleModelPropArrayOfRecordOfUnionOptionalRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : _simpleModelPropArrayOfRecordOfUnionOptionalDeserializer(item[key]); + }); + return result; +} + +export function simpleModelPropArrayOfRecordOfUnionOptionalRecordArraySerializer( + result: Array>, +): any[] { + return result.map((item) => { + return simpleModelPropArrayOfRecordOfUnionOptionalRecordSerializer(item); + }); +} + +export function simpleModelPropArrayOfRecordOfUnionOptionalRecordArrayDeserializer( + result: Array>, +): any[] { + return result.map((item) => { + return simpleModelPropArrayOfRecordOfUnionOptionalRecordDeserializer(item); + }); +} +``` \ No newline at end of file diff --git a/packages/typespec-ts/test/modularUnit/scenarios/samples/operations/armCurdOperations.md b/packages/typespec-ts/test/modularUnit/scenarios/samples/operations/armCurdOperations.md index 4c56b5cc7c..f8da5f039c 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/samples/operations/armCurdOperations.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/samples/operations/armCurdOperations.md @@ -192,11 +192,11 @@ async function employeesCreateOrUpdate() { properties: { age: 30, city: "gydhnntudughbmxlkyzrskcdkotrxn", - profile: "ms" + profile: "ms", }, tags: { key2913: "urperxmkkhhkp" }, - location: "itajgxyqozseoygnl" - } + location: "itajgxyqozseoygnl", + }, ); console.log(result); } diff --git a/packages/typespec-ts/test/modularUnit/scenarios/samples/operations/multipleExamplesInOneFile.md b/packages/typespec-ts/test/modularUnit/scenarios/samples/operations/multipleExamplesInOneFile.md index 916895aeb8..7c444e069c 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/samples/operations/multipleExamplesInOneFile.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/samples/operations/multipleExamplesInOneFile.md @@ -170,11 +170,11 @@ async function employeesCreateOrUpdateMaxage() { properties: { age: 110, city: "gydhnntudughbmxlkyzrskcdkotrxn", - profile: "ms" + profile: "ms", }, tags: { key2913: "urperxmkkhhkp" }, - location: "itajgxyqozseoygnl" - } + location: "itajgxyqozseoygnl", + }, ); console.log(result); } @@ -196,11 +196,11 @@ async function employeesCreateOrUpdateMinage() { properties: { age: 1, city: "gydhnntudughbmxlkyzrskcdkotrxn", - profile: "ms" + profile: "ms", }, tags: { key2913: "urperxmkkhhkp" }, - location: "itajgxyqozseoygnl" - } + location: "itajgxyqozseoygnl", + }, ); console.log(result); } diff --git a/packages/typespec-ts/test/modularUnit/scenarios/samples/parameters/paramaterSpreadCheck.md b/packages/typespec-ts/test/modularUnit/scenarios/samples/parameters/paramaterSpreadCheck.md index c376b82d93..6c5afe2a44 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/samples/parameters/paramaterSpreadCheck.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/samples/parameters/paramaterSpreadCheck.md @@ -84,8 +84,8 @@ async function read() { { name: "body name" }, { optionalHeader: "optional header", - renamedOptional: "renamed optional query" - } + renamedOptional: "renamed optional query", + }, ); console.log(result); } diff --git a/packages/typespec-ts/test/modularUnit/serializeUtil.spec.ts b/packages/typespec-ts/test/modularUnit/serializeUtil.spec.ts index 24f4dcceae..3364234712 100644 --- a/packages/typespec-ts/test/modularUnit/serializeUtil.spec.ts +++ b/packages/typespec-ts/test/modularUnit/serializeUtil.spec.ts @@ -8,7 +8,7 @@ import { assert } from "chai"; import { assertEqualContent } from "../util/testUtil.js"; // Replaced with new serializers -describe("modular special union serialization", () => { +describe.skip("modular special union serialization", () => { it("shouldn't generate serialize util or as any if there's no special union variant without discriminator", async () => { const tspContent = ` model WidgetData0 { @@ -35,7 +35,12 @@ describe("modular special union serialization", () => { `; const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); + serializeUtil?.getInterface("") + await assertEqualContent( + serializeUtil?.getFullText()!, + `` + ) const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -45,9 +50,9 @@ describe("modular special union serialization", () => { import { TestingContext as Client } from "./index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, PathUncheckedResponse, createRestError, + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _customGet1Send( @@ -59,12 +64,7 @@ describe("modular special union serialization", () => { .path("/customGet1") .get({ ...operationOptionsToRequestParameters(options), - body: { - id: body["id"], - weight: body["weight"], - color: body["color"], - data: body["data"], - }, + body: widget1Serializer(body), }); } @@ -124,7 +124,7 @@ describe("modular special union serialization", () => { `; const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -204,7 +204,7 @@ describe("modular special union serialization", () => { // to test the generated deserialized utils for union variant of model with datetime properties. const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -285,7 +285,7 @@ describe("modular special union serialization", () => { // to test the generated deserialized utils for union variant of model with datetime properties. const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -371,7 +371,7 @@ describe("modular special union serialization", () => { // to test the generated deserialized utils for union variant of model with datetime properties. const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -457,7 +457,7 @@ describe("modular special union serialization", () => { // to test the generated deserialized utils for union variant of model with datetime properties. const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -558,7 +558,7 @@ describe("modular special union serialization", () => { await assertEqualContent( serializeWidgetData1?.getFullText()!, ` - export function widgetData1Serializer(item: WidgetData1): Record { + export function widgetData1Serializer(item: WidgetData1): any { return { kind: item["kind"], start: item["start"].toISOString(), @@ -574,7 +574,7 @@ describe("modular special union serialization", () => { await assertEqualContent( serializeWidgetData0?.getFullText()!, ` - export function widgetData0Serializer(item: WidgetData0): Record { + export function widgetData0Serializer(item: WidgetData0): any { return { kind: item["kind"], fooProp: item["fooProp"], @@ -692,7 +692,7 @@ describe("modular special union serialization", () => { await assertEqualContent( modelsFile?.getFunction("widgetData1Serializer")?.getFullText()!, ` - export function widgetData1Serializer(item: WidgetData1): Record { + export function widgetData1Serializer(item: WidgetData1): any { return { kind: item["kind"], data: uint8ArrayToString(item["data"], "base64") @@ -815,7 +815,7 @@ describe("modular special union serialization", () => { await assertEqualContent( modelsFile?.getFunction("widgetData0Serializer")?.getFullText()!, ` - export function widgetData0Serializer(item: WidgetData0): Record { + export function widgetData0Serializer(item: WidgetData0): any { return { kind: item["kind"], fooProp: uint8ArrayToString(item["fooProp"], "base64"), @@ -827,7 +827,7 @@ describe("modular special union serialization", () => { await assertEqualContent( modelsFile?.getFunction("widgetData1Serializer")?.getFullText()!, ` - export function widgetData1Serializer(item: WidgetData1): Record { + export function widgetData1Serializer(item: WidgetData1): any { return { kind: item["kind"], data: item["data"].toISOString() @@ -945,7 +945,7 @@ describe("modular special union serialization", () => { await assertEqualContent( modelsFile?.getFunction("widgetData0Serializer")?.getFullText()!, ` - export function widgetData0Serializer(item: WidgetData0): Record { + export function widgetData0Serializer(item: WidgetData0): any { return { kind: item["kind"], fooProp: uint8ArrayToString(item["fooProp"], "base64"), @@ -957,7 +957,7 @@ describe("modular special union serialization", () => { await assertEqualContent( modelsFile?.getFunction("widgetData1Serializer")?.getFullText()!, ` - export function widgetData1Serializer(item: WidgetData1): Record { + export function widgetData1Serializer(item: WidgetData1): any { return { kind: item["kind"], data: uint8ArrayToString(item["data"], "base64") @@ -1134,7 +1134,7 @@ describe("modular special union serialization", () => { ` export function vectorStoreAutoChunkingStrategyRequestSerializer( item: VectorStoreAutoChunkingStrategyRequest, - ): Record { + ): any { return { type: item["type"], }; @@ -1147,7 +1147,7 @@ describe("modular special union serialization", () => { ` export function vectorStoreStaticChunkingStrategyRequestSerializer( item: VectorStoreStaticChunkingStrategyRequest, - ): Record { + ): any { return { type: item["type"], static: vectorStoreStaticChunkingStrategyOptionsSerializer(item.static), @@ -1161,14 +1161,14 @@ describe("modular special union serialization", () => { ` export function vectorStoreChunkingStrategyRequestSerializer( item: VectorStoreChunkingStrategyRequestUnion, - ): Record { + ): any { return { ...vectorStoreChunkingStrategyRequestUnionSerializer(item), }; } ` ); - + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -1229,7 +1229,7 @@ describe("modular special union serialization", () => { }); }); -describe("modular special union deserialization", () => { +describe.skip("modular special union deserialization", () => { it("shouldn't generate deserialize util or as any if there's no special union variant without discriminator", async () => { const tspContent = ` model WidgetData0 { @@ -1256,7 +1256,7 @@ describe("modular special union deserialization", () => { `; const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -1337,7 +1337,7 @@ describe("modular special union deserialization", () => { `; const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); assert.equal(operationFiles?.length, 1); @@ -1409,7 +1409,7 @@ describe("modular special union deserialization", () => { // to test the generated deserialized utils for union variant of model with datetime properties. const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -1482,7 +1482,7 @@ describe("modular special union deserialization", () => { // to test the generated deserialized utils for union variant of model with datetime properties. const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -1560,7 +1560,7 @@ describe("modular special union deserialization", () => { // to test the generated deserialized utils for union variant of model with datetime properties. const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -1637,7 +1637,7 @@ describe("modular special union deserialization", () => { // to test the generated deserialized utils for union variant of model with datetime properties. const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); assert.ok(operationFiles); @@ -1722,9 +1722,9 @@ describe("modular special union deserialization", () => { // to test the generated deserialized utils for union variant of model with datetime properties. const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.equal(serializeUtil?.length, 1); + assert.ok(serializeUtil); await assertEqualContent( - serializeUtil?.[0]?.getFullText()!, + serializeUtil?.getFullText()!, ` import { WidgetData1Output, WidgetDataOutput } from "../rest/index.js"; import { WidgetData1, WidgetData } from "../models/models.js"; @@ -1835,7 +1835,7 @@ describe("modular special union deserialization", () => { await emitModularSerializeUtilsFromTypeSpec(tspContent); assert.ok(serializeUtil); await assertEqualContent( - serializeUtil?.[0]?.getFullText()!, + serializeUtil?.getFullText()!, ` import { WidgetData1Output, WidgetDataOutput } from "../rest/index.js"; import { WidgetData1, WidgetData } from "../models/models.js"; @@ -1948,7 +1948,7 @@ describe("modular special union deserialization", () => { await emitModularSerializeUtilsFromTypeSpec(tspContent); assert.ok(serializeUtil); await assertEqualContent( - serializeUtil?.[0]?.getFullText()!, + serializeUtil?.getFullText()!, ` import { WidgetData0Output, @@ -2073,7 +2073,7 @@ describe("modular special union deserialization", () => { await emitModularSerializeUtilsFromTypeSpec(tspContent); assert.ok(serializeUtil); await assertEqualContent( - serializeUtil?.[0]?.getFullText()!, + serializeUtil?.getFullText()!, ` import { WidgetData0Output, @@ -2192,7 +2192,7 @@ describe("modular special union deserialization", () => { `; const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.ok(serializeUtil?.length === 0); + assert.ok(serializeUtil); }); it("should generate deserialize util even if circular in model properties but no other special variants", async () => { @@ -2222,9 +2222,9 @@ describe("modular special union deserialization", () => { `; const serializeUtil = await emitModularSerializeUtilsFromTypeSpec(tspContent); - assert.equal(serializeUtil?.length, 1); + assert.ok(serializeUtil); await assertEqualContent( - serializeUtil?.[0]?.getFullText()!, + serializeUtil?.getFullText()!, ` import { PetUnion, Gold, DogUnion } from "../models/models.js"; import { PetOutput, GoldOutput, DogOutput } from "../rest/index.js"; diff --git a/packages/typespec-ts/test/modularUnit/typeHelpers.spec.ts b/packages/typespec-ts/test/modularUnit/typeHelpers.spec.ts index 8d4fa605a8..186bd3a129 100644 --- a/packages/typespec-ts/test/modularUnit/typeHelpers.spec.ts +++ b/packages/typespec-ts/test/modularUnit/typeHelpers.spec.ts @@ -1,11 +1,6 @@ import { expect } from "chai"; import { Type } from "../../src/modular/modularCodeModel.js"; import { getType, buildType } from "../../src/modular/helpers/typeHelpers.js"; -import { - buildModelInterface, - buildModelTypeAlias, - extractAliases -} from "../../src/modular/emitModels.js"; describe("typeHelpers", () => { describe("getType", () => { @@ -376,14 +371,12 @@ describe("typeHelpers", () => { const type: Type = { type: "Key" }; const result = getType(type); expect(result.name).to.equal("KeyCredential"); - expect(result.originModule).to.equal("@azure/core-auth"); }); it("should handle OAuth2 type", () => { const type: Type = { type: "OAuth2" }; const result = getType(type); expect(result.name).to.equal("TokenCredential"); - expect(result.originModule).to.equal("@azure/core-auth"); }); it("should handle nullable boolean type", () => { @@ -494,39 +487,6 @@ describe("typeHelpers", () => { const result = getType(type); expect(result.name).to.equal("any"); }); - - it("should handle polymorphism base", () => { - const type: Type = { - type: "model", - name: "Fish", - alias: "FishParent", - aliasType: "Fish | Shark | Tuna" - }; - const result = getType(type); - expect(result.name).to.equal("Fish"); - const modelInterface = buildModelInterface(type, { - coreClientTypes: new Set(), - coreLroTypes: new Set() - }); - expect(modelInterface.name).to.equal("FishParent"); - expect(result.originModule).to.equal("models.js"); - expect(Boolean(result.nullable)).to.be.false; - }); - - it("should handle polymorphism alias", () => { - const type: Type = { - type: "model", - name: "Fish", - alias: "FishParent", - aliasType: "FishParent | Shark | Tuna" - }; - const result = extractAliases({ types: [type] } as any); - expect(result.length).to.equal(1); - expect(result[0]!.name).to.equal("Fish"); - const alias = buildModelTypeAlias(result[0]!); - expect(alias.name).to.equal("Fish"); - expect(alias.type).to.equal("FishParent | Shark | Tuna"); - }); }); describe("buildType", () => { diff --git a/packages/typespec-ts/test/unit/armTemplate.spec.ts b/packages/typespec-ts/test/unit/armTemplate.spec.ts index 78fc6ec9fa..d7b5ee9be1 100644 --- a/packages/typespec-ts/test/unit/armTemplate.spec.ts +++ b/packages/typespec-ts/test/unit/armTemplate.spec.ts @@ -70,10 +70,12 @@ describe("ARM template", () => { `; const response = await emitResponsesFromTypeSpec( tspContent, - false, - true, - true, - true + { + needAzureCore: false, + withRawContent: true, + needTCGC: true, + withVersionedApiVersion: true, + } ); assert.ok(response); await assertEqualContent( diff --git a/packages/typespec-ts/test/unit/azureCoreOperationsGenerator.spec.ts b/packages/typespec-ts/test/unit/azureCoreOperationsGenerator.spec.ts index 6275c153aa..3a65bb86c3 100644 --- a/packages/typespec-ts/test/unit/azureCoreOperationsGenerator.spec.ts +++ b/packages/typespec-ts/test/unit/azureCoreOperationsGenerator.spec.ts @@ -64,8 +64,8 @@ async function compileResourceOperation(code: string) { #suppress "@azure-tools/typespec-azure-core/documentation-required" "for test" ${code} `; - const parameters = await emitParameterFromTypeSpec(content, true); - const responses = await emitResponsesFromTypeSpec(content, true); + const parameters = await emitParameterFromTypeSpec(content, {needAzureCore: true}); + const responses = await emitResponsesFromTypeSpec(content, {needAzureCore: true}); return { parameters, responses }; } diff --git a/packages/typespec-ts/test/unit/clientFactoryGenerator.spec.ts b/packages/typespec-ts/test/unit/clientFactoryGenerator.spec.ts index 21169f0f1c..1294147f32 100644 --- a/packages/typespec-ts/test/unit/clientFactoryGenerator.spec.ts +++ b/packages/typespec-ts/test/unit/clientFactoryGenerator.spec.ts @@ -143,7 +143,9 @@ describe("Client Factory generation", () => { V2 } `; - const clientFactory = await emitClientFactoryFromTypeSpec(tsp, true); + const clientFactory = await emitClientFactoryFromTypeSpec(tsp, { + needAzureCore: true, + }); assert.ok(clientFactory); await assertEqualContent( clientFactory!.content, @@ -216,7 +218,9 @@ describe("Client Factory generation", () => { v1_1: "v1.1", } `, - true + { + needAzureCore: true + } ); assert.ok(models); await assertEqualContent( @@ -291,7 +295,9 @@ describe("Client Factory generation", () => { v1_1: "v1.1", } `, - true + { + needAzureCore: true + } ); assert.ok(models); await assertEqualContent( @@ -413,8 +419,6 @@ describe("Client Factory generation", () => { @service( {title: "PetStoreClient"}) namespace PetStore; `, - false, - true ); assert.fail("Should throw diagnostic errors"); } catch (e) { @@ -439,8 +443,9 @@ describe("Client Factory generation", () => { @service( {title: "PetStoreClient"}) namespace PetStore; `, - false, - false + { + mustEmptyDiagnostic: false + } ); assert.ok(factoryFile); diff --git a/packages/typespec-ts/test/unit/modelsGenerator.spec.ts b/packages/typespec-ts/test/unit/modelsGenerator.spec.ts index 42931bc8e8..99138c5137 100644 --- a/packages/typespec-ts/test/unit/modelsGenerator.spec.ts +++ b/packages/typespec-ts/test/unit/modelsGenerator.spec.ts @@ -57,8 +57,10 @@ describe("Input/output model type", () => { @route("/models") @get op getModel(@bodyRoot input: InputOutputModel): InputOutputModel;`, - needAzureCore, - needTCGC + { + needAzureCore, + needTCGC + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -462,10 +464,10 @@ describe("Input/output model type", () => { @get op getModel(...SimpleModel): SimpleModel; `, - false, - true, - false, - false // disable diagnostics + { + needTCGC: true, + mustEmptyDiagnostic: false + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -514,10 +516,10 @@ describe("Input/output model type", () => { @get op getModel(...SimpleModel): SimpleModel; `, - false, - true, - false, - true // throw exception for diagnostics + { + needTCGC: true, + mustEmptyDiagnostic: false + }// throw exception for diagnostics ); } catch (err: any) { assert.strictEqual(err.length, 2); @@ -542,10 +544,10 @@ describe("Input/output model type", () => { @get op getModel(...SimpleModel): SimpleModel; `, - false, - true, - false, - false // disable diagnostics + { + needTCGC: true, + mustEmptyDiagnostic: false + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -597,8 +599,9 @@ describe("Input/output model type", () => { @get op getModel(...SimpleModel): SimpleModel; `, - false, - true + { + needTCGC: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -1728,8 +1731,9 @@ describe("Input/output model type", () => { @get op getModel(...SimpleModel): SimpleModel; `, - false, - true + { + needTCGC: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -1762,8 +1766,9 @@ describe("Input/output model type", () => { @get op getModel(...SimpleModel): SimpleModel; `, - false, - true + { + needTCGC: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -1797,8 +1802,9 @@ describe("Input/output model type", () => { @get op getModel(...SimpleModel): SimpleModel; `, - false, - true + { + needTCGC: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -1845,8 +1851,6 @@ describe("Input/output model type", () => { @encode("seconds", float64) input: duration): NoContentResponse; `, - false, - false ); assert.ok(schemaOutput); await assertEqualContent( @@ -1865,8 +1869,6 @@ describe("Input/output model type", () => { @encode("iso8601") input: duration): NoContentResponse; `, - false, - false ); assert.ok(schemaOutput); await assertEqualContent( @@ -1918,8 +1920,9 @@ describe("Input/output model type", () => { @get op getModel(...SimpleModel): SimpleModel; `, - false, - true + { + needTCGC: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -1952,8 +1955,9 @@ describe("Input/output model type", () => { @get op getModel(...SimpleModel): SimpleModel; `, - false, - true + { + needTCGC: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -1987,8 +1991,9 @@ describe("Input/output model type", () => { @get op getModel(...SimpleModel): SimpleModel; `, - false, - true + { + needTCGC: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -2814,9 +2819,9 @@ describe("Input/output model type", () => { @clientName("testRunOperation", "javascript") op test(): string; `, - false, - false, - true + { + needTCGC: true + } ); assert.ok(parameters); await assertEqualContent( @@ -2955,11 +2960,13 @@ describe("Input/output model type", () => { op1(a: A): void } `, - false, - true, - true, - true, - true + { + needAzureCore: false, + needTCGC: true, + withRawContent: true, + mustEmptyDiagnostic: true, + enableModelNamespace: true + } ); assert.ok(schemaOutput); const { inputModelFile } = schemaOutput!; @@ -3260,9 +3267,11 @@ describe("Input/output model type", () => { `; const schemaOutput = await emitModelsFromTypeSpec( tspDefinition, - true, - true, - true + { + needAzureCore: true, + needTCGC: true, + withRawContent: true, + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -3450,9 +3459,11 @@ describe("Input/output model type", () => { `; const schemaOutput = await emitModelsFromTypeSpec( tspDefinition, - true, - true, - true + { + needAzureCore: true, + needTCGC: true, + withRawContent: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -3570,9 +3581,9 @@ describe("Input/output model type", () => { `; const schemaOutput = await emitModelsFromTypeSpec( tspDefinition, - false, - false, - true + { + withRawContent: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -3619,9 +3630,9 @@ describe("Input/output model type", () => { `; const schemaOutput = await emitModelsFromTypeSpec( tspDefinition, - false, - false, - true + { + withRawContent: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -3654,9 +3665,9 @@ describe("Input/output model type", () => { const paramOutput = await emitParameterFromTypeSpec( tspDefinition, - false, - false, - true + { + withRawContent: true + } ); assert.ok(paramOutput); assert.strictEqual(paramOutput?.path, "parameters.ts"); @@ -3684,8 +3695,9 @@ describe("Input/output model type", () => { ); const responseOutput = await emitResponsesFromTypeSpec( tspDefinition, - false, - true + { + withRawContent: true + } ); assert.ok(responseOutput); assert.strictEqual(responseOutput?.path, "responses.ts"); @@ -3753,9 +3765,9 @@ describe("Input/output model type", () => { `; const schemaOutput = await emitModelsFromTypeSpec( tspDefinition, - false, - false, - true + { + withRawContent: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -3804,9 +3816,9 @@ describe("Input/output model type", () => { const paramOutput = await emitParameterFromTypeSpec( tspDefinition, - false, - false, - true + { + withRawContent: true + } ); assert.ok(paramOutput); assert.strictEqual(paramOutput?.path, "parameters.ts"); @@ -3825,8 +3837,9 @@ describe("Input/output model type", () => { ); const responseOutput = await emitResponsesFromTypeSpec( tspDefinition, - false, - true + { + withRawContent: true + } ); assert.ok(responseOutput); assert.strictEqual(responseOutput?.path, "responses.ts"); @@ -3865,9 +3878,9 @@ describe("Input/output model type", () => { `; const schemaOutput = await emitModelsFromTypeSpec( tspDefinition, - false, - false, - true + { + withRawContent: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -3875,9 +3888,9 @@ describe("Input/output model type", () => { assert.isUndefined(outputModelFile); const paramOutput = await emitParameterFromTypeSpec( tspDefinition, - false, - false, - true + { + withRawContent: true + } ); assert.ok(paramOutput); assert.strictEqual(paramOutput?.path, "parameters.ts"); @@ -3904,8 +3917,9 @@ describe("Input/output model type", () => { ); const responseOutput = await emitResponsesFromTypeSpec( tspDefinition, - false, - true + { + withRawContent: true + } ); assert.ok(responseOutput); assert.strictEqual(responseOutput?.path, "responses.ts"); @@ -3955,9 +3969,9 @@ describe("Input/output model type", () => { `; const schemaOutput = await emitModelsFromTypeSpec( tspDefinition, - false, - false, - true + { + withRawContent: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -4001,9 +4015,10 @@ describe("Input/output model type", () => { `; const schemaOutput = await emitModelsFromTypeSpec( tspDefinition, - true, - false, - true + { + needAzureCore: true, + withRawContent: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -4017,10 +4032,9 @@ describe("Input/output model type", () => { assert.isUndefined(outputModelFile); const paramOutput = await emitParameterFromTypeSpec( tspDefinition, - false, - false, - true, - true + { + withRawContent: true, + } ); assert.ok(paramOutput); assert.strictEqual(paramOutput?.path, "parameters.ts"); @@ -4078,9 +4092,10 @@ describe("Input/output model type", () => { `; const schemaOutput = await emitModelsFromTypeSpec( tspDefinition, - true, - false, - true + { + needAzureCore: true, + withRawContent: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -4094,9 +4109,9 @@ describe("Input/output model type", () => { assert.isUndefined(outputModelFile); const paramOutput = await emitParameterFromTypeSpec( tspDefinition, - false, - false, - true + { + withRawContent: true + } ); assert.ok(paramOutput); assert.strictEqual(paramOutput?.path, "parameters.ts"); @@ -4153,10 +4168,9 @@ describe("Input/output model type", () => { const schemaOutput = await emitModelsFromTypeSpec( tspContent, - false, - false, - true, - true + { + withRawContent: true + } ); assert.ok(schemaOutput); const { inputModelFile, outputModelFile } = schemaOutput!; @@ -4164,10 +4178,9 @@ describe("Input/output model type", () => { assert.isUndefined(outputModelFile); const paramOutput = await emitParameterFromTypeSpec( tspContent, - false, - false, - true, - true + { + withRawContent: true + } ); assert.ok(paramOutput); assert.fail("Should throw diagnostic warnings"); diff --git a/packages/typespec-ts/test/unit/pageHelperGenerator.spec.ts b/packages/typespec-ts/test/unit/pageHelperGenerator.spec.ts index 040e50e052..5d153dc228 100644 --- a/packages/typespec-ts/test/unit/pageHelperGenerator.spec.ts +++ b/packages/typespec-ts/test/unit/pageHelperGenerator.spec.ts @@ -39,5 +39,7 @@ async function generatePagingHelper(code: string) { ${code} `; - return await emitPageHelperFromTypeSpec(content, true); + return await emitPageHelperFromTypeSpec(content, { + needAzureCore: true + }); } diff --git a/packages/typespec-ts/test/unit/parametersGenerator.spec.ts b/packages/typespec-ts/test/unit/parametersGenerator.spec.ts index c33f80679f..8eb6f4d43b 100644 --- a/packages/typespec-ts/test/unit/parametersGenerator.spec.ts +++ b/packages/typespec-ts/test/unit/parametersGenerator.spec.ts @@ -29,10 +29,9 @@ describe("Parameters.ts", () => { ); const models = await emitClientFactoryFromTypeSpec( tspContent, - false, - true, - false, - true + { + needNamespaces: true + } ); assert.ok(models); await assertEqualContent( @@ -106,11 +105,10 @@ describe("Parameters.ts", () => { } op test(...ApiVersionParameter): string; `, - false, - true, - false, - true, - true + { + needTCGC: true, + withVersionedApiVersion: true + } ); assert.ok(parameters); await assertEqualContent( @@ -134,8 +132,9 @@ describe("Parameters.ts", () => { @route("/test1") op test1(): string; `, - false, - true + { + needTCGC: true + } ); assert.ok(parameters); await assertEqualContent( diff --git a/packages/typespec-ts/test/unit/responsesGenerator.spec.ts b/packages/typespec-ts/test/unit/responsesGenerator.spec.ts index 10f9b7464c..cfe3e65f54 100644 --- a/packages/typespec-ts/test/unit/responsesGenerator.spec.ts +++ b/packages/typespec-ts/test/unit/responsesGenerator.spec.ts @@ -246,7 +246,9 @@ describe("Responses.ts", () => { @doc("testing") @get op read(): Azure.Core.Foundations.ErrorResponse; `, - true + { + needAzureCore: true + } ); assert.ok(parameters); await assertEqualContent( @@ -288,8 +290,8 @@ describe("Responses.ts", () => { @doc("testing") @get op read(): ErrorResponse; `; - const parameters = await emitResponsesFromTypeSpec(tsp, false); - const models = await emitModelsFromTypeSpec(tsp, false); + const parameters = await emitResponsesFromTypeSpec(tsp); + const models = await emitModelsFromTypeSpec(tsp); assert.ok(parameters); await assertEqualContent( models?.outputModelFile?.content!, diff --git a/packages/typespec-ts/test/unit/sample/generateSampleContent.spec.ts b/packages/typespec-ts/test/unit/sample/generateSampleContent.spec.ts index b852f60741..ef47915077 100644 --- a/packages/typespec-ts/test/unit/sample/generateSampleContent.spec.ts +++ b/packages/typespec-ts/test/unit/sample/generateSampleContent.spec.ts @@ -122,7 +122,9 @@ describe("Integration test for mocking sample", () => { } op getModel(@body input: Test): void; `, - true + { + needAzureCore: true + } ); const mockStr = generateParameterTypeValue( "Test", @@ -153,7 +155,9 @@ describe("Integration test for mocking sample", () => { } op getModel(@body input: Test): void; `, - true + { + needAzureCore: true + } ); const mockStr = generateParameterTypeValue( "Test", @@ -247,7 +251,9 @@ describe("Integration test for mocking sample", () => { } op getModel(@body input: Test): void; `, - true + { + needAzureCore: true + } ); const mockStr = generateParameterTypeValue( "Test", @@ -286,7 +292,9 @@ describe("Integration test for mocking sample", () => { } op getModel(@body input: Test): void; `, - true + { + needAzureCore: true + } ); const mockStr = generateParameterTypeValue( "Test", @@ -324,7 +332,9 @@ describe("Integration test for mocking sample", () => { } op getModel(@body input: Test): void; `, - true + { + needAzureCore: true + } ); const mockStr = generateParameterTypeValue( "Test", @@ -370,7 +380,9 @@ describe("Integration test for mocking sample", () => { } op getModel(@body input: Test): void; `, - true + { + needAzureCore: true + } ); const mockStr = generateParameterTypeValue( "Test", @@ -404,7 +416,9 @@ describe("Integration test for mocking sample", () => { } op getModel(@body input: Test): void; `, - true + { + needAzureCore: true + } ); const mockStr = generateParameterTypeValue( "Test", diff --git a/packages/typespec-ts/test/unit/transform/transformSchemas.spec.ts b/packages/typespec-ts/test/unit/transform/transformSchemas.spec.ts index bce31028a4..47cc0481d6 100644 --- a/packages/typespec-ts/test/unit/transform/transformSchemas.spec.ts +++ b/packages/typespec-ts/test/unit/transform/transformSchemas.spec.ts @@ -158,7 +158,9 @@ describe("#transformSchemas", () => { @get op getModel(@body input: Test): Test; `, - true + { + needAzureCore: true + } ); assert.isNotNull(schemaOutput); const first = schemaOutput?.[0] as ObjectSchema; @@ -212,7 +214,9 @@ describe("#transformSchemas", () => { @get op getModel(@body input: Test): Test; `, - true + { + needAzureCore: true + } ); assert.isNotNull(schemaOutput); const first = schemaOutput?.[0] as ObjectSchema; @@ -339,7 +343,9 @@ describe("#transformSchemas", () => { @get op getModel(@body input: Test): Test; `, - true + { + needAzureCore: true + } ); assert.isNotNull(schemaOutput); const first = schemaOutput?.[0] as ObjectSchema; @@ -389,7 +395,9 @@ describe("#transformSchemas", () => { @get op getModel(@body input: Test): Test; `, - true + { + needAzureCore: true + } ); assert.isNotNull(schemaOutput); const first = schemaOutput?.[0] as ObjectSchema; @@ -421,7 +429,9 @@ describe("#transformSchemas", () => { @get op getModel(@body input: Test): Test; `, - true + { + needAzureCore: true + } ); assert.isNotNull(schemaOutput); const first = schemaOutput?.[0] as ObjectSchema; @@ -489,7 +499,9 @@ describe("#transformSchemas", () => { @get op getModel(@body input: Test): Test; `, - true + { + needAzureCore: true + } ); assert.isNotNull(schemaOutput); const first = schemaOutput?.[0] as ObjectSchema; @@ -530,7 +542,7 @@ describe("#transformSchemas", () => { @get op getModel(@body input: Test): Test; `, - true + {needAzureCore: true} ); assert.isNotNull(schemaOutput); const first = schemaOutput?.[0] as ObjectSchema; @@ -576,7 +588,9 @@ describe("#transformSchemas", () => { @get op getModel(@body input: Test): Test; `, - true + { + needAzureCore: true + } ); assert.isNotNull(schemaOutput); const first = schemaOutput?.[0] as ObjectSchema; diff --git a/packages/typespec-ts/test/util/emitUtil.ts b/packages/typespec-ts/test/util/emitUtil.ts index 81e11b6bcb..c8cf606763 100644 --- a/packages/typespec-ts/test/util/emitUtil.ts +++ b/packages/typespec-ts/test/util/emitUtil.ts @@ -11,25 +11,20 @@ import { initInternalImports } from "@azure-tools/rlc-common"; import { - buildModels, - buildModelsOptions + emitTypes, } from "../../src/modular/emitModels.js"; import { - compileTypeSpecFor, - createDpgContextTestHelper, - ExampleJson, - rlcEmitterFor -} from "./testUtil.js"; + buildApiOptions +} from "../../src/modular/emitModelsOptions.js"; +import { compileTypeSpecFor, createDpgContextTestHelper, ExampleJson, rlcEmitterFor } from "./testUtil.js"; import { transformRLCModel, transformUrlInfo } from "../../src/transform/transform.js"; -import { Project } from "ts-morph"; import { buildClassicalClient } from "../../src/modular/buildClassicalClient.js"; import { buildClientContext } from "../../src/modular/buildClientContext.js"; import { buildOperationFiles } from "../../src/modular/buildOperations.js"; -import { buildSerializeUtils } from "../../src/modular/buildSerializeUtils.js"; import { emitCodeModel } from "../../src/modular/buildCodeModel.js"; import { expectDiagnosticEmpty } from "@typespec/compiler/testing"; import { getCredentialInfo } from "../../src/transform/transfromRLCOptions.js"; @@ -45,14 +40,21 @@ import { emitSamples } from "../../src/modular/emitSamples.js"; export async function emitPageHelperFromTypeSpec( tspContent: string, - needAzureCore: boolean = false, - needTCGC: boolean = false + { + needAzureCore = false, + needTCGC = false + }: { + needAzureCore?: boolean; + needTCGC?: boolean; + } = {} ) { const context = await rlcEmitterFor( tspContent, - true, - needAzureCore, - needTCGC + { + needNamespaces: true, + needAzureCore, + needTCGC + } ); const program = context.program; const dpgContext = await createDpgContextTestHelper(context.program); @@ -81,14 +83,21 @@ export async function emitPageHelperFromTypeSpec( export async function emitSchemasFromTypeSpec( tspContent: string, - needAzureCore: boolean = false, - needTCGC: boolean = false + { + needAzureCore = false, + needTCGC = false + }: { + needAzureCore?: boolean; + needTCGC?: boolean; + } = {} ) { const context = await rlcEmitterFor( tspContent, - true, - needAzureCore, - needTCGC + { + needNamespaces: true, + needAzureCore, + needTCGC + } ); const program = context.program; const dpgContext = await createDpgContextTestHelper(context.program); @@ -103,18 +112,28 @@ export async function emitSchemasFromTypeSpec( export async function emitModelsFromTypeSpec( tspContent: string, - needAzureCore: boolean = false, - needTCGC: boolean = false, - withRawContent: boolean = false, - mustEmptyDiagnostic: boolean = true, - enableModelNamespace: boolean = false + { + needAzureCore = false, + needTCGC = false, + withRawContent = false, + mustEmptyDiagnostic = true, + enableModelNamespace = false + }: { + needAzureCore?: boolean; + needTCGC?: boolean; + withRawContent?: boolean; + mustEmptyDiagnostic?: boolean; + enableModelNamespace?: boolean; + } = {} ) { const context = await rlcEmitterFor( tspContent, - true, - needAzureCore, - needTCGC, - withRawContent + { + needNamespaces: true, + needAzureCore, + needTCGC, + withRawContent + } ); const dpgContext = await createDpgContextTestHelper( context.program, @@ -142,19 +161,29 @@ export async function emitModelsFromTypeSpec( export async function emitParameterFromTypeSpec( tspContent: string, - needAzureCore: boolean = false, - needTCGC: boolean = false, - withRawContent: boolean = false, - mustEmptyDiagnostic: boolean = true, - withVersionedApiVersion: boolean = false + { + needAzureCore = false, + needTCGC = false, + withRawContent = false, + mustEmptyDiagnostic = true, + withVersionedApiVersion = false + }: { + needAzureCore?: boolean; + needTCGC?: boolean; + withRawContent?: boolean; + mustEmptyDiagnostic?: boolean; + withVersionedApiVersion?: boolean + } = {} ) { const context = await rlcEmitterFor( tspContent, - true, - needAzureCore, - needTCGC, - withRawContent, - withVersionedApiVersion + { + needNamespaces: true, + needAzureCore, + needTCGC, + withRawContent, + withVersionedApiVersion + } ); const dpgContext = await createDpgContextTestHelper(context.program); const clients = getRLCClients(dpgContext); @@ -187,9 +216,16 @@ export async function emitParameterFromTypeSpec( export async function emitClientDefinitionFromTypeSpec( tspContent: string, - needAzureCore: boolean = false + { + needAzureCore = false + }: { + needAzureCore?: boolean; + } = {} ) { - const context = await rlcEmitterFor(tspContent, true, needAzureCore); + const context = await rlcEmitterFor(tspContent, { + needNamespaces: true, + needAzureCore + }); const dpgContext = await createDpgContextTestHelper(context.program); const clients = getRLCClients(dpgContext); const internalImports = initInternalImports(); @@ -212,17 +248,26 @@ export async function emitClientDefinitionFromTypeSpec( export async function emitClientFactoryFromTypeSpec( tspContent: string, - needAzureCore: boolean = false, - mustEmptyDiagnostic = true, - withRawContent = false, - needNamespaces = false + { + needAzureCore = false, + mustEmptyDiagnostic = true, + withRawContent = false, + needNamespaces = false + }: { + needAzureCore?: boolean; + mustEmptyDiagnostic?: boolean; + withRawContent?: boolean; + needNamespaces?: boolean; + } = {} ) { const context = await rlcEmitterFor( tspContent, - needNamespaces, - needAzureCore, - false, - withRawContent + { + needNamespaces, + needAzureCore, + needTCGC: false, + withRawContent + } ); const program = context.program; const dpgContext = await createDpgContextTestHelper(context.program); @@ -263,20 +308,30 @@ export async function emitClientFactoryFromTypeSpec( export async function emitResponsesFromTypeSpec( tspContent: string, - needAzureCore: boolean = false, - withRawContent: boolean = false, - needTCGC: boolean = false, - withVersionedApiVersion: boolean = false, - needArmTemplate: boolean = false + { + needAzureCore = false, + withRawContent = false, + needTCGC = false, + withVersionedApiVersion = false, + needArmTemplate = false + }: { + needAzureCore?: boolean; + withRawContent?: boolean; + needTCGC?: boolean; + withVersionedApiVersion?: boolean; + needArmTemplate?: boolean; + } = {} ) { const context = await rlcEmitterFor( tspContent, - true, - needAzureCore, - needTCGC, - withRawContent, - withVersionedApiVersion, - needArmTemplate + { + needNamespaces: true, + needAzureCore, + needTCGC, + withRawContent, + withVersionedApiVersion, + needArmTemplate + } ); const dpgContext = await createDpgContextTestHelper(context.program); const importSet = initInternalImports(); @@ -300,7 +355,12 @@ export async function emitResponsesFromTypeSpec( } export async function getRLCClientsFromTypeSpec(tspContent: string) { - const context = await rlcEmitterFor(tspContent, true, false, true, true); + const context = await rlcEmitterFor(tspContent, { + needNamespaces: true, + needAzureCore: false, + needTCGC: true, + withRawContent: true + }); const dpgContext = await createDpgContextTestHelper(context.program); const clients = getRLCClients(dpgContext); expectDiagnosticEmpty(dpgContext.program.diagnostics); @@ -309,19 +369,30 @@ export async function getRLCClientsFromTypeSpec(tspContent: string) { export async function emitModularModelsFromTypeSpec( tspContent: string, - needOptions: boolean = false, - withRawContent: boolean = false, - needAzureCore: boolean = false, - compatibilityMode: boolean = false, - mustEmptyDiagnostic: boolean = true, - experimentalExtensibleEnums: boolean = false + { + needOptions = false, + withRawContent = false, + needAzureCore = false, + compatibilityMode = false, + mustEmptyDiagnostic = true, + experimentalExtensibleEnums = false + }: { + needOptions?: boolean; + withRawContent?: boolean; + needAzureCore?: boolean; + compatibilityMode?: boolean; + mustEmptyDiagnostic?: boolean; + experimentalExtensibleEnums?: boolean; + } = {} ) { const context = await rlcEmitterFor( tspContent, - true, - needAzureCore, - false, - withRawContent + { + needNamespaces: true, + needAzureCore, + needTCGC: false, + withRawContent, + } ); const dpgContext = await createDpgContextTestHelper(context.program); const serviceNameToRlcModelsMap: Map = new Map< @@ -355,12 +426,12 @@ export async function emitModularModelsFromTypeSpec( modularCodeModel.clients[0] ) { if (needOptions) { - modelFile = buildModelsOptions( + modelFile = buildApiOptions( modularCodeModel.clients[0], modularCodeModel ); } else { - modelFile = buildModels(modularCodeModel.clients[0], modularCodeModel); + modelFile = emitTypes(dpgContext, { sourceRoot: "" }); } } } @@ -376,56 +447,39 @@ export async function emitModularSerializeUtilsFromTypeSpec( ) { const context = await rlcEmitterFor(tspContent); const dpgContext = await createDpgContextTestHelper(context.program); - const serviceNameToRlcModelsMap: Map = new Map< - string, - RLCModel - >(); - const project = useContext("outputProject"); const binder = useBinder(); - const clients = getRLCClients(dpgContext); - if (clients && clients[0]) { - dpgContext.rlcOptions!.isModularLibrary = true; - const rlcModels = await transformRLCModel(clients[0], dpgContext); - serviceNameToRlcModelsMap.set(clients[0].service.name, rlcModels); - const modularCodeModel = emitCodeModel( - dpgContext, - serviceNameToRlcModelsMap, - "", - project, - { - casing: "camel" - } - ); - if ( - modularCodeModel && - modularCodeModel.clients && - modularCodeModel.clients.length > 0 && - modularCodeModel.clients[0] - ) { - const files = buildSerializeUtils(modularCodeModel); - binder.resolveAllReferences(); - return files; - } - } + dpgContext.rlcOptions!.isModularLibrary = true; + const files = emitTypes(dpgContext, { sourceRoot: "" }); + binder.resolveAllReferences(); expectDiagnosticEmpty(dpgContext.program.diagnostics); - return undefined; + return files; } export async function emitModularOperationsFromTypeSpec( tspContent: string, - mustEmptyDiagnostic = true, - needNamespaces: boolean = true, - needAzureCore: boolean = false, - withRawContent: boolean = false, - withVersionedApiVersion: boolean = false + { + mustEmptyDiagnostic = true, + needNamespaces = true, + needAzureCore = false, + withRawContent = false, + withVersionedApiVersion = false + }: { + mustEmptyDiagnostic?: boolean; + needNamespaces?: boolean; + needAzureCore?: boolean; + withRawContent?: boolean; + withVersionedApiVersion?: boolean; + } = {} ) { const context = await rlcEmitterFor( tspContent, - needNamespaces, - needAzureCore, - false, - withRawContent, - withVersionedApiVersion + { + needNamespaces, + needAzureCore, + needTCGC: false, + withRawContent, + withVersionedApiVersion + } ); const dpgContext = await createDpgContextTestHelper(context.program); const serviceNameToRlcModelsMap: Map = new Map< @@ -471,23 +525,31 @@ export async function emitModularOperationsFromTypeSpec( export async function emitModularClientContextFromTypeSpec( tspContent: string, - withRawContent: boolean = false, - withVersionedApiVersion: boolean = false + { + withRawContent = false, + withVersionedApiVersion = false + }: { + withRawContent?: boolean; + withVersionedApiVersion?: boolean; + } = {} ) { const context = await rlcEmitterFor( tspContent, - true, - false, - false, - withRawContent, - withVersionedApiVersion + { + needNamespaces: true, + needAzureCore: false, + needTCGC: false, + withRawContent, + withVersionedApiVersion + } ); const dpgContext = await createDpgContextTestHelper(context.program); const serviceNameToRlcModelsMap: Map = new Map< string, RLCModel >(); - const project = new Project(); + const project = useContext("outputProject"); + const binder = useBinder(); const clients = getRLCClients(dpgContext); if (clients && clients[0]) { dpgContext.rlcOptions!.isModularLibrary = true; @@ -508,11 +570,13 @@ export async function emitModularClientContextFromTypeSpec( modularCodeModel.clients.length > 0 && modularCodeModel.clients[0] ) { - return buildClientContext( + const res = buildClientContext( modularCodeModel.clients[0], dpgContext, modularCodeModel ); + binder.resolveAllReferences(); + return res; } } expectDiagnosticEmpty(dpgContext.program.diagnostics); @@ -521,23 +585,31 @@ export async function emitModularClientContextFromTypeSpec( export async function emitModularClientFromTypeSpec( tspContent: string, - withRawContent: boolean = false, - withVersionedApiVersion: boolean = false + { + withRawContent = false, + withVersionedApiVersion = false + }: { + withRawContent?: boolean; + withVersionedApiVersion?: boolean; + } = {} ) { const context = await rlcEmitterFor( tspContent, - true, - false, - false, - withRawContent, - withVersionedApiVersion + { + needNamespaces: true, + needAzureCore: false, + needTCGC: false, + withRawContent, + withVersionedApiVersion + } ); const dpgContext = await createDpgContextTestHelper(context.program); const serviceNameToRlcModelsMap: Map = new Map< string, RLCModel >(); - const project = new Project(); + const project = useContext("outputProject"); + const binder = useBinder(); const clients = getRLCClients(dpgContext); if (clients && clients[0]) { dpgContext.rlcOptions!.isModularLibrary = true; @@ -558,11 +630,13 @@ export async function emitModularClientFromTypeSpec( modularCodeModel.clients.length > 0 && modularCodeModel.clients[0] ) { - return buildClassicalClient( + const res = buildClassicalClient( modularCodeModel.clients[0], dpgContext, modularCodeModel ); + binder.resolveAllReferences(); + return res; } } expectDiagnosticEmpty(dpgContext.program.diagnostics); diff --git a/packages/typespec-ts/test/util/testUtil.ts b/packages/typespec-ts/test/util/testUtil.ts index 067ae22281..c4ce8c8aea 100644 --- a/packages/typespec-ts/test/util/testUtil.ts +++ b/packages/typespec-ts/test/util/testUtil.ts @@ -54,15 +54,27 @@ export async function createRLCEmitterTestHost() { }); } +export interface RLCEmitterOptions { + needNamespaces?: boolean; + needAzureCore?: boolean; + needTCGC?: boolean; + withRawContent?: boolean; + withVersionedApiVersion?: boolean; + needArmTemplate?: boolean; + exampleJson?: Record; +} + export async function rlcEmitterFor( code: string, - needNamespaces: boolean = true, - needAzureCore: boolean = false, - needTCGC: boolean = false, - withRawContent: boolean = false, - withVersionedApiVersion: boolean = false, - needArmTemplate: boolean = false, - exampleJson: Record = {} + { + needNamespaces = true, + needAzureCore = false, + needTCGC = false, + withRawContent = false, + withVersionedApiVersion = false, + needArmTemplate = false, + exampleJson = {} + }: RLCEmitterOptions = {} ): Promise { const host: TestHost = await createRLCEmitterTestHost(); const namespace = ` @@ -205,7 +217,7 @@ export async function createDpgContextTestHelper( tcgcContext: sdkContext }); - provideSdkTypes(context.sdkPackage); + provideSdkTypes(context); await provideBinderWithAzureDependencies(outputProject); return sdkContext; diff --git a/packages/typespec-ts/tsconfig.json b/packages/typespec-ts/tsconfig.json index 65dbd014db..62b681c8b8 100644 --- a/packages/typespec-ts/tsconfig.json +++ b/packages/typespec-ts/tsconfig.json @@ -31,6 +31,6 @@ "ts-node": { "esm": true }, - "include": ["src/**/*.ts"], + "include": ["src/**/*.ts", "src/modular/emitModelsOptions.ts"], "exclude": ["dist", "node_modules", "typespec-output"] }