From 4540897e3931c331a2489d33e491d35c17ccba24 Mon Sep 17 00:00:00 2001 From: Qiaoqiao Zhang Date: Mon, 4 Sep 2023 15:39:21 +0800 Subject: [PATCH 01/17] add-encode-test-case-for-modular --- .../test/commands/cadl-ranch-list.ts | 12 ++ .../modularIntegration/encodeBytes.spec.ts | 156 ++++++++++++++ .../modularIntegration/encodeDatetime.spec.ts | 182 ++++++++++++++++ .../modularIntegration/encodeDuration.spec.ts | 158 ++++++++++++++ .../generated/encode/bytes/src/BytesClient.ts | 130 ++++++++++++ .../encode/bytes/src/api/BytesContext.ts | 16 ++ .../generated/encode/bytes/src/api/header.ts | 148 +++++++++++++ .../generated/encode/bytes/src/api/index.ts | 26 +++ .../encode/bytes/src/api/property.ts | 172 +++++++++++++++ .../generated/encode/bytes/src/api/query.ts | 148 +++++++++++++ .../generated/encode/bytes/src/index.ts | 22 ++ .../generated/encode/bytes/src/logger.ts | 5 + .../encode/bytes/src/models/index.ts | 23 ++ .../encode/bytes/src/models/models.ts | 18 ++ .../encode/bytes/src/models/options.ts | 28 +++ .../encode/bytes/src/rest/bytesClient.ts | 35 +++ .../bytes/src/rest/clientDefinitions.ts | 133 ++++++++++++ .../generated/encode/bytes/src/rest/index.ts | 13 ++ .../generated/encode/bytes/src/rest/models.ts | 18 ++ .../encode/bytes/src/rest/outputModels.ts | 18 ++ .../encode/bytes/src/rest/parameters.ts | 126 +++++++++++ .../encode/bytes/src/rest/responses.ts | 74 +++++++ .../encode/bytes/src/rest/serializeHelper.ts | 6 + .../generated/encode/bytes/tspconfig.yaml | 14 ++ .../encode/datetime/src/DatetimeClient.ts | 137 ++++++++++++ .../datetime/src/api/DatetimeContext.ts | 18 ++ .../encode/datetime/src/api/header.ts | 182 ++++++++++++++++ .../encode/datetime/src/api/index.ts | 29 +++ .../encode/datetime/src/api/property.ts | 199 ++++++++++++++++++ .../encode/datetime/src/api/query.ts | 182 ++++++++++++++++ .../generated/encode/datetime/src/index.ts | 26 +++ .../generated/encode/datetime/src/logger.ts | 5 + .../encode/datetime/src/models/index.ts | 27 +++ .../encode/datetime/src/models/models.ts | 22 ++ .../encode/datetime/src/models/options.ts | 34 +++ .../datetime/src/rest/clientDefinitions.ts | 171 +++++++++++++++ .../datetime/src/rest/datetimeClient.ts | 35 +++ .../encode/datetime/src/rest/index.ts | 13 ++ .../encode/datetime/src/rest/models.ts | 22 ++ .../encode/datetime/src/rest/outputModels.ts | 22 ++ .../encode/datetime/src/rest/parameters.ts | 155 ++++++++++++++ .../encode/datetime/src/rest/responses.ts | 91 ++++++++ .../datetime/src/rest/serializeHelper.ts | 6 + .../generated/encode/datetime/tspconfig.yaml | 14 ++ .../encode/duration/src/DurationClient.ts | 149 +++++++++++++ .../duration/src/api/DurationContext.ts | 18 ++ .../encode/duration/src/api/header.ts | 182 ++++++++++++++++ .../encode/duration/src/api/index.ts | 29 +++ .../encode/duration/src/api/property.ts | 199 ++++++++++++++++++ .../encode/duration/src/api/query.ts | 182 ++++++++++++++++ .../generated/encode/duration/src/index.ts | 26 +++ .../generated/encode/duration/src/logger.ts | 5 + .../encode/duration/src/models/index.ts | 27 +++ .../encode/duration/src/models/models.ts | 22 ++ .../encode/duration/src/models/options.ts | 34 +++ .../duration/src/rest/clientDefinitions.ts | 167 +++++++++++++++ .../duration/src/rest/durationClient.ts | 35 +++ .../encode/duration/src/rest/index.ts | 13 ++ .../encode/duration/src/rest/models.ts | 22 ++ .../encode/duration/src/rest/outputModels.ts | 22 ++ .../encode/duration/src/rest/parameters.ts | 156 ++++++++++++++ .../encode/duration/src/rest/responses.ts | 91 ++++++++ .../duration/src/rest/serializeHelper.ts | 6 + .../generated/encode/duration/tspconfig.yaml | 14 ++ 64 files changed, 4470 insertions(+) create mode 100644 packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts create mode 100644 packages/typespec-ts/test/modularIntegration/encodeDatetime.spec.ts create mode 100644 packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/BytesClient.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/BytesContext.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/logger.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/models.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/options.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/bytesClient.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/clientDefinitions.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/models.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/outputModels.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/parameters.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/responses.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/serializeHelper.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/bytes/tspconfig.yaml create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/DatetimeClient.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/DatetimeContext.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/logger.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/models.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/options.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/clientDefinitions.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/datetimeClient.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/models.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/outputModels.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/parameters.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/responses.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/serializeHelper.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/datetime/tspconfig.yaml create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/DurationContext.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/logger.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/options.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/clientDefinitions.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/durationClient.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/models.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/outputModels.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/parameters.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/responses.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/serializeHelper.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/encode/duration/tspconfig.yaml diff --git a/packages/typespec-ts/test/commands/cadl-ranch-list.ts b/packages/typespec-ts/test/commands/cadl-ranch-list.ts index 4ea4f28312..d2dec8c71a 100644 --- a/packages/typespec-ts/test/commands/cadl-ranch-list.ts +++ b/packages/typespec-ts/test/commands/cadl-ranch-list.ts @@ -207,5 +207,17 @@ export const modularTsps: TypeSpecRanchConfig[] = [ { outputPath: "azure/core", inputPath: "azure/core/basic" + }, + { + outputPath: "encode/bytes", + inputPath: "encode/bytes" + }, + { + outputPath: "encode/duration", + inputPath: "encode/duration" + }, + { + outputPath: "encode/datetime", + inputPath: "encode/datetime" } ]; diff --git a/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts new file mode 100644 index 0000000000..7a4d37d223 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts @@ -0,0 +1,156 @@ +import { assert } from "chai"; +import { BytesClient } from "./generated/encode/bytes/src/index"; +import { stringToUint8Array } from "@azure/core-util"; +describe("EncodeDatetimeClient Rest Client", () => { + let client: BytesClient; + + beforeEach(() => { + client = new BytesClient({ + allowInsecureConnection: true, + retryOptions: { + maxRetries: 0 + } + }); + }); + + describe("query", () => { + it(`should get bytes`, async () => { + try { + const result = await client.query.default( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64 encoding`, async () => { + try { + const result = await client.query.base64( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64url encoding`, async () => { + try { + const result = await client.query.base64url( + stringToUint8Array("dGVzdA", "base64url") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64url-array`, async () => { + try { + const result = await client.query.base64urlArray([ + stringToUint8Array("dGVzdA", "base64url"), + stringToUint8Array("dGVzdA", "base64url") + ]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("property", () => { + it(`should post bytes`, async () => { + try { + const result = await client.property.default( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should post bytes base64 encoding`, async () => { + try { + const result = await client.property.base64( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should post bytes base64url encoding`, async () => { + try { + const result = await client.property.base64url( + stringToUint8Array("dGVzdA", "base64url") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should post bytes base64url array`, async () => { + try { + const result = await client.property.base64urlArray([ + stringToUint8Array("dGVzdA", "base64url"), + stringToUint8Array("dGVzdA", "base64url") + ]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("header", () => { + it(`should get bytes`, async () => { + try { + const result = await client.header.default( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64 encoding`, async () => { + try { + const result = await client.header.base64( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64url encoding`, async () => { + try { + const result = await client.header.base64url( + stringToUint8Array("dGVzdA", "base64url") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64url-array`, async () => { + try { + const result = await client.header.base64urlArray([ + stringToUint8Array("dGVzdA", "base64url"), + stringToUint8Array("dGVzdA", "base64url") + ]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); +}); diff --git a/packages/typespec-ts/test/modularIntegration/encodeDatetime.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeDatetime.spec.ts new file mode 100644 index 0000000000..4e1872024e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/encodeDatetime.spec.ts @@ -0,0 +1,182 @@ +import { assert } from "chai"; +import { DatetimeClient } from "./generated/encode/datetime/src/index"; +describe("EncodeDatetimeClient Rest Client", () => { + let client: DatetimeClient; + + beforeEach(() => { + client = new DatetimeClient({ + allowInsecureConnection: true, + retryOptions: { + maxRetries: 0 + } + }); + }); + + describe("query", () => { + it(`should get default datetime`, async () => { + try { + const result = await client.query.default( + new Date("2022-08-26T18:38:00.000Z") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc3339`, async () => { + try { + const result = await client.query.rfc3339( + new Date("2022-08-26T18:38:00.000Z") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc7231`, async () => { + try { + const result = await client.query.rfc7231( + new Date("Fri, 26 Aug 2022 14:38:00 GMT") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp`, async () => { + try { + const result = await client.query.unixTimestamp(new Date(1686566864)); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp-array`, async () => { + try { + const result = await client.query.unixTimestampArray([ + new Date(1686566864), + new Date(1686734256) + ]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("property", () => { + it(`should get default datetime`, async () => { + try { + const result = await client.property.default( + new Date("2022-08-26T18:38:00.000Z") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc3339`, async () => { + try { + const result = await client.property.rfc3339( + new Date("2022-08-26T18:38:00.000Z") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc7231`, async () => { + try { + const result = await client.property.rfc7231( + new Date("Fri, 26 Aug 2022 14:38:00 GMT") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp`, async () => { + try { + const result = await client.property.unixTimestamp(new Date(1686566864)); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp-array`, async () => { + try { + const result = await client.property.unixTimestampArray([ + new Date(1686566864), + new Date(1686734256) + ]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("header", () => { + it(`should get default datetime`, async () => { + try { + const result = await client.header.default( + new Date("2022-08-26T18:38:00.000Z") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc3339`, async () => { + try { + const result = await client.header.rfc3339( + new Date("2022-08-26T18:38:00.000Z") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc7231`, async () => { + try { + const result = await client.header.rfc7231( + new Date("Fri, 26 Aug 2022 14:38:00 GMT") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp`, async () => { + try { + const result = await client.header.unixTimestamp(new Date(1686566864)); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp-array`, async () => { + try { + const result = await client.header.unixTimestampArray([ + new Date(1686566864), + new Date(1686734256) + ]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); +}); diff --git a/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts new file mode 100644 index 0000000000..00ad899377 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts @@ -0,0 +1,158 @@ +import { assert } from "chai"; +import { DurationClient } from "./generated/encode/duration/src/index"; +describe("EncodeDatetimeClient Rest Client", () => { + let client: DurationClient; + + beforeEach(() => { + client = new DurationClient({ + allowInsecureConnection: true, + retryOptions: { + maxRetries: 0 + } + }); + }); + + describe("query", () => { + it(`should get default duration`, async () => { + try { + const result = await client.query.default("P40D"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get iso8601 duration`, async () => { + try { + const result = await client.query.iso8601("P40D"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get float seconds`, async () => { + try { + const result = await client.query.floatSeconds("35.621"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds`, async () => { + try { + const result = await client.query.int32Seconds("36"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds array`, async () => { + try { + const result = await client.query.int32SecondsArray(["36", "47"]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("property", () => { + it(`should get default duration`, async () => { + try { + const result = await client.property.default("P40D"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get iso8601 duration`, async () => { + try { + const result = await client.property.iso8601("P40D"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get float seconds`, async () => { + try { + const result = await client.property.floatSeconds("35.621"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds`, async () => { + try { + const result = await client.property.int32Seconds("36"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds array`, async () => { + try { + const result = await client.property.floatSecondsArray([ + "35.621", + "46.781" + ]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("header", () => { + it(`should get default duration`, async () => { + try { + const result = await client.header.default("P40D"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get iso8601 duration`, async () => { + try { + const result = await client.header.iso8601("P40D"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get float seconds`, async () => { + try { + const result = await client.header.floatSeconds("35.621"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds`, async () => { + try { + const result = await client.header.int32Seconds("36"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds array`, async () => { + try { + const result = await client.header.iso8601Array(["P40D", "P50D"]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); +}); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/BytesClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/BytesClient.ts new file mode 100644 index 0000000000..dd3ad1c0dd --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/BytesClient.ts @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultBytesProperty, + Base64BytesProperty, + Base64urlBytesProperty, + Base64urlArrayBytesProperty, +} from "./models/models.js"; +import { + QueryDefaultOptions, + QueryBase64Options, + QueryBase64urlOptions, + QueryBase64urlArrayOptions, + PropertyDefaultOptions, + PropertyBase64Options, + PropertyBase64urlOptions, + PropertyBase64urlArrayOptions, + HeaderDefaultOptions, + HeaderBase64Options, + HeaderBase64urlOptions, + HeaderBase64urlArrayOptions, +} from "./models/options.js"; +import { + createBytes, + BytesClientOptions, + BytesContext, + headerDefault, + headerBase64, + headerBase64url, + headerBase64urlArray, + propertyDefault, + propertyBase64, + propertyBase64url, + propertyBase64urlArray, + queryDefault, + queryBase64, + queryBase64url, + queryBase64urlArray, +} from "./api/index.js"; + +export { BytesClientOptions } from "./api/BytesContext.js"; + +export class BytesClient { + private _client: BytesContext; + + /** Test for encode decorator on bytes. */ + constructor(options: BytesClientOptions = {}) { + this._client = createBytes(options); + } + + query = { + default: ( + value: Uint8Array, + options?: QueryDefaultOptions + ): Promise => { + return queryDefault(this._client, value, options); + }, + base64: ( + value: Uint8Array, + options?: QueryBase64Options + ): Promise => { + return queryBase64(this._client, value, options); + }, + base64url: ( + value: Uint8Array, + options?: QueryBase64urlOptions + ): Promise => { + return queryBase64url(this._client, value, options); + }, + base64urlArray: ( + value: Uint8Array[], + options?: QueryBase64urlArrayOptions + ): Promise => { + return queryBase64urlArray(this._client, value, options); + }, + }; + property = { + default: ( + value: Uint8Array, + options?: PropertyDefaultOptions + ): Promise => { + return propertyDefault(this._client, value, options); + }, + base64: ( + value: Uint8Array, + options?: PropertyBase64Options + ): Promise => { + return propertyBase64(this._client, value, options); + }, + base64url: ( + value: Uint8Array, + options?: PropertyBase64urlOptions + ): Promise => { + return propertyBase64url(this._client, value, options); + }, + base64urlArray: ( + value: Uint8Array[], + options?: PropertyBase64urlArrayOptions + ): Promise => { + return propertyBase64urlArray(this._client, value, options); + }, + }; + header = { + default: ( + value: Uint8Array, + options?: HeaderDefaultOptions + ): Promise => { + return headerDefault(this._client, value, options); + }, + base64: ( + value: Uint8Array, + options?: HeaderBase64Options + ): Promise => { + return headerBase64(this._client, value, options); + }, + base64url: ( + value: Uint8Array, + options?: HeaderBase64urlOptions + ): Promise => { + return headerBase64url(this._client, value, options); + }, + base64urlArray: ( + value: Uint8Array[], + options?: HeaderBase64urlArrayOptions + ): Promise => { + return headerBase64urlArray(this._client, value, options); + }, + }; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/BytesContext.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/BytesContext.ts new file mode 100644 index 0000000000..d05b414bfe --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/BytesContext.ts @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { ClientOptions } from "@azure-rest/core-client"; +import { BytesContext } from "../rest/index.js"; +import getClient from "../rest/index.js"; + +export interface BytesClientOptions extends ClientOptions {} + +export { BytesContext } from "../rest/index.js"; + +/** Test for encode decorator on bytes. */ +export function createBytes(options: BytesClientOptions = {}): BytesContext { + const clientContext = getClient(options); + return clientContext; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts new file mode 100644 index 0000000000..b117843ac8 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + BytesContext as Client, + HeaderBase64204Response, + HeaderBase64url204Response, + HeaderBase64urlArray204Response, + HeaderDefault204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + HeaderDefaultOptions, + HeaderBase64Options, + HeaderBase64urlOptions, + HeaderBase64urlArrayOptions, +} from "../models/options.js"; + +export function _headerDefaultSend( + context: Client, + value: Uint8Array, + options: HeaderDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/header/default") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: value }, + }); +} + +export async function _headerDefaultDeserialize( + result: HeaderDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerDefault( + context: Client, + value: Uint8Array, + options: HeaderDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _headerDefaultSend(context, value, options); + return _headerDefaultDeserialize(result); +} + +export function _headerBase64Send( + context: Client, + value: Uint8Array, + options: HeaderBase64Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/header/base64") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: value }, + }); +} + +export async function _headerBase64Deserialize( + result: HeaderBase64204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerBase64( + context: Client, + value: Uint8Array, + options: HeaderBase64Options = { requestOptions: {} } +): Promise { + const result = await _headerBase64Send(context, value, options); + return _headerBase64Deserialize(result); +} + +export function _headerBase64urlSend( + context: Client, + value: Uint8Array, + options: HeaderBase64urlOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/header/base64url") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: value }, + }); +} + +export async function _headerBase64urlDeserialize( + result: HeaderBase64url204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerBase64url( + context: Client, + value: Uint8Array, + options: HeaderBase64urlOptions = { requestOptions: {} } +): Promise { + const result = await _headerBase64urlSend(context, value, options); + return _headerBase64urlDeserialize(result); +} + +export function _headerBase64urlArraySend( + context: Client, + value: Uint8Array[], + options: HeaderBase64urlArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/header/base64url-array") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: buildCsvCollection(value) }, + }); +} + +export async function _headerBase64urlArrayDeserialize( + result: HeaderBase64urlArray204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerBase64urlArray( + context: Client, + value: Uint8Array[], + options: HeaderBase64urlArrayOptions = { requestOptions: {} } +): Promise { + const result = await _headerBase64urlArraySend(context, value, options); + return _headerBase64urlArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/index.ts new file mode 100644 index 0000000000..5f7df54269 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/index.ts @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + createBytes, + BytesClientOptions, + BytesContext, +} from "./BytesContext.js"; +export { + headerDefault, + headerBase64, + headerBase64url, + headerBase64urlArray, +} from "./header.js"; +export { + propertyDefault, + propertyBase64, + propertyBase64url, + propertyBase64urlArray, +} from "./property.js"; +export { + queryDefault, + queryBase64, + queryBase64url, + queryBase64urlArray, +} from "./query.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts new file mode 100644 index 0000000000..183258afce --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultBytesProperty, + Base64BytesProperty, + Base64urlBytesProperty, + Base64urlArrayBytesProperty, +} from "../models/models.js"; +import { + BytesContext as Client, + PropertyBase64200Response, + PropertyBase64url200Response, + PropertyBase64urlArray200Response, + PropertyDefault200Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { stringToUint8Array } from "@azure/core-util"; +import { + PropertyDefaultOptions, + PropertyBase64Options, + PropertyBase64urlOptions, + PropertyBase64urlArrayOptions, +} from "../models/options.js"; + +export function _propertyDefaultSend( + context: Client, + value: Uint8Array, + options: PropertyDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/property/default") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyDefaultDeserialize( + result: PropertyDefault200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: + typeof result.body["value"] === "string" + ? stringToUint8Array(result.body["value"], "base64") + : result.body["value"], + }; +} + +export async function propertyDefault( + context: Client, + value: Uint8Array, + options: PropertyDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _propertyDefaultSend(context, value, options); + return _propertyDefaultDeserialize(result); +} + +export function _propertyBase64Send( + context: Client, + value: Uint8Array, + options: PropertyBase64Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/property/base64") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyBase64Deserialize( + result: PropertyBase64200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: + typeof result.body["value"] === "string" + ? stringToUint8Array(result.body["value"], "base64") + : result.body["value"], + }; +} + +export async function propertyBase64( + context: Client, + value: Uint8Array, + options: PropertyBase64Options = { requestOptions: {} } +): Promise { + const result = await _propertyBase64Send(context, value, options); + return _propertyBase64Deserialize(result); +} + +export function _propertyBase64urlSend( + context: Client, + value: Uint8Array, + options: PropertyBase64urlOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/property/base64url") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyBase64urlDeserialize( + result: PropertyBase64url200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: + typeof result.body["value"] === "string" + ? stringToUint8Array(result.body["value"], "base64") + : result.body["value"], + }; +} + +export async function propertyBase64url( + context: Client, + value: Uint8Array, + options: PropertyBase64urlOptions = { requestOptions: {} } +): Promise { + const result = await _propertyBase64urlSend(context, value, options); + return _propertyBase64urlDeserialize(result); +} + +export function _propertyBase64urlArraySend( + context: Client, + value: Uint8Array[], + options: PropertyBase64urlArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/property/base64url-array") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyBase64urlArrayDeserialize( + result: PropertyBase64urlArray200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyBase64urlArray( + context: Client, + value: Uint8Array[], + options: PropertyBase64urlArrayOptions = { requestOptions: {} } +): Promise { + const result = await _propertyBase64urlArraySend(context, value, options); + return _propertyBase64urlArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts new file mode 100644 index 0000000000..61a00d4c94 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + BytesContext as Client, + QueryBase64204Response, + QueryBase64url204Response, + QueryBase64urlArray204Response, + QueryDefault204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + QueryDefaultOptions, + QueryBase64Options, + QueryBase64urlOptions, + QueryBase64urlArrayOptions, +} from "../models/options.js"; + +export function _queryDefaultSend( + context: Client, + value: Uint8Array, + options: QueryDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/query/default") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value }, + }); +} + +export async function _queryDefaultDeserialize( + result: QueryDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryDefault( + context: Client, + value: Uint8Array, + options: QueryDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _queryDefaultSend(context, value, options); + return _queryDefaultDeserialize(result); +} + +export function _queryBase64Send( + context: Client, + value: Uint8Array, + options: QueryBase64Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/query/base64") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value }, + }); +} + +export async function _queryBase64Deserialize( + result: QueryBase64204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryBase64( + context: Client, + value: Uint8Array, + options: QueryBase64Options = { requestOptions: {} } +): Promise { + const result = await _queryBase64Send(context, value, options); + return _queryBase64Deserialize(result); +} + +export function _queryBase64urlSend( + context: Client, + value: Uint8Array, + options: QueryBase64urlOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/query/base64url") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value }, + }); +} + +export async function _queryBase64urlDeserialize( + result: QueryBase64url204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryBase64url( + context: Client, + value: Uint8Array, + options: QueryBase64urlOptions = { requestOptions: {} } +): Promise { + const result = await _queryBase64urlSend(context, value, options); + return _queryBase64urlDeserialize(result); +} + +export function _queryBase64urlArraySend( + context: Client, + value: Uint8Array[], + options: QueryBase64urlArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/query/base64url-array") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value }, + }); +} + +export async function _queryBase64urlArrayDeserialize( + result: QueryBase64urlArray204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryBase64urlArray( + context: Client, + value: Uint8Array[], + options: QueryBase64urlArrayOptions = { requestOptions: {} } +): Promise { + const result = await _queryBase64urlArraySend(context, value, options); + return _queryBase64urlArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/index.ts new file mode 100644 index 0000000000..e2daf3d2e1 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/index.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { BytesClient, BytesClientOptions } from "./BytesClient.js"; +export { + DefaultBytesProperty, + Base64BytesProperty, + Base64urlBytesProperty, + Base64urlArrayBytesProperty, + QueryDefaultOptions, + QueryBase64Options, + QueryBase64urlOptions, + QueryBase64urlArrayOptions, + PropertyDefaultOptions, + PropertyBase64Options, + PropertyBase64urlOptions, + PropertyBase64urlArrayOptions, + HeaderDefaultOptions, + HeaderBase64Options, + HeaderBase64urlOptions, + HeaderBase64urlArrayOptions, +} from "./models/index.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/logger.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/logger.ts new file mode 100644 index 0000000000..370150902d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/logger.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("encode-bytes"); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/index.ts new file mode 100644 index 0000000000..7dac823549 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/index.ts @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + DefaultBytesProperty, + Base64BytesProperty, + Base64urlBytesProperty, + Base64urlArrayBytesProperty, +} from "./models.js"; +export { + QueryDefaultOptions, + QueryBase64Options, + QueryBase64urlOptions, + QueryBase64urlArrayOptions, + PropertyDefaultOptions, + PropertyBase64Options, + PropertyBase64urlOptions, + PropertyBase64urlArrayOptions, + HeaderDefaultOptions, + HeaderBase64Options, + HeaderBase64urlOptions, + HeaderBase64urlArrayOptions, +} from "./options.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/models.ts new file mode 100644 index 0000000000..a5c4bdd415 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/models.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultBytesProperty { + value: Uint8Array; +} + +export interface Base64BytesProperty { + value: Uint8Array; +} + +export interface Base64urlBytesProperty { + value: Uint8Array; +} + +export interface Base64urlArrayBytesProperty { + value: Uint8Array[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/options.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/options.ts new file mode 100644 index 0000000000..e57487c598 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/options.ts @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { OperationOptions } from "@azure-rest/core-client"; + +export interface QueryDefaultOptions extends OperationOptions {} + +export interface QueryBase64Options extends OperationOptions {} + +export interface QueryBase64urlOptions extends OperationOptions {} + +export interface QueryBase64urlArrayOptions extends OperationOptions {} + +export interface PropertyDefaultOptions extends OperationOptions {} + +export interface PropertyBase64Options extends OperationOptions {} + +export interface PropertyBase64urlOptions extends OperationOptions {} + +export interface PropertyBase64urlArrayOptions extends OperationOptions {} + +export interface HeaderDefaultOptions extends OperationOptions {} + +export interface HeaderBase64Options extends OperationOptions {} + +export interface HeaderBase64urlOptions extends OperationOptions {} + +export interface HeaderBase64urlArrayOptions extends OperationOptions {} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/bytesClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/bytesClient.ts new file mode 100644 index 0000000000..f8b0556248 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/bytesClient.ts @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "../logger.js"; +import { BytesContext } from "./clientDefinitions.js"; + +/** + * Initialize a new instance of `BytesContext` + * @param options - the parameter for all optional parameters + */ +export default function createClient( + options: ClientOptions = {} +): BytesContext { + const baseUrl = options.baseUrl ?? `http://localhost:3000`; + options.apiVersion = options.apiVersion ?? "1.0.0"; + const userAgentInfo = `azsdk-js-encode-bytes-rest/1.0.0-beta.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + }; + + const client = getClient(baseUrl, options) as BytesContext; + + return client; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/clientDefinitions.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/clientDefinitions.ts new file mode 100644 index 0000000000..8bad05bb6e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/clientDefinitions.ts @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + QueryDefaultParameters, + QueryBase64Parameters, + QueryBase64urlParameters, + QueryBase64urlArrayParameters, + PropertyDefaultParameters, + PropertyBase64Parameters, + PropertyBase64urlParameters, + PropertyBase64urlArrayParameters, + HeaderDefaultParameters, + HeaderBase64Parameters, + HeaderBase64urlParameters, + HeaderBase64urlArrayParameters, +} from "./parameters.js"; +import { + QueryDefault204Response, + QueryBase64204Response, + QueryBase64url204Response, + QueryBase64urlArray204Response, + PropertyDefault200Response, + PropertyBase64200Response, + PropertyBase64url200Response, + PropertyBase64urlArray200Response, + HeaderDefault204Response, + HeaderBase64204Response, + HeaderBase64url204Response, + HeaderBase64urlArray204Response, +} from "./responses.js"; +import { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface QueryDefault { + get( + options: QueryDefaultParameters + ): StreamableMethod; +} + +export interface QueryBase64 { + get(options: QueryBase64Parameters): StreamableMethod; +} + +export interface QueryBase64url { + get( + options: QueryBase64urlParameters + ): StreamableMethod; +} + +export interface QueryBase64urlArray { + get( + options: QueryBase64urlArrayParameters + ): StreamableMethod; +} + +export interface PropertyDefault { + post( + options: PropertyDefaultParameters + ): StreamableMethod; +} + +export interface PropertyBase64 { + post( + options: PropertyBase64Parameters + ): StreamableMethod; +} + +export interface PropertyBase64url { + post( + options: PropertyBase64urlParameters + ): StreamableMethod; +} + +export interface PropertyBase64urlArray { + post( + options: PropertyBase64urlArrayParameters + ): StreamableMethod; +} + +export interface HeaderDefault { + get( + options: HeaderDefaultParameters + ): StreamableMethod; +} + +export interface HeaderBase64 { + get( + options: HeaderBase64Parameters + ): StreamableMethod; +} + +export interface HeaderBase64url { + get( + options: HeaderBase64urlParameters + ): StreamableMethod; +} + +export interface HeaderBase64urlArray { + get( + options: HeaderBase64urlArrayParameters + ): StreamableMethod; +} + +export interface Routes { + /** Resource for '/encode/bytes/query/default' has methods for the following verbs: get */ + (path: "/encode/bytes/query/default"): QueryDefault; + /** Resource for '/encode/bytes/query/base64' has methods for the following verbs: get */ + (path: "/encode/bytes/query/base64"): QueryBase64; + /** Resource for '/encode/bytes/query/base64url' has methods for the following verbs: get */ + (path: "/encode/bytes/query/base64url"): QueryBase64url; + /** Resource for '/encode/bytes/query/base64url-array' has methods for the following verbs: get */ + (path: "/encode/bytes/query/base64url-array"): QueryBase64urlArray; + /** Resource for '/encode/bytes/property/default' has methods for the following verbs: post */ + (path: "/encode/bytes/property/default"): PropertyDefault; + /** Resource for '/encode/bytes/property/base64' has methods for the following verbs: post */ + (path: "/encode/bytes/property/base64"): PropertyBase64; + /** Resource for '/encode/bytes/property/base64url' has methods for the following verbs: post */ + (path: "/encode/bytes/property/base64url"): PropertyBase64url; + /** Resource for '/encode/bytes/property/base64url-array' has methods for the following verbs: post */ + (path: "/encode/bytes/property/base64url-array"): PropertyBase64urlArray; + /** Resource for '/encode/bytes/header/default' has methods for the following verbs: get */ + (path: "/encode/bytes/header/default"): HeaderDefault; + /** Resource for '/encode/bytes/header/base64' has methods for the following verbs: get */ + (path: "/encode/bytes/header/base64"): HeaderBase64; + /** Resource for '/encode/bytes/header/base64url' has methods for the following verbs: get */ + (path: "/encode/bytes/header/base64url"): HeaderBase64url; + /** Resource for '/encode/bytes/header/base64url-array' has methods for the following verbs: get */ + (path: "/encode/bytes/header/base64url-array"): HeaderBase64urlArray; +} + +export type BytesContext = Client & { + path: Routes; +}; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/index.ts new file mode 100644 index 0000000000..ae094eae02 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/index.ts @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import BytesClient from "./bytesClient.js"; + +export * from "./bytesClient.js"; +export * from "./parameters.js"; +export * from "./responses.js"; +export * from "./clientDefinitions.js"; +export * from "./models.js"; +export * from "./outputModels.js"; + +export default BytesClient; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/models.ts new file mode 100644 index 0000000000..e318f7928d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/models.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultBytesProperty { + value: string; +} + +export interface Base64BytesProperty { + value: string; +} + +export interface Base64urlBytesProperty { + value: string; +} + +export interface Base64urlArrayBytesProperty { + value: string[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/outputModels.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/outputModels.ts new file mode 100644 index 0000000000..66195f40c4 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/outputModels.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultBytesPropertyOutput { + value: string; +} + +export interface Base64BytesPropertyOutput { + value: string; +} + +export interface Base64urlBytesPropertyOutput { + value: string; +} + +export interface Base64urlArrayBytesPropertyOutput { + value: string[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/parameters.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/parameters.ts new file mode 100644 index 0000000000..629e71eff7 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/parameters.ts @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RawHttpHeadersInput } from "@azure/core-rest-pipeline"; +import { RequestParameters } from "@azure-rest/core-client"; +import { + DefaultBytesProperty, + Base64BytesProperty, + Base64urlBytesProperty, + Base64urlArrayBytesProperty, +} from "./models.js"; + +export interface QueryDefaultQueryParamProperties { + value: string; +} + +export interface QueryDefaultQueryParam { + queryParameters: QueryDefaultQueryParamProperties; +} + +export type QueryDefaultParameters = QueryDefaultQueryParam & RequestParameters; + +export interface QueryBase64QueryParamProperties { + value: string; +} + +export interface QueryBase64QueryParam { + queryParameters: QueryBase64QueryParamProperties; +} + +export type QueryBase64Parameters = QueryBase64QueryParam & RequestParameters; + +export interface QueryBase64urlQueryParamProperties { + value: string; +} + +export interface QueryBase64urlQueryParam { + queryParameters: QueryBase64urlQueryParamProperties; +} + +export type QueryBase64urlParameters = QueryBase64urlQueryParam & + RequestParameters; + +export interface QueryBase64urlArrayQueryParamProperties { + value: string[]; +} + +export interface QueryBase64urlArrayQueryParam { + queryParameters: QueryBase64urlArrayQueryParamProperties; +} + +export type QueryBase64urlArrayParameters = QueryBase64urlArrayQueryParam & + RequestParameters; + +export interface PropertyDefaultBodyParam { + body: DefaultBytesProperty; +} + +export type PropertyDefaultParameters = PropertyDefaultBodyParam & + RequestParameters; + +export interface PropertyBase64BodyParam { + body: Base64BytesProperty; +} + +export type PropertyBase64Parameters = PropertyBase64BodyParam & + RequestParameters; + +export interface PropertyBase64urlBodyParam { + body: Base64urlBytesProperty; +} + +export type PropertyBase64urlParameters = PropertyBase64urlBodyParam & + RequestParameters; + +export interface PropertyBase64urlArrayBodyParam { + body: Base64urlArrayBytesProperty; +} + +export type PropertyBase64urlArrayParameters = PropertyBase64urlArrayBodyParam & + RequestParameters; + +export interface HeaderDefaultHeaders { + value: string; +} + +export interface HeaderDefaultHeaderParam { + headers: RawHttpHeadersInput & HeaderDefaultHeaders; +} + +export type HeaderDefaultParameters = HeaderDefaultHeaderParam & + RequestParameters; + +export interface HeaderBase64Headers { + value: string; +} + +export interface HeaderBase64HeaderParam { + headers: RawHttpHeadersInput & HeaderBase64Headers; +} + +export type HeaderBase64Parameters = HeaderBase64HeaderParam & + RequestParameters; + +export interface HeaderBase64urlHeaders { + value: string; +} + +export interface HeaderBase64urlHeaderParam { + headers: RawHttpHeadersInput & HeaderBase64urlHeaders; +} + +export type HeaderBase64urlParameters = HeaderBase64urlHeaderParam & + RequestParameters; + +export interface HeaderBase64urlArrayHeaders { + /** This parameter needs to be formatted as csv collection, we provide buildCsvCollection from serializeHelper.ts to help */ + value: string; +} + +export interface HeaderBase64urlArrayHeaderParam { + headers: RawHttpHeadersInput & HeaderBase64urlArrayHeaders; +} + +export type HeaderBase64urlArrayParameters = HeaderBase64urlArrayHeaderParam & + RequestParameters; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/responses.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/responses.ts new file mode 100644 index 0000000000..302790a12f --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/responses.ts @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { HttpResponse } from "@azure-rest/core-client"; +import { + DefaultBytesPropertyOutput, + Base64BytesPropertyOutput, + Base64urlBytesPropertyOutput, + Base64urlArrayBytesPropertyOutput, +} from "./outputModels.js"; + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryBase64204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryBase64url204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryBase64urlArray204Response extends HttpResponse { + status: "204"; +} + +/** The request has succeeded. */ +export interface PropertyDefault200Response extends HttpResponse { + status: "200"; + body: DefaultBytesPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyBase64200Response extends HttpResponse { + status: "200"; + body: Base64BytesPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyBase64url200Response extends HttpResponse { + status: "200"; + body: Base64urlBytesPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyBase64urlArray200Response extends HttpResponse { + status: "200"; + body: Base64urlArrayBytesPropertyOutput; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderBase64204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderBase64url204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderBase64urlArray204Response extends HttpResponse { + status: "204"; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/serializeHelper.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/serializeHelper.ts new file mode 100644 index 0000000000..aeb95223cc --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/serializeHelper.ts @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function buildCsvCollection(items: string[] | number[]) { + return items.join(","); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/tspconfig.yaml b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/tspconfig.yaml new file mode 100644 index 0000000000..f43d04c270 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/tspconfig.yaml @@ -0,0 +1,14 @@ +emit: + - "@azure-tools/typespec-ts" +options: + "@azure-tools/typespec-ts": + "emitter-output-dir": "{project-root}" + generateMetadata: false + generateTest: false + addCredentials: false + azureSdkForJs: false + isTypeSpecTest: true + enableOperationGroup: true + isModularLibrary: true + packageDetails: + name: "@msinternal/encode-bytes" diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/DatetimeClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/DatetimeClient.ts new file mode 100644 index 0000000000..ff1c463643 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/DatetimeClient.ts @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultDatetimeProperty, + Rfc3339DatetimeProperty, + Rfc7231DatetimeProperty, + UnixTimestampDatetimeProperty, + UnixTimestampArrayDatetimeProperty, +} from "./models/models.js"; +import { + QueryDefaultOptions, + QueryRfc3339Options, + QueryRfc7231Options, + QueryUnixTimestampOptions, + QueryUnixTimestampArrayOptions, + PropertyDefaultOptions, + PropertyRfc3339Options, + PropertyRfc7231Options, + PropertyUnixTimestampOptions, + PropertyUnixTimestampArrayOptions, + HeaderDefaultOptions, + HeaderRfc3339Options, + HeaderRfc7231Options, + HeaderUnixTimestampOptions, + HeaderUnixTimestampArrayOptions, +} from "./models/options.js"; +import { + createDatetime, + DatetimeClientOptions, + DatetimeContext, + headerDefault, + headerRfc3339, + headerRfc7231, + headerUnixTimestamp, + headerUnixTimestampArray, + propertyDefault, + propertyRfc3339, + propertyRfc7231, + propertyUnixTimestamp, + propertyUnixTimestampArray, + queryDefault, + queryRfc3339, + queryRfc7231, + queryUnixTimestamp, + queryUnixTimestampArray, +} from "./api/index.js"; + +export { DatetimeClientOptions } from "./api/DatetimeContext.js"; + +export class DatetimeClient { + private _client: DatetimeContext; + + /** Test for encode decorator on datetime. */ + constructor(options: DatetimeClientOptions = {}) { + this._client = createDatetime(options); + } + + query = { + default: (value: Date, options?: QueryDefaultOptions): Promise => { + return queryDefault(this._client, value, options); + }, + rfc3339: (value: Date, options?: QueryRfc3339Options): Promise => { + return queryRfc3339(this._client, value, options); + }, + rfc7231: (value: Date, options?: QueryRfc7231Options): Promise => { + return queryRfc7231(this._client, value, options); + }, + unixTimestamp: ( + value: Date, + options?: QueryUnixTimestampOptions + ): Promise => { + return queryUnixTimestamp(this._client, value, options); + }, + unixTimestampArray: ( + value: Date[], + options?: QueryUnixTimestampArrayOptions + ): Promise => { + return queryUnixTimestampArray(this._client, value, options); + }, + }; + property = { + default: ( + value: Date, + options?: PropertyDefaultOptions + ): Promise => { + return propertyDefault(this._client, value, options); + }, + rfc3339: ( + value: Date, + options?: PropertyRfc3339Options + ): Promise => { + return propertyRfc3339(this._client, value, options); + }, + rfc7231: ( + value: Date, + options?: PropertyRfc7231Options + ): Promise => { + return propertyRfc7231(this._client, value, options); + }, + unixTimestamp: ( + value: Date, + options?: PropertyUnixTimestampOptions + ): Promise => { + return propertyUnixTimestamp(this._client, value, options); + }, + unixTimestampArray: ( + value: Date[], + options?: PropertyUnixTimestampArrayOptions + ): Promise => { + return propertyUnixTimestampArray(this._client, value, options); + }, + }; + header = { + default: (value: Date, options?: HeaderDefaultOptions): Promise => { + return headerDefault(this._client, value, options); + }, + rfc3339: (value: Date, options?: HeaderRfc3339Options): Promise => { + return headerRfc3339(this._client, value, options); + }, + rfc7231: (value: Date, options?: HeaderRfc7231Options): Promise => { + return headerRfc7231(this._client, value, options); + }, + unixTimestamp: ( + value: Date, + options?: HeaderUnixTimestampOptions + ): Promise => { + return headerUnixTimestamp(this._client, value, options); + }, + unixTimestampArray: ( + value: Date[], + options?: HeaderUnixTimestampArrayOptions + ): Promise => { + return headerUnixTimestampArray(this._client, value, options); + }, + }; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/DatetimeContext.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/DatetimeContext.ts new file mode 100644 index 0000000000..6efab496bf --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/DatetimeContext.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { ClientOptions } from "@azure-rest/core-client"; +import { DatetimeContext } from "../rest/index.js"; +import getClient from "../rest/index.js"; + +export interface DatetimeClientOptions extends ClientOptions {} + +export { DatetimeContext } from "../rest/index.js"; + +/** Test for encode decorator on datetime. */ +export function createDatetime( + options: DatetimeClientOptions = {} +): DatetimeContext { + const clientContext = getClient(options); + return clientContext; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts new file mode 100644 index 0000000000..bbca3d9c64 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DatetimeContext as Client, + HeaderDefault204Response, + HeaderRfc3339204Response, + HeaderRfc7231204Response, + HeaderUnixTimestamp204Response, + HeaderUnixTimestampArray204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + HeaderDefaultOptions, + HeaderRfc3339Options, + HeaderRfc7231Options, + HeaderUnixTimestampOptions, + HeaderUnixTimestampArrayOptions, +} from "../models/options.js"; + +export function _headerDefaultSend( + context: Client, + value: Date, + options: HeaderDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/header/default") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: value }, + }); +} + +export async function _headerDefaultDeserialize( + result: HeaderDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerDefault( + context: Client, + value: Date, + options: HeaderDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _headerDefaultSend(context, value, options); + return _headerDefaultDeserialize(result); +} + +export function _headerRfc3339Send( + context: Client, + value: Date, + options: HeaderRfc3339Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/header/rfc3339") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: value }, + }); +} + +export async function _headerRfc3339Deserialize( + result: HeaderRfc3339204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerRfc3339( + context: Client, + value: Date, + options: HeaderRfc3339Options = { requestOptions: {} } +): Promise { + const result = await _headerRfc3339Send(context, value, options); + return _headerRfc3339Deserialize(result); +} + +export function _headerRfc7231Send( + context: Client, + value: Date, + options: HeaderRfc7231Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/header/rfc7231") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: value }, + }); +} + +export async function _headerRfc7231Deserialize( + result: HeaderRfc7231204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerRfc7231( + context: Client, + value: Date, + options: HeaderRfc7231Options = { requestOptions: {} } +): Promise { + const result = await _headerRfc7231Send(context, value, options); + return _headerRfc7231Deserialize(result); +} + +export function _headerUnixTimestampSend( + context: Client, + value: Date, + options: HeaderUnixTimestampOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/header/unix-timestamp") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: value }, + }); +} + +export async function _headerUnixTimestampDeserialize( + result: HeaderUnixTimestamp204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerUnixTimestamp( + context: Client, + value: Date, + options: HeaderUnixTimestampOptions = { requestOptions: {} } +): Promise { + const result = await _headerUnixTimestampSend(context, value, options); + return _headerUnixTimestampDeserialize(result); +} + +export function _headerUnixTimestampArraySend( + context: Client, + value: Date[], + options: HeaderUnixTimestampArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/header/unix-timestamp-array") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: buildCsvCollection(value) }, + }); +} + +export async function _headerUnixTimestampArrayDeserialize( + result: HeaderUnixTimestampArray204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerUnixTimestampArray( + context: Client, + value: Date[], + options: HeaderUnixTimestampArrayOptions = { requestOptions: {} } +): Promise { + const result = await _headerUnixTimestampArraySend(context, value, options); + return _headerUnixTimestampArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/index.ts new file mode 100644 index 0000000000..ca55c56612 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/index.ts @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + createDatetime, + DatetimeClientOptions, + DatetimeContext, +} from "./DatetimeContext.js"; +export { + headerDefault, + headerRfc3339, + headerRfc7231, + headerUnixTimestamp, + headerUnixTimestampArray, +} from "./header.js"; +export { + propertyDefault, + propertyRfc3339, + propertyRfc7231, + propertyUnixTimestamp, + propertyUnixTimestampArray, +} from "./property.js"; +export { + queryDefault, + queryRfc3339, + queryRfc7231, + queryUnixTimestamp, + queryUnixTimestampArray, +} from "./query.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts new file mode 100644 index 0000000000..d69ec85dae --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultDatetimeProperty, + Rfc3339DatetimeProperty, + Rfc7231DatetimeProperty, + UnixTimestampDatetimeProperty, + UnixTimestampArrayDatetimeProperty, +} from "../models/models.js"; +import { + DatetimeContext as Client, + PropertyDefault200Response, + PropertyRfc3339200Response, + PropertyRfc7231200Response, + PropertyUnixTimestamp200Response, + PropertyUnixTimestampArray200Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + PropertyDefaultOptions, + PropertyRfc3339Options, + PropertyRfc7231Options, + PropertyUnixTimestampOptions, + PropertyUnixTimestampArrayOptions, +} from "../models/options.js"; + +export function _propertyDefaultSend( + context: Client, + value: Date, + options: PropertyDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/property/default") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyDefaultDeserialize( + result: PropertyDefault200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: new Date(result.body["value"]), + }; +} + +export async function propertyDefault( + context: Client, + value: Date, + options: PropertyDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _propertyDefaultSend(context, value, options); + return _propertyDefaultDeserialize(result); +} + +export function _propertyRfc3339Send( + context: Client, + value: Date, + options: PropertyRfc3339Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/property/rfc3339") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyRfc3339Deserialize( + result: PropertyRfc3339200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: new Date(result.body["value"]), + }; +} + +export async function propertyRfc3339( + context: Client, + value: Date, + options: PropertyRfc3339Options = { requestOptions: {} } +): Promise { + const result = await _propertyRfc3339Send(context, value, options); + return _propertyRfc3339Deserialize(result); +} + +export function _propertyRfc7231Send( + context: Client, + value: Date, + options: PropertyRfc7231Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/property/rfc7231") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyRfc7231Deserialize( + result: PropertyRfc7231200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: new Date(result.body["value"]), + }; +} + +export async function propertyRfc7231( + context: Client, + value: Date, + options: PropertyRfc7231Options = { requestOptions: {} } +): Promise { + const result = await _propertyRfc7231Send(context, value, options); + return _propertyRfc7231Deserialize(result); +} + +export function _propertyUnixTimestampSend( + context: Client, + value: Date, + options: PropertyUnixTimestampOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/property/unix-timestamp") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyUnixTimestampDeserialize( + result: PropertyUnixTimestamp200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: new Date(result.body["value"]), + }; +} + +export async function propertyUnixTimestamp( + context: Client, + value: Date, + options: PropertyUnixTimestampOptions = { requestOptions: {} } +): Promise { + const result = await _propertyUnixTimestampSend(context, value, options); + return _propertyUnixTimestampDeserialize(result); +} + +export function _propertyUnixTimestampArraySend( + context: Client, + value: Date[], + options: PropertyUnixTimestampArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/property/unix-timestamp-array") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyUnixTimestampArrayDeserialize( + result: PropertyUnixTimestampArray200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyUnixTimestampArray( + context: Client, + value: Date[], + options: PropertyUnixTimestampArrayOptions = { requestOptions: {} } +): Promise { + const result = await _propertyUnixTimestampArraySend(context, value, options); + return _propertyUnixTimestampArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts new file mode 100644 index 0000000000..99941c34c8 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DatetimeContext as Client, + QueryDefault204Response, + QueryRfc3339204Response, + QueryRfc7231204Response, + QueryUnixTimestamp204Response, + QueryUnixTimestampArray204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + QueryDefaultOptions, + QueryRfc3339Options, + QueryRfc7231Options, + QueryUnixTimestampOptions, + QueryUnixTimestampArrayOptions, +} from "../models/options.js"; + +export function _queryDefaultSend( + context: Client, + value: Date, + options: QueryDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/query/default") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value }, + }); +} + +export async function _queryDefaultDeserialize( + result: QueryDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryDefault( + context: Client, + value: Date, + options: QueryDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _queryDefaultSend(context, value, options); + return _queryDefaultDeserialize(result); +} + +export function _queryRfc3339Send( + context: Client, + value: Date, + options: QueryRfc3339Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/query/rfc3339") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value }, + }); +} + +export async function _queryRfc3339Deserialize( + result: QueryRfc3339204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryRfc3339( + context: Client, + value: Date, + options: QueryRfc3339Options = { requestOptions: {} } +): Promise { + const result = await _queryRfc3339Send(context, value, options); + return _queryRfc3339Deserialize(result); +} + +export function _queryRfc7231Send( + context: Client, + value: Date, + options: QueryRfc7231Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/query/rfc7231") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value }, + }); +} + +export async function _queryRfc7231Deserialize( + result: QueryRfc7231204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryRfc7231( + context: Client, + value: Date, + options: QueryRfc7231Options = { requestOptions: {} } +): Promise { + const result = await _queryRfc7231Send(context, value, options); + return _queryRfc7231Deserialize(result); +} + +export function _queryUnixTimestampSend( + context: Client, + value: Date, + options: QueryUnixTimestampOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/query/unix-timestamp") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value }, + }); +} + +export async function _queryUnixTimestampDeserialize( + result: QueryUnixTimestamp204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryUnixTimestamp( + context: Client, + value: Date, + options: QueryUnixTimestampOptions = { requestOptions: {} } +): Promise { + const result = await _queryUnixTimestampSend(context, value, options); + return _queryUnixTimestampDeserialize(result); +} + +export function _queryUnixTimestampArraySend( + context: Client, + value: Date[], + options: QueryUnixTimestampArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/query/unix-timestamp-array") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value }, + }); +} + +export async function _queryUnixTimestampArrayDeserialize( + result: QueryUnixTimestampArray204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryUnixTimestampArray( + context: Client, + value: Date[], + options: QueryUnixTimestampArrayOptions = { requestOptions: {} } +): Promise { + const result = await _queryUnixTimestampArraySend(context, value, options); + return _queryUnixTimestampArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/index.ts new file mode 100644 index 0000000000..db7b5809d5 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/index.ts @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { DatetimeClient, DatetimeClientOptions } from "./DatetimeClient.js"; +export { + DefaultDatetimeProperty, + Rfc3339DatetimeProperty, + Rfc7231DatetimeProperty, + UnixTimestampDatetimeProperty, + UnixTimestampArrayDatetimeProperty, + QueryDefaultOptions, + QueryRfc3339Options, + QueryRfc7231Options, + QueryUnixTimestampOptions, + QueryUnixTimestampArrayOptions, + PropertyDefaultOptions, + PropertyRfc3339Options, + PropertyRfc7231Options, + PropertyUnixTimestampOptions, + PropertyUnixTimestampArrayOptions, + HeaderDefaultOptions, + HeaderRfc3339Options, + HeaderRfc7231Options, + HeaderUnixTimestampOptions, + HeaderUnixTimestampArrayOptions, +} from "./models/index.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/logger.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/logger.ts new file mode 100644 index 0000000000..f3e4c0f4f4 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/logger.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("encode-datatime"); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/index.ts new file mode 100644 index 0000000000..a28faa2ffb --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/index.ts @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + DefaultDatetimeProperty, + Rfc3339DatetimeProperty, + Rfc7231DatetimeProperty, + UnixTimestampDatetimeProperty, + UnixTimestampArrayDatetimeProperty, +} from "./models.js"; +export { + QueryDefaultOptions, + QueryRfc3339Options, + QueryRfc7231Options, + QueryUnixTimestampOptions, + QueryUnixTimestampArrayOptions, + PropertyDefaultOptions, + PropertyRfc3339Options, + PropertyRfc7231Options, + PropertyUnixTimestampOptions, + PropertyUnixTimestampArrayOptions, + HeaderDefaultOptions, + HeaderRfc3339Options, + HeaderRfc7231Options, + HeaderUnixTimestampOptions, + HeaderUnixTimestampArrayOptions, +} from "./options.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/models.ts new file mode 100644 index 0000000000..11e83eab15 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/models.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDatetimeProperty { + value: Date; +} + +export interface Rfc3339DatetimeProperty { + value: Date; +} + +export interface Rfc7231DatetimeProperty { + value: Date; +} + +export interface UnixTimestampDatetimeProperty { + value: Date; +} + +export interface UnixTimestampArrayDatetimeProperty { + value: Date[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/options.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/options.ts new file mode 100644 index 0000000000..264e8163e3 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/options.ts @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { OperationOptions } from "@azure-rest/core-client"; + +export interface QueryDefaultOptions extends OperationOptions {} + +export interface QueryRfc3339Options extends OperationOptions {} + +export interface QueryRfc7231Options extends OperationOptions {} + +export interface QueryUnixTimestampOptions extends OperationOptions {} + +export interface QueryUnixTimestampArrayOptions extends OperationOptions {} + +export interface PropertyDefaultOptions extends OperationOptions {} + +export interface PropertyRfc3339Options extends OperationOptions {} + +export interface PropertyRfc7231Options extends OperationOptions {} + +export interface PropertyUnixTimestampOptions extends OperationOptions {} + +export interface PropertyUnixTimestampArrayOptions extends OperationOptions {} + +export interface HeaderDefaultOptions extends OperationOptions {} + +export interface HeaderRfc3339Options extends OperationOptions {} + +export interface HeaderRfc7231Options extends OperationOptions {} + +export interface HeaderUnixTimestampOptions extends OperationOptions {} + +export interface HeaderUnixTimestampArrayOptions extends OperationOptions {} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/clientDefinitions.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/clientDefinitions.ts new file mode 100644 index 0000000000..0cbfb4245b --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/clientDefinitions.ts @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + QueryDefaultParameters, + QueryRfc3339Parameters, + QueryRfc7231Parameters, + QueryUnixTimestampParameters, + QueryUnixTimestampArrayParameters, + PropertyDefaultParameters, + PropertyRfc3339Parameters, + PropertyRfc7231Parameters, + PropertyUnixTimestampParameters, + PropertyUnixTimestampArrayParameters, + HeaderDefaultParameters, + HeaderRfc3339Parameters, + HeaderRfc7231Parameters, + HeaderUnixTimestampParameters, + HeaderUnixTimestampArrayParameters, +} from "./parameters.js"; +import { + QueryDefault204Response, + QueryRfc3339204Response, + QueryRfc7231204Response, + QueryUnixTimestamp204Response, + QueryUnixTimestampArray204Response, + PropertyDefault200Response, + PropertyRfc3339200Response, + PropertyRfc7231200Response, + PropertyUnixTimestamp200Response, + PropertyUnixTimestampArray200Response, + HeaderDefault204Response, + HeaderRfc3339204Response, + HeaderRfc7231204Response, + HeaderUnixTimestamp204Response, + HeaderUnixTimestampArray204Response, +} from "./responses.js"; +import { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface QueryDefault { + get( + options: QueryDefaultParameters + ): StreamableMethod; +} + +export interface QueryRfc3339 { + get( + options: QueryRfc3339Parameters + ): StreamableMethod; +} + +export interface QueryRfc7231 { + get( + options: QueryRfc7231Parameters + ): StreamableMethod; +} + +export interface QueryUnixTimestamp { + get( + options: QueryUnixTimestampParameters + ): StreamableMethod; +} + +export interface QueryUnixTimestampArray { + get( + options: QueryUnixTimestampArrayParameters + ): StreamableMethod; +} + +export interface PropertyDefault { + post( + options: PropertyDefaultParameters + ): StreamableMethod; +} + +export interface PropertyRfc3339 { + post( + options: PropertyRfc3339Parameters + ): StreamableMethod; +} + +export interface PropertyRfc7231 { + post( + options: PropertyRfc7231Parameters + ): StreamableMethod; +} + +export interface PropertyUnixTimestamp { + post( + options: PropertyUnixTimestampParameters + ): StreamableMethod; +} + +export interface PropertyUnixTimestampArray { + post( + options: PropertyUnixTimestampArrayParameters + ): StreamableMethod; +} + +export interface HeaderDefault { + get( + options: HeaderDefaultParameters + ): StreamableMethod; +} + +export interface HeaderRfc3339 { + get( + options: HeaderRfc3339Parameters + ): StreamableMethod; +} + +export interface HeaderRfc7231 { + get( + options: HeaderRfc7231Parameters + ): StreamableMethod; +} + +export interface HeaderUnixTimestamp { + get( + options: HeaderUnixTimestampParameters + ): StreamableMethod; +} + +export interface HeaderUnixTimestampArray { + get( + options: HeaderUnixTimestampArrayParameters + ): StreamableMethod; +} + +export interface Routes { + /** Resource for '/encode/datetime/query/default' has methods for the following verbs: get */ + (path: "/encode/datetime/query/default"): QueryDefault; + /** Resource for '/encode/datetime/query/rfc3339' has methods for the following verbs: get */ + (path: "/encode/datetime/query/rfc3339"): QueryRfc3339; + /** Resource for '/encode/datetime/query/rfc7231' has methods for the following verbs: get */ + (path: "/encode/datetime/query/rfc7231"): QueryRfc7231; + /** Resource for '/encode/datetime/query/unix-timestamp' has methods for the following verbs: get */ + (path: "/encode/datetime/query/unix-timestamp"): QueryUnixTimestamp; + /** Resource for '/encode/datetime/query/unix-timestamp-array' has methods for the following verbs: get */ + ( + path: "/encode/datetime/query/unix-timestamp-array" + ): QueryUnixTimestampArray; + /** Resource for '/encode/datetime/property/default' has methods for the following verbs: post */ + (path: "/encode/datetime/property/default"): PropertyDefault; + /** Resource for '/encode/datetime/property/rfc3339' has methods for the following verbs: post */ + (path: "/encode/datetime/property/rfc3339"): PropertyRfc3339; + /** Resource for '/encode/datetime/property/rfc7231' has methods for the following verbs: post */ + (path: "/encode/datetime/property/rfc7231"): PropertyRfc7231; + /** Resource for '/encode/datetime/property/unix-timestamp' has methods for the following verbs: post */ + (path: "/encode/datetime/property/unix-timestamp"): PropertyUnixTimestamp; + /** Resource for '/encode/datetime/property/unix-timestamp-array' has methods for the following verbs: post */ + ( + path: "/encode/datetime/property/unix-timestamp-array" + ): PropertyUnixTimestampArray; + /** Resource for '/encode/datetime/header/default' has methods for the following verbs: get */ + (path: "/encode/datetime/header/default"): HeaderDefault; + /** Resource for '/encode/datetime/header/rfc3339' has methods for the following verbs: get */ + (path: "/encode/datetime/header/rfc3339"): HeaderRfc3339; + /** Resource for '/encode/datetime/header/rfc7231' has methods for the following verbs: get */ + (path: "/encode/datetime/header/rfc7231"): HeaderRfc7231; + /** Resource for '/encode/datetime/header/unix-timestamp' has methods for the following verbs: get */ + (path: "/encode/datetime/header/unix-timestamp"): HeaderUnixTimestamp; + /** Resource for '/encode/datetime/header/unix-timestamp-array' has methods for the following verbs: get */ + ( + path: "/encode/datetime/header/unix-timestamp-array" + ): HeaderUnixTimestampArray; +} + +export type DatetimeContext = Client & { + path: Routes; +}; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/datetimeClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/datetimeClient.ts new file mode 100644 index 0000000000..eadbf6b783 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/datetimeClient.ts @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "../logger.js"; +import { DatetimeContext } from "./clientDefinitions.js"; + +/** + * Initialize a new instance of `DatetimeContext` + * @param options - the parameter for all optional parameters + */ +export default function createClient( + options: ClientOptions = {} +): DatetimeContext { + const baseUrl = options.baseUrl ?? `http://localhost:3000`; + options.apiVersion = options.apiVersion ?? "1.0.0"; + const userAgentInfo = `azsdk-js-encode-datatime-rest/1.0.0-beta.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + }; + + const client = getClient(baseUrl, options) as DatetimeContext; + + return client; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/index.ts new file mode 100644 index 0000000000..968ba66f03 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/index.ts @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import DatetimeClient from "./datetimeClient.js"; + +export * from "./datetimeClient.js"; +export * from "./parameters.js"; +export * from "./responses.js"; +export * from "./clientDefinitions.js"; +export * from "./models.js"; +export * from "./outputModels.js"; + +export default DatetimeClient; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/models.ts new file mode 100644 index 0000000000..ae51efd66e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/models.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDatetimeProperty { + value: Date | string; +} + +export interface Rfc3339DatetimeProperty { + value: Date | string; +} + +export interface Rfc7231DatetimeProperty { + value: Date | string; +} + +export interface UnixTimestampDatetimeProperty { + value: number; +} + +export interface UnixTimestampArrayDatetimeProperty { + value: number[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/outputModels.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/outputModels.ts new file mode 100644 index 0000000000..51c6afbd5e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/outputModels.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDatetimePropertyOutput { + value: string; +} + +export interface Rfc3339DatetimePropertyOutput { + value: string; +} + +export interface Rfc7231DatetimePropertyOutput { + value: string; +} + +export interface UnixTimestampDatetimePropertyOutput { + value: number; +} + +export interface UnixTimestampArrayDatetimePropertyOutput { + value: number[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/parameters.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/parameters.ts new file mode 100644 index 0000000000..ba029da0b3 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/parameters.ts @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RawHttpHeadersInput } from "@azure/core-rest-pipeline"; +import { RequestParameters } from "@azure-rest/core-client"; +import { + DefaultDatetimeProperty, + Rfc3339DatetimeProperty, + Rfc7231DatetimeProperty, + UnixTimestampDatetimeProperty, + UnixTimestampArrayDatetimeProperty, +} from "./models.js"; + +export interface QueryDefaultQueryParamProperties { + value: Date | string; +} + +export interface QueryDefaultQueryParam { + queryParameters: QueryDefaultQueryParamProperties; +} + +export type QueryDefaultParameters = QueryDefaultQueryParam & RequestParameters; + +export interface QueryRfc3339QueryParamProperties { + value: Date | string; +} + +export interface QueryRfc3339QueryParam { + queryParameters: QueryRfc3339QueryParamProperties; +} + +export type QueryRfc3339Parameters = QueryRfc3339QueryParam & RequestParameters; + +export interface QueryRfc7231QueryParamProperties { + value: Date | string; +} + +export interface QueryRfc7231QueryParam { + queryParameters: QueryRfc7231QueryParamProperties; +} + +export type QueryRfc7231Parameters = QueryRfc7231QueryParam & RequestParameters; + +export interface QueryUnixTimestampQueryParamProperties { + value: number; +} + +export interface QueryUnixTimestampQueryParam { + queryParameters: QueryUnixTimestampQueryParamProperties; +} + +export type QueryUnixTimestampParameters = QueryUnixTimestampQueryParam & + RequestParameters; + +export interface QueryUnixTimestampArrayQueryParamProperties { + value: number[]; +} + +export interface QueryUnixTimestampArrayQueryParam { + queryParameters: QueryUnixTimestampArrayQueryParamProperties; +} + +export type QueryUnixTimestampArrayParameters = + QueryUnixTimestampArrayQueryParam & RequestParameters; + +export interface PropertyDefaultBodyParam { + body: DefaultDatetimeProperty; +} + +export type PropertyDefaultParameters = PropertyDefaultBodyParam & + RequestParameters; + +export interface PropertyRfc3339BodyParam { + body: Rfc3339DatetimeProperty; +} + +export type PropertyRfc3339Parameters = PropertyRfc3339BodyParam & + RequestParameters; + +export interface PropertyRfc7231BodyParam { + body: Rfc7231DatetimeProperty; +} + +export type PropertyRfc7231Parameters = PropertyRfc7231BodyParam & + RequestParameters; + +export interface PropertyUnixTimestampBodyParam { + body: UnixTimestampDatetimeProperty; +} + +export type PropertyUnixTimestampParameters = PropertyUnixTimestampBodyParam & + RequestParameters; + +export interface PropertyUnixTimestampArrayBodyParam { + body: UnixTimestampArrayDatetimeProperty; +} + +export type PropertyUnixTimestampArrayParameters = + PropertyUnixTimestampArrayBodyParam & RequestParameters; + +export interface HeaderDefaultHeaders { + value: string; +} + +export interface HeaderDefaultHeaderParam { + headers: RawHttpHeadersInput & HeaderDefaultHeaders; +} + +export type HeaderDefaultParameters = HeaderDefaultHeaderParam & + RequestParameters; + +export interface HeaderRfc3339Headers { + value: string; +} + +export interface HeaderRfc3339HeaderParam { + headers: RawHttpHeadersInput & HeaderRfc3339Headers; +} + +export type HeaderRfc3339Parameters = HeaderRfc3339HeaderParam & + RequestParameters; + +export interface HeaderRfc7231Headers { + value: string; +} + +export interface HeaderRfc7231HeaderParam { + headers: RawHttpHeadersInput & HeaderRfc7231Headers; +} + +export type HeaderRfc7231Parameters = HeaderRfc7231HeaderParam & + RequestParameters; + +export interface HeaderUnixTimestampHeaders { + value: number; +} + +export interface HeaderUnixTimestampHeaderParam { + headers: RawHttpHeadersInput & HeaderUnixTimestampHeaders; +} + +export type HeaderUnixTimestampParameters = HeaderUnixTimestampHeaderParam & + RequestParameters; + +export interface HeaderUnixTimestampArrayHeaders { + /** This parameter needs to be formatted as csv collection, we provide buildCsvCollection from serializeHelper.ts to help */ + value: string; +} + +export interface HeaderUnixTimestampArrayHeaderParam { + headers: RawHttpHeadersInput & HeaderUnixTimestampArrayHeaders; +} + +export type HeaderUnixTimestampArrayParameters = + HeaderUnixTimestampArrayHeaderParam & RequestParameters; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/responses.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/responses.ts new file mode 100644 index 0000000000..0b0101e9ba --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/responses.ts @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { HttpResponse } from "@azure-rest/core-client"; +import { + DefaultDatetimePropertyOutput, + Rfc3339DatetimePropertyOutput, + Rfc7231DatetimePropertyOutput, + UnixTimestampDatetimePropertyOutput, + UnixTimestampArrayDatetimePropertyOutput, +} from "./outputModels.js"; + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryRfc3339204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryRfc7231204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryUnixTimestamp204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryUnixTimestampArray204Response extends HttpResponse { + status: "204"; +} + +/** The request has succeeded. */ +export interface PropertyDefault200Response extends HttpResponse { + status: "200"; + body: DefaultDatetimePropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyRfc3339200Response extends HttpResponse { + status: "200"; + body: Rfc3339DatetimePropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyRfc7231200Response extends HttpResponse { + status: "200"; + body: Rfc7231DatetimePropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyUnixTimestamp200Response extends HttpResponse { + status: "200"; + body: UnixTimestampDatetimePropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyUnixTimestampArray200Response extends HttpResponse { + status: "200"; + body: UnixTimestampArrayDatetimePropertyOutput; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderRfc3339204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderRfc7231204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderUnixTimestamp204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderUnixTimestampArray204Response extends HttpResponse { + status: "204"; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/serializeHelper.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/serializeHelper.ts new file mode 100644 index 0000000000..aeb95223cc --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/serializeHelper.ts @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function buildCsvCollection(items: string[] | number[]) { + return items.join(","); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/tspconfig.yaml b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/tspconfig.yaml new file mode 100644 index 0000000000..03aecac2c6 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/tspconfig.yaml @@ -0,0 +1,14 @@ +emit: + - "@azure-tools/typespec-ts" +options: + "@azure-tools/typespec-ts": + "emitter-output-dir": "{project-root}" + generateMetadata: false + generateTest: false + addCredentials: false + azureSdkForJs: false + isTypeSpecTest: true + enableOperationGroup: true + isModularLibrary: true + packageDetails: + name: "@msinternal/encode-datatime" diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts new file mode 100644 index 0000000000..81632e75d7 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultDurationProperty, + ISO8601DurationProperty, + Int32SecondsDurationProperty, + FloatSecondsDurationProperty, + FloatSecondsDurationArrayProperty, +} from "./models/models.js"; +import { + QueryDefaultOptions, + QueryIso8601Options, + QueryInt32SecondsOptions, + QueryFloatSecondsOptions, + QueryInt32SecondsArrayOptions, + PropertyDefaultOptions, + PropertyIso8601Options, + PropertyInt32SecondsOptions, + PropertyFloatSecondsOptions, + PropertyFloatSecondsArrayOptions, + HeaderDefaultOptions, + HeaderIso8601Options, + HeaderIso8601ArrayOptions, + HeaderInt32SecondsOptions, + HeaderFloatSecondsOptions, +} from "./models/options.js"; +import { + createDuration, + DurationClientOptions, + DurationContext, + headerDefault, + headerIso8601, + headerIso8601Array, + headerInt32Seconds, + headerFloatSeconds, + propertyDefault, + propertyIso8601, + propertyInt32Seconds, + propertyFloatSeconds, + propertyFloatSecondsArray, + queryDefault, + queryIso8601, + queryInt32Seconds, + queryFloatSeconds, + queryInt32SecondsArray, +} from "./api/index.js"; + +export { DurationClientOptions } from "./api/DurationContext.js"; + +export class DurationClient { + private _client: DurationContext; + + /** Test for encode decorator on duration. */ + constructor(options: DurationClientOptions = {}) { + this._client = createDuration(options); + } + + query = { + default: (input: string, options?: QueryDefaultOptions): Promise => { + return queryDefault(this._client, input, options); + }, + iso8601: (input: string, options?: QueryIso8601Options): Promise => { + return queryIso8601(this._client, input, options); + }, + int32Seconds: ( + input: string, + options?: QueryInt32SecondsOptions + ): Promise => { + return queryInt32Seconds(this._client, input, options); + }, + floatSeconds: ( + input: string, + options?: QueryFloatSecondsOptions + ): Promise => { + return queryFloatSeconds(this._client, input, options); + }, + int32SecondsArray: ( + input: string[], + options?: QueryInt32SecondsArrayOptions + ): Promise => { + return queryInt32SecondsArray(this._client, input, options); + }, + }; + property = { + default: ( + value: string, + options?: PropertyDefaultOptions + ): Promise => { + return propertyDefault(this._client, value, options); + }, + iso8601: ( + value: string, + options?: PropertyIso8601Options + ): Promise => { + return propertyIso8601(this._client, value, options); + }, + int32Seconds: ( + value: string, + options?: PropertyInt32SecondsOptions + ): Promise => { + return propertyInt32Seconds(this._client, value, options); + }, + floatSeconds: ( + value: string, + options?: PropertyFloatSecondsOptions + ): Promise => { + return propertyFloatSeconds(this._client, value, options); + }, + floatSecondsArray: ( + value: string[], + options?: PropertyFloatSecondsArrayOptions + ): Promise => { + return propertyFloatSecondsArray(this._client, value, options); + }, + }; + header = { + default: ( + duration: string, + options?: HeaderDefaultOptions + ): Promise => { + return headerDefault(this._client, duration, options); + }, + iso8601: ( + duration: string, + options?: HeaderIso8601Options + ): Promise => { + return headerIso8601(this._client, duration, options); + }, + iso8601Array: ( + duration: string[], + options?: HeaderIso8601ArrayOptions + ): Promise => { + return headerIso8601Array(this._client, duration, options); + }, + int32Seconds: ( + duration: string, + options?: HeaderInt32SecondsOptions + ): Promise => { + return headerInt32Seconds(this._client, duration, options); + }, + floatSeconds: ( + duration: string, + options?: HeaderFloatSecondsOptions + ): Promise => { + return headerFloatSeconds(this._client, duration, options); + }, + }; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/DurationContext.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/DurationContext.ts new file mode 100644 index 0000000000..0016bd1b25 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/DurationContext.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { ClientOptions } from "@azure-rest/core-client"; +import { DurationContext } from "../rest/index.js"; +import getClient from "../rest/index.js"; + +export interface DurationClientOptions extends ClientOptions {} + +export { DurationContext } from "../rest/index.js"; + +/** Test for encode decorator on duration. */ +export function createDuration( + options: DurationClientOptions = {} +): DurationContext { + const clientContext = getClient(options); + return clientContext; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts new file mode 100644 index 0000000000..42bb25e523 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DurationContext as Client, + HeaderDefault204Response, + HeaderFloatSeconds204Response, + HeaderInt32Seconds204Response, + HeaderIso8601204Response, + HeaderIso8601Array204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + HeaderDefaultOptions, + HeaderIso8601Options, + HeaderIso8601ArrayOptions, + HeaderInt32SecondsOptions, + HeaderFloatSecondsOptions, +} from "../models/options.js"; + +export function _headerDefaultSend( + context: Client, + duration: string, + options: HeaderDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/header/default") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { duration: duration }, + }); +} + +export async function _headerDefaultDeserialize( + result: HeaderDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerDefault( + context: Client, + duration: string, + options: HeaderDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _headerDefaultSend(context, duration, options); + return _headerDefaultDeserialize(result); +} + +export function _headerIso8601Send( + context: Client, + duration: string, + options: HeaderIso8601Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/header/iso8601") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { duration: duration }, + }); +} + +export async function _headerIso8601Deserialize( + result: HeaderIso8601204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerIso8601( + context: Client, + duration: string, + options: HeaderIso8601Options = { requestOptions: {} } +): Promise { + const result = await _headerIso8601Send(context, duration, options); + return _headerIso8601Deserialize(result); +} + +export function _headerIso8601ArraySend( + context: Client, + duration: string[], + options: HeaderIso8601ArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/header/iso8601-array") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { duration: buildCsvCollection(duration) }, + }); +} + +export async function _headerIso8601ArrayDeserialize( + result: HeaderIso8601Array204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerIso8601Array( + context: Client, + duration: string[], + options: HeaderIso8601ArrayOptions = { requestOptions: {} } +): Promise { + const result = await _headerIso8601ArraySend(context, duration, options); + return _headerIso8601ArrayDeserialize(result); +} + +export function _headerInt32SecondsSend( + context: Client, + duration: string, + options: HeaderInt32SecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/header/int32-seconds") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { duration: duration }, + }); +} + +export async function _headerInt32SecondsDeserialize( + result: HeaderInt32Seconds204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerInt32Seconds( + context: Client, + duration: string, + options: HeaderInt32SecondsOptions = { requestOptions: {} } +): Promise { + const result = await _headerInt32SecondsSend(context, duration, options); + return _headerInt32SecondsDeserialize(result); +} + +export function _headerFloatSecondsSend( + context: Client, + duration: string, + options: HeaderFloatSecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/header/float-seconds") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { duration: duration }, + }); +} + +export async function _headerFloatSecondsDeserialize( + result: HeaderFloatSeconds204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerFloatSeconds( + context: Client, + duration: string, + options: HeaderFloatSecondsOptions = { requestOptions: {} } +): Promise { + const result = await _headerFloatSecondsSend(context, duration, options); + return _headerFloatSecondsDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/index.ts new file mode 100644 index 0000000000..716eddc539 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/index.ts @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + createDuration, + DurationClientOptions, + DurationContext, +} from "./DurationContext.js"; +export { + headerDefault, + headerIso8601, + headerIso8601Array, + headerInt32Seconds, + headerFloatSeconds, +} from "./header.js"; +export { + propertyDefault, + propertyIso8601, + propertyInt32Seconds, + propertyFloatSeconds, + propertyFloatSecondsArray, +} from "./property.js"; +export { + queryDefault, + queryIso8601, + queryInt32Seconds, + queryFloatSeconds, + queryInt32SecondsArray, +} from "./query.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts new file mode 100644 index 0000000000..6078800421 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultDurationProperty, + ISO8601DurationProperty, + Int32SecondsDurationProperty, + FloatSecondsDurationProperty, + FloatSecondsDurationArrayProperty, +} from "../models/models.js"; +import { + DurationContext as Client, + PropertyDefault200Response, + PropertyFloatSeconds200Response, + PropertyFloatSecondsArray200Response, + PropertyInt32Seconds200Response, + PropertyIso8601200Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + PropertyDefaultOptions, + PropertyIso8601Options, + PropertyInt32SecondsOptions, + PropertyFloatSecondsOptions, + PropertyFloatSecondsArrayOptions, +} from "../models/options.js"; + +export function _propertyDefaultSend( + context: Client, + value: string, + options: PropertyDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/property/default") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyDefaultDeserialize( + result: PropertyDefault200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyDefault( + context: Client, + value: string, + options: PropertyDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _propertyDefaultSend(context, value, options); + return _propertyDefaultDeserialize(result); +} + +export function _propertyIso8601Send( + context: Client, + value: string, + options: PropertyIso8601Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/property/iso8601") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyIso8601Deserialize( + result: PropertyIso8601200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyIso8601( + context: Client, + value: string, + options: PropertyIso8601Options = { requestOptions: {} } +): Promise { + const result = await _propertyIso8601Send(context, value, options); + return _propertyIso8601Deserialize(result); +} + +export function _propertyInt32SecondsSend( + context: Client, + value: string, + options: PropertyInt32SecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/property/int32-seconds") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyInt32SecondsDeserialize( + result: PropertyInt32Seconds200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyInt32Seconds( + context: Client, + value: string, + options: PropertyInt32SecondsOptions = { requestOptions: {} } +): Promise { + const result = await _propertyInt32SecondsSend(context, value, options); + return _propertyInt32SecondsDeserialize(result); +} + +export function _propertyFloatSecondsSend( + context: Client, + value: string, + options: PropertyFloatSecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/property/float-seconds") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyFloatSecondsDeserialize( + result: PropertyFloatSeconds200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyFloatSeconds( + context: Client, + value: string, + options: PropertyFloatSecondsOptions = { requestOptions: {} } +): Promise { + const result = await _propertyFloatSecondsSend(context, value, options); + return _propertyFloatSecondsDeserialize(result); +} + +export function _propertyFloatSecondsArraySend( + context: Client, + value: string[], + options: PropertyFloatSecondsArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/property/float-seconds-array") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyFloatSecondsArrayDeserialize( + result: PropertyFloatSecondsArray200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyFloatSecondsArray( + context: Client, + value: string[], + options: PropertyFloatSecondsArrayOptions = { requestOptions: {} } +): Promise { + const result = await _propertyFloatSecondsArraySend(context, value, options); + return _propertyFloatSecondsArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts new file mode 100644 index 0000000000..2b18a69d3c --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DurationContext as Client, + QueryDefault204Response, + QueryFloatSeconds204Response, + QueryInt32Seconds204Response, + QueryInt32SecondsArray204Response, + QueryIso8601204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + QueryDefaultOptions, + QueryIso8601Options, + QueryInt32SecondsOptions, + QueryFloatSecondsOptions, + QueryInt32SecondsArrayOptions, +} from "../models/options.js"; + +export function _queryDefaultSend( + context: Client, + input: string, + options: QueryDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/query/default") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { input: input }, + }); +} + +export async function _queryDefaultDeserialize( + result: QueryDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryDefault( + context: Client, + input: string, + options: QueryDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _queryDefaultSend(context, input, options); + return _queryDefaultDeserialize(result); +} + +export function _queryIso8601Send( + context: Client, + input: string, + options: QueryIso8601Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/query/iso8601") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { input: input }, + }); +} + +export async function _queryIso8601Deserialize( + result: QueryIso8601204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryIso8601( + context: Client, + input: string, + options: QueryIso8601Options = { requestOptions: {} } +): Promise { + const result = await _queryIso8601Send(context, input, options); + return _queryIso8601Deserialize(result); +} + +export function _queryInt32SecondsSend( + context: Client, + input: string, + options: QueryInt32SecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/query/int32-seconds") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { input: input }, + }); +} + +export async function _queryInt32SecondsDeserialize( + result: QueryInt32Seconds204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryInt32Seconds( + context: Client, + input: string, + options: QueryInt32SecondsOptions = { requestOptions: {} } +): Promise { + const result = await _queryInt32SecondsSend(context, input, options); + return _queryInt32SecondsDeserialize(result); +} + +export function _queryFloatSecondsSend( + context: Client, + input: string, + options: QueryFloatSecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/query/float-seconds") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { input: input }, + }); +} + +export async function _queryFloatSecondsDeserialize( + result: QueryFloatSeconds204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryFloatSeconds( + context: Client, + input: string, + options: QueryFloatSecondsOptions = { requestOptions: {} } +): Promise { + const result = await _queryFloatSecondsSend(context, input, options); + return _queryFloatSecondsDeserialize(result); +} + +export function _queryInt32SecondsArraySend( + context: Client, + input: string[], + options: QueryInt32SecondsArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/query/int32-seconds-array") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { input: input }, + }); +} + +export async function _queryInt32SecondsArrayDeserialize( + result: QueryInt32SecondsArray204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryInt32SecondsArray( + context: Client, + input: string[], + options: QueryInt32SecondsArrayOptions = { requestOptions: {} } +): Promise { + const result = await _queryInt32SecondsArraySend(context, input, options); + return _queryInt32SecondsArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/index.ts new file mode 100644 index 0000000000..58be9b1f92 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/index.ts @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { DurationClient, DurationClientOptions } from "./DurationClient.js"; +export { + DefaultDurationProperty, + ISO8601DurationProperty, + Int32SecondsDurationProperty, + FloatSecondsDurationProperty, + FloatSecondsDurationArrayProperty, + QueryDefaultOptions, + QueryIso8601Options, + QueryInt32SecondsOptions, + QueryFloatSecondsOptions, + QueryInt32SecondsArrayOptions, + PropertyDefaultOptions, + PropertyIso8601Options, + PropertyInt32SecondsOptions, + PropertyFloatSecondsOptions, + PropertyFloatSecondsArrayOptions, + HeaderDefaultOptions, + HeaderIso8601Options, + HeaderIso8601ArrayOptions, + HeaderInt32SecondsOptions, + HeaderFloatSecondsOptions, +} from "./models/index.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/logger.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/logger.ts new file mode 100644 index 0000000000..aa142f6020 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/logger.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("encode-duration"); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/index.ts new file mode 100644 index 0000000000..f0b43ea881 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/index.ts @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + DefaultDurationProperty, + ISO8601DurationProperty, + Int32SecondsDurationProperty, + FloatSecondsDurationProperty, + FloatSecondsDurationArrayProperty, +} from "./models.js"; +export { + QueryDefaultOptions, + QueryIso8601Options, + QueryInt32SecondsOptions, + QueryFloatSecondsOptions, + QueryInt32SecondsArrayOptions, + PropertyDefaultOptions, + PropertyIso8601Options, + PropertyInt32SecondsOptions, + PropertyFloatSecondsOptions, + PropertyFloatSecondsArrayOptions, + HeaderDefaultOptions, + HeaderIso8601Options, + HeaderIso8601ArrayOptions, + HeaderInt32SecondsOptions, + HeaderFloatSecondsOptions, +} from "./options.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts new file mode 100644 index 0000000000..2f6b1086e3 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDurationProperty { + value: string; +} + +export interface ISO8601DurationProperty { + value: string; +} + +export interface Int32SecondsDurationProperty { + value: string; +} + +export interface FloatSecondsDurationProperty { + value: string; +} + +export interface FloatSecondsDurationArrayProperty { + value: string[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/options.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/options.ts new file mode 100644 index 0000000000..5dff518131 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/options.ts @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { OperationOptions } from "@azure-rest/core-client"; + +export interface QueryDefaultOptions extends OperationOptions {} + +export interface QueryIso8601Options extends OperationOptions {} + +export interface QueryInt32SecondsOptions extends OperationOptions {} + +export interface QueryFloatSecondsOptions extends OperationOptions {} + +export interface QueryInt32SecondsArrayOptions extends OperationOptions {} + +export interface PropertyDefaultOptions extends OperationOptions {} + +export interface PropertyIso8601Options extends OperationOptions {} + +export interface PropertyInt32SecondsOptions extends OperationOptions {} + +export interface PropertyFloatSecondsOptions extends OperationOptions {} + +export interface PropertyFloatSecondsArrayOptions extends OperationOptions {} + +export interface HeaderDefaultOptions extends OperationOptions {} + +export interface HeaderIso8601Options extends OperationOptions {} + +export interface HeaderIso8601ArrayOptions extends OperationOptions {} + +export interface HeaderInt32SecondsOptions extends OperationOptions {} + +export interface HeaderFloatSecondsOptions extends OperationOptions {} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/clientDefinitions.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/clientDefinitions.ts new file mode 100644 index 0000000000..c75cf2c79f --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/clientDefinitions.ts @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + QueryDefaultParameters, + QueryIso8601Parameters, + QueryInt32SecondsParameters, + QueryFloatSecondsParameters, + QueryInt32SecondsArrayParameters, + PropertyDefaultParameters, + PropertyIso8601Parameters, + PropertyInt32SecondsParameters, + PropertyFloatSecondsParameters, + PropertyFloatSecondsArrayParameters, + HeaderDefaultParameters, + HeaderIso8601Parameters, + HeaderIso8601ArrayParameters, + HeaderInt32SecondsParameters, + HeaderFloatSecondsParameters, +} from "./parameters.js"; +import { + QueryDefault204Response, + QueryIso8601204Response, + QueryInt32Seconds204Response, + QueryFloatSeconds204Response, + QueryInt32SecondsArray204Response, + PropertyDefault200Response, + PropertyIso8601200Response, + PropertyInt32Seconds200Response, + PropertyFloatSeconds200Response, + PropertyFloatSecondsArray200Response, + HeaderDefault204Response, + HeaderIso8601204Response, + HeaderIso8601Array204Response, + HeaderInt32Seconds204Response, + HeaderFloatSeconds204Response, +} from "./responses.js"; +import { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface QueryDefault { + get( + options: QueryDefaultParameters + ): StreamableMethod; +} + +export interface QueryIso8601 { + get( + options: QueryIso8601Parameters + ): StreamableMethod; +} + +export interface QueryInt32Seconds { + get( + options: QueryInt32SecondsParameters + ): StreamableMethod; +} + +export interface QueryFloatSeconds { + get( + options: QueryFloatSecondsParameters + ): StreamableMethod; +} + +export interface QueryInt32SecondsArray { + get( + options: QueryInt32SecondsArrayParameters + ): StreamableMethod; +} + +export interface PropertyDefault { + post( + options: PropertyDefaultParameters + ): StreamableMethod; +} + +export interface PropertyIso8601 { + post( + options: PropertyIso8601Parameters + ): StreamableMethod; +} + +export interface PropertyInt32Seconds { + post( + options: PropertyInt32SecondsParameters + ): StreamableMethod; +} + +export interface PropertyFloatSeconds { + post( + options: PropertyFloatSecondsParameters + ): StreamableMethod; +} + +export interface PropertyFloatSecondsArray { + post( + options: PropertyFloatSecondsArrayParameters + ): StreamableMethod; +} + +export interface HeaderDefault { + get( + options: HeaderDefaultParameters + ): StreamableMethod; +} + +export interface HeaderIso8601 { + get( + options: HeaderIso8601Parameters + ): StreamableMethod; +} + +export interface HeaderIso8601Array { + get( + options: HeaderIso8601ArrayParameters + ): StreamableMethod; +} + +export interface HeaderInt32Seconds { + get( + options: HeaderInt32SecondsParameters + ): StreamableMethod; +} + +export interface HeaderFloatSeconds { + get( + options: HeaderFloatSecondsParameters + ): StreamableMethod; +} + +export interface Routes { + /** Resource for '/encode/duration/query/default' has methods for the following verbs: get */ + (path: "/encode/duration/query/default"): QueryDefault; + /** Resource for '/encode/duration/query/iso8601' has methods for the following verbs: get */ + (path: "/encode/duration/query/iso8601"): QueryIso8601; + /** Resource for '/encode/duration/query/int32-seconds' has methods for the following verbs: get */ + (path: "/encode/duration/query/int32-seconds"): QueryInt32Seconds; + /** Resource for '/encode/duration/query/float-seconds' has methods for the following verbs: get */ + (path: "/encode/duration/query/float-seconds"): QueryFloatSeconds; + /** Resource for '/encode/duration/query/int32-seconds-array' has methods for the following verbs: get */ + (path: "/encode/duration/query/int32-seconds-array"): QueryInt32SecondsArray; + /** Resource for '/encode/duration/property/default' has methods for the following verbs: post */ + (path: "/encode/duration/property/default"): PropertyDefault; + /** Resource for '/encode/duration/property/iso8601' has methods for the following verbs: post */ + (path: "/encode/duration/property/iso8601"): PropertyIso8601; + /** Resource for '/encode/duration/property/int32-seconds' has methods for the following verbs: post */ + (path: "/encode/duration/property/int32-seconds"): PropertyInt32Seconds; + /** Resource for '/encode/duration/property/float-seconds' has methods for the following verbs: post */ + (path: "/encode/duration/property/float-seconds"): PropertyFloatSeconds; + /** Resource for '/encode/duration/property/float-seconds-array' has methods for the following verbs: post */ + ( + path: "/encode/duration/property/float-seconds-array" + ): PropertyFloatSecondsArray; + /** Resource for '/encode/duration/header/default' has methods for the following verbs: get */ + (path: "/encode/duration/header/default"): HeaderDefault; + /** Resource for '/encode/duration/header/iso8601' has methods for the following verbs: get */ + (path: "/encode/duration/header/iso8601"): HeaderIso8601; + /** Resource for '/encode/duration/header/iso8601-array' has methods for the following verbs: get */ + (path: "/encode/duration/header/iso8601-array"): HeaderIso8601Array; + /** Resource for '/encode/duration/header/int32-seconds' has methods for the following verbs: get */ + (path: "/encode/duration/header/int32-seconds"): HeaderInt32Seconds; + /** Resource for '/encode/duration/header/float-seconds' has methods for the following verbs: get */ + (path: "/encode/duration/header/float-seconds"): HeaderFloatSeconds; +} + +export type DurationContext = Client & { + path: Routes; +}; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/durationClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/durationClient.ts new file mode 100644 index 0000000000..d10bbfbf29 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/durationClient.ts @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "../logger.js"; +import { DurationContext } from "./clientDefinitions.js"; + +/** + * Initialize a new instance of `DurationContext` + * @param options - the parameter for all optional parameters + */ +export default function createClient( + options: ClientOptions = {} +): DurationContext { + const baseUrl = options.baseUrl ?? `http://localhost:3000`; + options.apiVersion = options.apiVersion ?? "1.0.0"; + const userAgentInfo = `azsdk-js-encode-duration-rest/1.0.0-beta.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + }; + + const client = getClient(baseUrl, options) as DurationContext; + + return client; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/index.ts new file mode 100644 index 0000000000..7f411a2b28 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/index.ts @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import DurationClient from "./durationClient.js"; + +export * from "./durationClient.js"; +export * from "./parameters.js"; +export * from "./responses.js"; +export * from "./clientDefinitions.js"; +export * from "./models.js"; +export * from "./outputModels.js"; + +export default DurationClient; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/models.ts new file mode 100644 index 0000000000..476962243e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/models.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDurationProperty { + value: string; +} + +export interface ISO8601DurationProperty { + value: string; +} + +export interface Int32SecondsDurationProperty { + value: number; +} + +export interface FloatSecondsDurationProperty { + value: number; +} + +export interface FloatSecondsDurationArrayProperty { + value: number[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/outputModels.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/outputModels.ts new file mode 100644 index 0000000000..a31b5b57db --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/outputModels.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDurationPropertyOutput { + value: string; +} + +export interface ISO8601DurationPropertyOutput { + value: string; +} + +export interface Int32SecondsDurationPropertyOutput { + value: number; +} + +export interface FloatSecondsDurationPropertyOutput { + value: number; +} + +export interface FloatSecondsDurationArrayPropertyOutput { + value: number[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/parameters.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/parameters.ts new file mode 100644 index 0000000000..15fe2c7595 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/parameters.ts @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RawHttpHeadersInput } from "@azure/core-rest-pipeline"; +import { RequestParameters } from "@azure-rest/core-client"; +import { + DefaultDurationProperty, + ISO8601DurationProperty, + Int32SecondsDurationProperty, + FloatSecondsDurationProperty, + FloatSecondsDurationArrayProperty, +} from "./models.js"; + +export interface QueryDefaultQueryParamProperties { + input: string; +} + +export interface QueryDefaultQueryParam { + queryParameters: QueryDefaultQueryParamProperties; +} + +export type QueryDefaultParameters = QueryDefaultQueryParam & RequestParameters; + +export interface QueryIso8601QueryParamProperties { + input: string; +} + +export interface QueryIso8601QueryParam { + queryParameters: QueryIso8601QueryParamProperties; +} + +export type QueryIso8601Parameters = QueryIso8601QueryParam & RequestParameters; + +export interface QueryInt32SecondsQueryParamProperties { + input: number; +} + +export interface QueryInt32SecondsQueryParam { + queryParameters: QueryInt32SecondsQueryParamProperties; +} + +export type QueryInt32SecondsParameters = QueryInt32SecondsQueryParam & + RequestParameters; + +export interface QueryFloatSecondsQueryParamProperties { + input: number; +} + +export interface QueryFloatSecondsQueryParam { + queryParameters: QueryFloatSecondsQueryParamProperties; +} + +export type QueryFloatSecondsParameters = QueryFloatSecondsQueryParam & + RequestParameters; + +export interface QueryInt32SecondsArrayQueryParamProperties { + input: number[]; +} + +export interface QueryInt32SecondsArrayQueryParam { + queryParameters: QueryInt32SecondsArrayQueryParamProperties; +} + +export type QueryInt32SecondsArrayParameters = + QueryInt32SecondsArrayQueryParam & RequestParameters; + +export interface PropertyDefaultBodyParam { + body: DefaultDurationProperty; +} + +export type PropertyDefaultParameters = PropertyDefaultBodyParam & + RequestParameters; + +export interface PropertyIso8601BodyParam { + body: ISO8601DurationProperty; +} + +export type PropertyIso8601Parameters = PropertyIso8601BodyParam & + RequestParameters; + +export interface PropertyInt32SecondsBodyParam { + body: Int32SecondsDurationProperty; +} + +export type PropertyInt32SecondsParameters = PropertyInt32SecondsBodyParam & + RequestParameters; + +export interface PropertyFloatSecondsBodyParam { + body: FloatSecondsDurationProperty; +} + +export type PropertyFloatSecondsParameters = PropertyFloatSecondsBodyParam & + RequestParameters; + +export interface PropertyFloatSecondsArrayBodyParam { + body: FloatSecondsDurationArrayProperty; +} + +export type PropertyFloatSecondsArrayParameters = + PropertyFloatSecondsArrayBodyParam & RequestParameters; + +export interface HeaderDefaultHeaders { + duration: string; +} + +export interface HeaderDefaultHeaderParam { + headers: RawHttpHeadersInput & HeaderDefaultHeaders; +} + +export type HeaderDefaultParameters = HeaderDefaultHeaderParam & + RequestParameters; + +export interface HeaderIso8601Headers { + duration: string; +} + +export interface HeaderIso8601HeaderParam { + headers: RawHttpHeadersInput & HeaderIso8601Headers; +} + +export type HeaderIso8601Parameters = HeaderIso8601HeaderParam & + RequestParameters; + +export interface HeaderIso8601ArrayHeaders { + /** This parameter needs to be formatted as csv collection, we provide buildCsvCollection from serializeHelper.ts to help */ + duration: string; +} + +export interface HeaderIso8601ArrayHeaderParam { + headers: RawHttpHeadersInput & HeaderIso8601ArrayHeaders; +} + +export type HeaderIso8601ArrayParameters = HeaderIso8601ArrayHeaderParam & + RequestParameters; + +export interface HeaderInt32SecondsHeaders { + duration: number; +} + +export interface HeaderInt32SecondsHeaderParam { + headers: RawHttpHeadersInput & HeaderInt32SecondsHeaders; +} + +export type HeaderInt32SecondsParameters = HeaderInt32SecondsHeaderParam & + RequestParameters; + +export interface HeaderFloatSecondsHeaders { + duration: number; +} + +export interface HeaderFloatSecondsHeaderParam { + headers: RawHttpHeadersInput & HeaderFloatSecondsHeaders; +} + +export type HeaderFloatSecondsParameters = HeaderFloatSecondsHeaderParam & + RequestParameters; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/responses.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/responses.ts new file mode 100644 index 0000000000..bcddc3be93 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/responses.ts @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { HttpResponse } from "@azure-rest/core-client"; +import { + DefaultDurationPropertyOutput, + ISO8601DurationPropertyOutput, + Int32SecondsDurationPropertyOutput, + FloatSecondsDurationPropertyOutput, + FloatSecondsDurationArrayPropertyOutput, +} from "./outputModels.js"; + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryIso8601204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryInt32Seconds204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryFloatSeconds204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryInt32SecondsArray204Response extends HttpResponse { + status: "204"; +} + +/** The request has succeeded. */ +export interface PropertyDefault200Response extends HttpResponse { + status: "200"; + body: DefaultDurationPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyIso8601200Response extends HttpResponse { + status: "200"; + body: ISO8601DurationPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyInt32Seconds200Response extends HttpResponse { + status: "200"; + body: Int32SecondsDurationPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyFloatSeconds200Response extends HttpResponse { + status: "200"; + body: FloatSecondsDurationPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyFloatSecondsArray200Response extends HttpResponse { + status: "200"; + body: FloatSecondsDurationArrayPropertyOutput; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderIso8601204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderIso8601Array204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderInt32Seconds204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderFloatSeconds204Response extends HttpResponse { + status: "204"; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/serializeHelper.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/serializeHelper.ts new file mode 100644 index 0000000000..aeb95223cc --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/serializeHelper.ts @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function buildCsvCollection(items: string[] | number[]) { + return items.join(","); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/tspconfig.yaml b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/tspconfig.yaml new file mode 100644 index 0000000000..36b5a41544 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/tspconfig.yaml @@ -0,0 +1,14 @@ +emit: + - "@azure-tools/typespec-ts" +options: + "@azure-tools/typespec-ts": + "emitter-output-dir": "{project-root}" + generateMetadata: false + generateTest: false + addCredentials: false + azureSdkForJs: false + isTypeSpecTest: true + enableOperationGroup: true + isModularLibrary: true + packageDetails: + name: "@msinternal/encode-duration" From a47b338a890e865c1e58962b9e3949f5a8d7466f Mon Sep 17 00:00:00 2001 From: Qiaoqiao Zhang Date: Mon, 4 Sep 2023 17:16:09 +0800 Subject: [PATCH 02/17] try fix modular encoding --- .../typespec-ts/src/modular/buildCodeModel.ts | 3 +- .../src/modular/helpers/operationHelpers.ts | 45 ++++++++++++++----- .../azure/core/src/api/operations.ts | 16 ++++++- .../generated/encode/bytes/src/api/header.ts | 7 +-- .../encode/bytes/src/api/property.ts | 8 ++-- .../generated/encode/bytes/src/api/query.ts | 7 +-- .../encode/datetime/src/api/header.ts | 8 ++-- .../encode/datetime/src/api/property.ts | 10 ++--- .../encode/datetime/src/api/query.ts | 10 ++--- 9 files changed, 76 insertions(+), 38 deletions(-) diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index b601160f81..280def95ea 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -27,7 +27,6 @@ import { isStringType, getPropertyType, isNumericType, - getFormat, getMinItems, getMaxItems, listServices, @@ -1076,7 +1075,7 @@ function applyIntrinsicDecorators( newResult.description = docStr; } - const formatStr = getFormat(program, type); + const formatStr = getEncode(program, type); if (isString && !result.format && formatStr) { newResult.format = formatStr; } diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index e67b3d548e..583ec6b022 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -483,7 +483,12 @@ function getRequired(param: RequiredType, importSet: Map>) { importSet ).join(",")}`; } - return `"${param.restApiName}": ${param.clientName}`; + return `"${param.restApiName}": ${serializeRequestValue( + param.type, + param.restApiName, + importSet, + true + )}`; } type ConstantType = (Parameter | Property) & { @@ -525,7 +530,12 @@ function getOptional(param: OptionalType, importSet: Map>) { importSet ).join(", ")}}`; } - return `"${param.restApiName}": options?.${param.clientName}`; + return `"${param.restApiName}": ${serializeRequestValue( + param.type, + `options?.${param.restApiName}`, + importSet, + false + )}`; } /** @@ -633,7 +643,8 @@ function getRequestModelMapping( `"${property.restApiName}": ${serializeRequestValue( property.type, restValue, - importSet + importSet, + !propertyPath.endsWith("?") )}` ); } @@ -787,12 +798,21 @@ function deserializeResponseValue( function serializeRequestValue( type: Type, restValue: string, - importSet: Map> + importSet: Map>, + required: boolean ): string { const coreUtilSet = importSet.get("@azure/core-util"); switch (type.type) { case "datetime": - return `${restValue} !== undefined ? new Date(${restValue}): undefined`; + if (type.format === "ISO8601") { + return `${restValue}.toISOString()`; + } if (type.format === "RFC1123") { + new Date().getTime() + return `${restValue}.toLo()`; + } if (type.format === "UnixTime") { + return `${restValue}.getTime()`; + } + return `${restValue}.toISOString()`; case "list": if (type.elementType?.type === "model") { return `(${restValue} ?? []).map(p => ({${getRequestModelMapping( @@ -801,12 +821,15 @@ function serializeRequestValue( importSet )}}))`; } else if ( - type.elementType?.properties?.some((p) => needsDeserialize(p.type)) + needsDeserialize(type.elementType) ) { return `(${restValue} ?? []).map(p => ${serializeRequestValue( type.elementType!, "p", - importSet + importSet, + type.elementType?.nullable !== undefined + ? !type.elementType.nullable + : false )})`; } else { return restValue; @@ -820,9 +843,11 @@ function serializeRequestValue( } else { coreUtilSet.add("uint8ArrayToString"); } - return `${restValue} !== undefined ? uint8ArrayToString(${restValue}, "${ - type.format ?? "base64" - }"): undefined`; + return required + ? `uint8ArrayToString(${restValue}, "${type.format ?? "base64"}")` + : `${restValue} !== undefined ? uint8ArrayToString(${restValue}, "${ + type.format ?? "base64" + }"): undefined`; default: return restValue; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts index 492cd4f9a9..6feb3389e3 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts @@ -56,7 +56,13 @@ export function _createOrUpdateSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { name: name, orders: options?.orders }, + body: { + name: name, + orders: (options?.orders ?? []).map((p) => ({ + userId: p["userId"], + detail: p["detail"], + })), + }, }); } @@ -107,7 +113,13 @@ export function _createOrReplaceSend( .path("/azure/core/basic/users/{id}", id) .put({ ...operationOptionsToRequestParameters(options), - body: { name: name, orders: options?.orders }, + body: { + name: name, + orders: (options?.orders ?? []).map((p) => ({ + userId: p["userId"], + detail: p["detail"], + })), + }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts index b117843ac8..9b205cb054 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts @@ -12,6 +12,7 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; +import { uint8ArrayToString } from "@azure/core-util"; import { HeaderDefaultOptions, HeaderBase64Options, @@ -28,7 +29,7 @@ export function _headerDefaultSend( .path("/encode/bytes/header/default") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value }, + headers: { value: uint8ArrayToString(value, "base64") }, }); } @@ -60,7 +61,7 @@ export function _headerBase64Send( .path("/encode/bytes/header/base64") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value }, + headers: { value: uint8ArrayToString(value, "base64") }, }); } @@ -92,7 +93,7 @@ export function _headerBase64urlSend( .path("/encode/bytes/header/base64url") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value }, + headers: { value: uint8ArrayToString(value, "base64") }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts index 183258afce..f441f2f773 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts @@ -18,7 +18,7 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { stringToUint8Array } from "@azure/core-util"; +import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; import { PropertyDefaultOptions, PropertyBase64Options, @@ -35,7 +35,7 @@ export function _propertyDefaultSend( .path("/encode/bytes/property/default") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value }, + body: { value: uint8ArrayToString(value, "base64") }, }); } @@ -72,7 +72,7 @@ export function _propertyBase64Send( .path("/encode/bytes/property/base64") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value }, + body: { value: uint8ArrayToString(value, "base64") }, }); } @@ -109,7 +109,7 @@ export function _propertyBase64urlSend( .path("/encode/bytes/property/base64url") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value }, + body: { value: uint8ArrayToString(value, "base64") }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts index 61a00d4c94..fdb3e67e47 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts @@ -12,6 +12,7 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; +import { uint8ArrayToString } from "@azure/core-util"; import { QueryDefaultOptions, QueryBase64Options, @@ -28,7 +29,7 @@ export function _queryDefaultSend( .path("/encode/bytes/query/default") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value }, + queryParameters: { value: uint8ArrayToString(value, "base64") }, }); } @@ -60,7 +61,7 @@ export function _queryBase64Send( .path("/encode/bytes/query/base64") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value }, + queryParameters: { value: uint8ArrayToString(value, "base64") }, }); } @@ -92,7 +93,7 @@ export function _queryBase64urlSend( .path("/encode/bytes/query/base64url") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value }, + queryParameters: { value: uint8ArrayToString(value, "base64") }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts index bbca3d9c64..76feb7bc54 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts @@ -30,7 +30,7 @@ export function _headerDefaultSend( .path("/encode/datetime/header/default") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value }, + headers: { value: value.toISOString() }, }); } @@ -62,7 +62,7 @@ export function _headerRfc3339Send( .path("/encode/datetime/header/rfc3339") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value }, + headers: { value: value.toISOString() }, }); } @@ -94,7 +94,7 @@ export function _headerRfc7231Send( .path("/encode/datetime/header/rfc7231") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value }, + headers: { value: value.toISOString() }, }); } @@ -126,7 +126,7 @@ export function _headerUnixTimestampSend( .path("/encode/datetime/header/unix-timestamp") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value }, + headers: { value: value.toISOString() }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts index d69ec85dae..ffff739242 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts @@ -37,7 +37,7 @@ export function _propertyDefaultSend( .path("/encode/datetime/property/default") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value }, + body: { value: value.toISOString() }, }); } @@ -71,7 +71,7 @@ export function _propertyRfc3339Send( .path("/encode/datetime/property/rfc3339") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value }, + body: { value: value.toISOString() }, }); } @@ -105,7 +105,7 @@ export function _propertyRfc7231Send( .path("/encode/datetime/property/rfc7231") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value }, + body: { value: value.toISOString() }, }); } @@ -139,7 +139,7 @@ export function _propertyUnixTimestampSend( .path("/encode/datetime/property/unix-timestamp") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value }, + body: { value: value.toISOString() }, }); } @@ -173,7 +173,7 @@ export function _propertyUnixTimestampArraySend( .path("/encode/datetime/property/unix-timestamp-array") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value }, + body: { value: (value ?? []).map((p) => p.toISOString()) }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts index 99941c34c8..68361f17a1 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts @@ -30,7 +30,7 @@ export function _queryDefaultSend( .path("/encode/datetime/query/default") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value }, + queryParameters: { value: value.toISOString() }, }); } @@ -62,7 +62,7 @@ export function _queryRfc3339Send( .path("/encode/datetime/query/rfc3339") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value }, + queryParameters: { value: value.toISOString() }, }); } @@ -94,7 +94,7 @@ export function _queryRfc7231Send( .path("/encode/datetime/query/rfc7231") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value }, + queryParameters: { value: value.toISOString() }, }); } @@ -126,7 +126,7 @@ export function _queryUnixTimestampSend( .path("/encode/datetime/query/unix-timestamp") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value }, + queryParameters: { value: value.toISOString() }, }); } @@ -158,7 +158,7 @@ export function _queryUnixTimestampArraySend( .path("/encode/datetime/query/unix-timestamp-array") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value }, + queryParameters: { value: (value ?? []).map((p) => p.toISOString()) }, }); } From a34c705cd74c11c8120cf449cd22a5089c72d1eb Mon Sep 17 00:00:00 2001 From: qiaozha Date: Tue, 5 Sep 2023 16:32:24 +0800 Subject: [PATCH 03/17] resolve issues in modular bytes encoding and datetime encoding --- .../typespec-ts/src/modular/buildCodeModel.ts | 68 +++++++++++---- .../src/modular/helpers/operationHelpers.ts | 87 +++++++++++++------ .../src/modular/modularCodeModel.ts | 1 + .../azure/core/src/api/operations.ts | 2 +- .../generated/encode/bytes/src/api/header.ts | 9 +- .../encode/bytes/src/api/property.ts | 8 +- .../generated/encode/bytes/src/api/query.ts | 6 +- .../encode/datetime/src/api/header.ts | 9 +- .../encode/datetime/src/api/property.ts | 8 +- .../encode/datetime/src/api/query.ts | 6 +- .../encode/duration/src/api/header.ts | 1 + .../collection-format/src/api/header.ts | 2 +- .../collection-format/src/api/query.ts | 10 ++- 13 files changed, 149 insertions(+), 68 deletions(-) diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 280def95ea..8e474c7b30 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -154,7 +154,8 @@ function isSimpleType( getMaxValue, getMinLength, getMaxLength, - getPattern + getPattern, + getEncode ]; for (const func of funcs) { if (func(program, type)) { @@ -276,8 +277,7 @@ function getType( options: { disableEffectiveModel?: boolean } = {} ): any { // don't cache simple type(string, int, etc) since decorators may change the result - const enableCache = - !isSimpleType(context.program, type) && !isEmptyModel(type); + const enableCache = !isSimpleType(context.program, type); const effectiveModel = !options.disableEffectiveModel && (type.kind === "Model" || type.kind === "Union") @@ -297,6 +297,9 @@ function getType( newValue = emitType(context, type); } + if (type.kind === "ModelProperty" || type.kind === "Scalar") { + newValue.format = applyEncoding(context.program, type); + } if (enableCache) { typesMap.set(effectiveModel, newValue); if (type.kind === "Union") { @@ -310,14 +313,6 @@ function getType( // need to do properties after insertion to avoid infinite recursion processModelProperties(context, newValue, type); } - } else { - const key = JSON.stringify(newValue); - const value = simpleTypesMap.get(key); - if (value) { - newValue = value; - } else { - simpleTypesMap.set(key, newValue); - } } return newValue; @@ -334,6 +329,7 @@ type ParamBase = { addedOn: string | undefined; clientName: string; inOverload: boolean; + format?: string; }; function emitParamBase( program: Program, @@ -343,12 +339,14 @@ function emitParamBase( let name: string; let description: string = ""; let addedOn: string | undefined; + let format: string | undefined; if (parameter.kind === "ModelProperty") { optional = parameter.optional; name = parameter.name; description = getDocStr(program, parameter); addedOn = getAddedOnVersion(program, parameter); + format = applyEncoding(program, parameter); } else { optional = false; name = "body"; @@ -359,7 +357,8 @@ function emitParamBase( description, addedOn, clientName: applyCasing(name, { casing: CASING }), - inOverload: false + inOverload: false, + format }; } @@ -427,7 +426,6 @@ function emitBodyParameter( const type = getType(context, getBodyType(context.program, httpOperation), { disableEffectiveModel: true }); - if (type.type === "model" && type.name === "") { type.name = capitalize(httpOperation.operation.name) + "Request"; } @@ -451,6 +449,9 @@ function emitParameter( implementation: string ): Parameter { const base = emitParamBase(context.program, parameter.param); + if (base.format === "base64url") { + base; + } let type = getType(context, parameter.param.type); let clientDefaultValue = undefined; if ( @@ -468,7 +469,7 @@ function emitParameter( type: type, implementation: implementation, skipUrlEncoding: parameter.type === "endpointPath", - format: (parameter as any).format + format: (parameter as any).format ?? base.format }; if (paramMap.type.type === "constant") { @@ -859,7 +860,8 @@ function emitProperty( addedOn: getAddedOnVersion(context.program, property), readonly: isReadOnly(context.program, property) || isKey(context.program, property), - clientDefaultValue: clientDefaultValue + clientDefaultValue: clientDefaultValue, + format: applyEncoding(context.program, property) }; } @@ -1025,7 +1027,7 @@ function emitStdScalar( ): Record { switch (scalar.name) { case "bytes": - return { type: "byte-array", format: getEncode(program, scalar) }; + return { type: "byte-array", format: applyEncoding(program, scalar) }; case "int8": case "int16": case "int32": @@ -1049,7 +1051,7 @@ function emitStdScalar( case "plainDate": return { type: "date" }; case "utcDateTime": - return { type: "datetime", format: "date-time" }; + return { type: "datetime", format: applyEncoding(program, scalar) }; case "plainTime": return { type: "time" }; case "duration": @@ -1061,6 +1063,33 @@ function emitStdScalar( } } +function applyEncoding(program: Program, type: Scalar | ModelProperty) { + const encodeData = getEncode(program, type); + if (encodeData) { + return mergeFormatAndEncoding(encodeData.encoding); + // const newTarget = { ...result }; + // const newType = emitScalar(program, encodeData.type); + // newTarget.type = newType["type"]; + // // If the target already has a format it takes priority. (e.g. int32) + // newTarget.format = + // return newTarget; + } + return undefined; +} + +function mergeFormatAndEncoding(encoding: string): string { + switch (encoding) { + + case "rfc7231": + return "utc-date" + case "unixTimestamp": + return "unixtime"; + case "rfc3339": + default: + return "date-time"; + } +} + function applyIntrinsicDecorators( program: Program, type: Scalar | ModelProperty, @@ -1075,7 +1104,7 @@ function applyIntrinsicDecorators( newResult.description = docStr; } - const formatStr = getEncode(program, type); + const formatStr = applyEncoding(program, type); if (isString && !result.format && formatStr) { newResult.format = formatStr; } @@ -1119,7 +1148,8 @@ function applyIntrinsicDecorators( function emitScalar(program: Program, scalar: Scalar): Record { let result: Record = {}; - if (program.checker.isStdType(scalar)) { + const isStd = program.checker.isStdType(scalar); + if (isStd) { result = emitStdScalar(program, scalar); } else if (scalar.baseScalar) { result = emitScalar(program, scalar.baseScalar); diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 583ec6b022..a78b6e0183 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -298,7 +298,9 @@ function getRequestParameters( if (!operation.parameters) { return ""; } - + if (operation.name.endsWith("unixTimestamp") && operation.groupName === "Property") { + operation; + } const operationParameters = operation.parameters.filter( (p) => p.implementation !== "Client" && !isContentType(p) ); @@ -412,7 +414,7 @@ function getParameterMap( } if (hasCollectionFormatInfo((param as any).location, (param as any).format)) { - return getCollectionFormat(param as Parameter); + return getCollectionFormat(param as Parameter, importSet); } // if the parameter or property is optional, we don't need to handle the default value @@ -427,7 +429,10 @@ function getParameterMap( throw new Error(`Parameter ${param.clientName} is not supported`); } -function getCollectionFormat(param: Parameter) { +function getCollectionFormat( + param: Parameter, + importSet: Map> +) { const collectionInfo = getCollectionFormatHelper( param.location, param.format ?? "" @@ -437,10 +442,33 @@ function getCollectionFormat(param: Parameter) { } const isMulti = (param.format ?? "").toLowerCase() === "multi"; const additionalParam = isMulti ? `, "${param.restApiName}"` : ""; - if (!param.optional) { - return `"${param.restApiName}": ${collectionInfo}(${param.clientName}${additionalParam})`; + const serializeHelperImport = importSet.get("../rest/index.js"); + if (serializeHelperImport) { + serializeHelperImport.add(collectionInfo); + } else { + importSet.set( + "../rest/index.js", + new Set().add(collectionInfo) + ); } - return `"${param.restApiName}": options?.${param.clientName} !== undefined ? ${collectionInfo}(options?.${param.clientName}${additionalParam}): undefined`; + if (!param.optional) { + return `"${param.restApiName}": ${collectionInfo}(${serializeRequestValue( + param.type, + param.clientName, + importSet, + true, + param.format + )}${additionalParam})`; + } + return `"${param.restApiName}": options?.${ + param.clientName + } !== undefined ? ${collectionInfo}(${serializeRequestValue( + param.type, + "options?." + param.clientName, + importSet, + true, + param.format + )}${additionalParam}): undefined`; } function isContentType(param: Parameter): boolean { @@ -487,7 +515,8 @@ function getRequired(param: RequiredType, importSet: Map>) { param.type, param.restApiName, importSet, - true + true, + param.format )}`; } @@ -534,7 +563,8 @@ function getOptional(param: OptionalType, importSet: Map>) { param.type, `options?.${param.restApiName}`, importSet, - false + false, + param.format )}`; } @@ -644,7 +674,8 @@ function getRequestModelMapping( property.type, restValue, importSet, - !propertyPath.endsWith("?") + !propertyPath.endsWith("?"), + property.format )}` ); } @@ -761,9 +792,7 @@ function deserializeResponseValue( "p", importSet )}}))`; - } else if ( - type.elementType?.properties?.some((p) => needsDeserialize(p.type)) - ) { + } else if (needsDeserialize(type.elementType)) { return `(${restValue} ?? []).map(p => ${deserializeResponseValue( type.elementType!, "p", @@ -799,17 +828,19 @@ function serializeRequestValue( type: Type, restValue: string, importSet: Map>, - required: boolean + required: boolean, + format?: string ): string { const coreUtilSet = importSet.get("@azure/core-util"); switch (type.type) { case "datetime": - if (type.format === "ISO8601") { + if (format === "date-time") { return `${restValue}.toISOString()`; - } if (type.format === "RFC1123") { - new Date().getTime() - return `${restValue}.toLo()`; - } if (type.format === "UnixTime") { + } + if (format === "utc-date") { + return `${restValue}.toUTCString()`; + } + if (format === "unixtime") { return `${restValue}.getTime()`; } return `${restValue}.toISOString()`; @@ -820,16 +851,13 @@ function serializeRequestValue( "p", importSet )}}))`; - } else if ( - needsDeserialize(type.elementType) - ) { + } else if (needsDeserialize(type.elementType)) { return `(${restValue} ?? []).map(p => ${serializeRequestValue( type.elementType!, "p", importSet, - type.elementType?.nullable !== undefined - ? !type.elementType.nullable - : false + required, + type.elementType?.format )})`; } else { return restValue; @@ -844,9 +872,9 @@ function serializeRequestValue( coreUtilSet.add("uint8ArrayToString"); } return required - ? `uint8ArrayToString(${restValue}, "${type.format ?? "base64"}")` + ? `uint8ArrayToString(${restValue}, "${format ?? "base64"}")` : `${restValue} !== undefined ? uint8ArrayToString(${restValue}, "${ - type.format ?? "base64" + format ?? "base64" }"): undefined`; default: return restValue; @@ -854,7 +882,12 @@ function serializeRequestValue( } function needsDeserialize(type?: Type) { - return type?.type === "datetime" || type?.type === "model"; + return ( + type?.type === "datetime" || + type?.type === "model" || + type?.type === "list" || + type?.type === "byte-array" + ); } export function hasLROOperation(codeModel: ModularCodeModel) { diff --git a/packages/typespec-ts/src/modular/modularCodeModel.ts b/packages/typespec-ts/src/modular/modularCodeModel.ts index b0d65b20e4..3ce025dfed 100644 --- a/packages/typespec-ts/src/modular/modularCodeModel.ts +++ b/packages/typespec-ts/src/modular/modularCodeModel.ts @@ -27,6 +27,7 @@ export interface Property { optional?: boolean; description: string; readonly?: boolean; + format?: string; } export interface BodyParameter { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts index 6feb3389e3..24fa363fc3 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts @@ -5,7 +5,6 @@ import { User, UserListResults, PagedUser } from "../models/models.js"; import { isUnexpected, BasicContext as Client, - buildMultiCollection, CreateOrReplace200Response, CreateOrReplace201Response, CreateOrReplaceDefaultResponse, @@ -29,6 +28,7 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; +import { buildMultiCollection } from "../rest/serializeHelper.js"; import { CreateOrUpdateOptions, CreateOrReplaceOptions, diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts index 9b205cb054..b117f8e016 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts @@ -13,6 +13,7 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; import { uint8ArrayToString } from "@azure/core-util"; +import { buildCsvCollection } from "../rest/serializeHelper.js"; import { HeaderDefaultOptions, HeaderBase64Options, @@ -93,7 +94,7 @@ export function _headerBase64urlSend( .path("/encode/bytes/header/base64url") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: uint8ArrayToString(value, "base64") }, + headers: { value: uint8ArrayToString(value, "base64url") }, }); } @@ -125,7 +126,11 @@ export function _headerBase64urlArraySend( .path("/encode/bytes/header/base64url-array") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: buildCsvCollection(value) }, + headers: { + value: buildCsvCollection( + (value ?? []).map((p) => uint8ArrayToString(p, "base64url")) + ), + }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts index f441f2f773..6149adad43 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts @@ -146,7 +146,9 @@ export function _propertyBase64urlArraySend( .path("/encode/bytes/property/base64url-array") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value }, + body: { + value: (value ?? []).map((p) => uint8ArrayToString(p, "base64url")), + }, }); } @@ -158,7 +160,9 @@ export async function _propertyBase64urlArrayDeserialize( } return { - value: result.body["value"], + value: (result.body["value"] ?? []).map((p) => + typeof p === "string" ? stringToUint8Array(p, "base64url") : p + ), }; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts index fdb3e67e47..fe03bfd668 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts @@ -93,7 +93,7 @@ export function _queryBase64urlSend( .path("/encode/bytes/query/base64url") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: uint8ArrayToString(value, "base64") }, + queryParameters: { value: uint8ArrayToString(value, "base64url") }, }); } @@ -125,7 +125,9 @@ export function _queryBase64urlArraySend( .path("/encode/bytes/query/base64url-array") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value }, + queryParameters: { + value: (value ?? []).map((p) => uint8ArrayToString(p, "base64url")), + }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts index 76feb7bc54..63aeb3c997 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts @@ -13,6 +13,7 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; +import { buildCsvCollection } from "../rest/index.js"; import { HeaderDefaultOptions, HeaderRfc3339Options, @@ -94,7 +95,7 @@ export function _headerRfc7231Send( .path("/encode/datetime/header/rfc7231") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value.toISOString() }, + headers: { value: value.toUTCString() }, }); } @@ -126,7 +127,7 @@ export function _headerUnixTimestampSend( .path("/encode/datetime/header/unix-timestamp") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value.toISOString() }, + headers: { value: value.getTime() }, }); } @@ -158,7 +159,9 @@ export function _headerUnixTimestampArraySend( .path("/encode/datetime/header/unix-timestamp-array") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: buildCsvCollection(value) }, + headers: { + value: buildCsvCollection((value ?? []).map((p) => p.getTime())), + }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts index ffff739242..9f0173a0e4 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts @@ -105,7 +105,7 @@ export function _propertyRfc7231Send( .path("/encode/datetime/property/rfc7231") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value.toISOString() }, + body: { value: value.toUTCString() }, }); } @@ -139,7 +139,7 @@ export function _propertyUnixTimestampSend( .path("/encode/datetime/property/unix-timestamp") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value.toISOString() }, + body: { value: value.getTime() }, }); } @@ -173,7 +173,7 @@ export function _propertyUnixTimestampArraySend( .path("/encode/datetime/property/unix-timestamp-array") .post({ ...operationOptionsToRequestParameters(options), - body: { value: (value ?? []).map((p) => p.toISOString()) }, + body: { value: (value ?? []).map((p) => p.getTime()) }, }); } @@ -185,7 +185,7 @@ export async function _propertyUnixTimestampArrayDeserialize( } return { - value: result.body["value"], + value: (result.body["value"] ?? []).map((p) => new Date(p)), }; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts index 68361f17a1..ffce73a4fe 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts @@ -94,7 +94,7 @@ export function _queryRfc7231Send( .path("/encode/datetime/query/rfc7231") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value.toISOString() }, + queryParameters: { value: value.toUTCString() }, }); } @@ -126,7 +126,7 @@ export function _queryUnixTimestampSend( .path("/encode/datetime/query/unix-timestamp") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value.toISOString() }, + queryParameters: { value: value.getTime() }, }); } @@ -158,7 +158,7 @@ export function _queryUnixTimestampArraySend( .path("/encode/datetime/query/unix-timestamp-array") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: (value ?? []).map((p) => p.toISOString()) }, + queryParameters: { value: (value ?? []).map((p) => p.getTime()) }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts index 42bb25e523..eb27905175 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts @@ -13,6 +13,7 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; +import { buildCsvCollection } from "../rest/serializeHelper.js"; import { HeaderDefaultOptions, HeaderIso8601Options, diff --git a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts index 82d2b7daf5..57d8b05924 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts @@ -2,7 +2,6 @@ // Licensed under the MIT license. import { - buildCsvCollection, CollectionFormatContext as Client, HeaderCsv204Response, } from "../rest/index.js"; @@ -10,6 +9,7 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; +import { buildCsvCollection } from "../rest/serializeHelper.js"; import { HeaderCsvOptions } from "../models/options.js"; export function _headerCsvSend( diff --git a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts index 6cb204b48f..7cf32f9ce3 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts @@ -2,10 +2,6 @@ // Licensed under the MIT license. import { - buildMultiCollection, - buildPipeCollection, - buildSsvCollection, - buildTsvCollection, CollectionFormatContext as Client, QueryCsv204Response, QueryMulti204Response, @@ -17,6 +13,12 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; +import { + buildMultiCollection, + buildSsvCollection, + buildTsvCollection, + buildPipeCollection, +} from "../rest/serializeHelper.js"; import { QueryMultiOptions, QuerySsvOptions, From 0389af58f6e92fa4b8f242c74e36ae06ace8a008 Mon Sep 17 00:00:00 2001 From: qiaozha Date: Tue, 5 Sep 2023 19:12:46 +0800 Subject: [PATCH 04/17] reserve work --- packages/rlc-common/src/buildIndexFile.ts | 3 +- .../typespec-ts/src/modular/buildCodeModel.ts | 80 ++++++++++++------- .../src/modular/helpers/operationHelpers.ts | 3 - packages/typespec-ts/src/utils/modelUtils.ts | 8 +- .../modularIntegration/encodeBytes.spec.ts | 2 +- .../encode/datetime/src/rest/index.ts | 1 + .../encode/duration/src/DurationClient.ts | 36 ++++----- .../encode/duration/src/api/header.ts | 22 ++--- .../encode/duration/src/api/property.ts | 20 ++--- .../encode/duration/src/api/query.ts | 20 ++--- .../encode/duration/src/models/models.ts | 10 +-- .../encode/duration/src/rest/index.ts | 1 + 12 files changed, 114 insertions(+), 92 deletions(-) diff --git a/packages/rlc-common/src/buildIndexFile.ts b/packages/rlc-common/src/buildIndexFile.ts index cfc029164e..634b16039c 100644 --- a/packages/rlc-common/src/buildIndexFile.ts +++ b/packages/rlc-common/src/buildIndexFile.ts @@ -311,7 +311,8 @@ function generateRLCIndex(file: SourceFile, model: RLCModel) { hasMultiCollection(model) || hasSsvCollection(model) || hasPipeCollection(model) || - hasTsvCollection(model) + hasTsvCollection(model) || + hasCsvCollection(model) ) { file.addExportDeclarations([ { diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 8e474c7b30..156b9f9c0d 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -298,7 +298,7 @@ function getType( } if (type.kind === "ModelProperty" || type.kind === "Scalar") { - newValue.format = applyEncoding(context.program, type); + newValue.format = applyEncoding(context.program, type, newValue).format; } if (enableCache) { typesMap.set(effectiveModel, newValue); @@ -346,7 +346,7 @@ function emitParamBase( name = parameter.name; description = getDocStr(program, parameter); addedOn = getAddedOnVersion(program, parameter); - format = applyEncoding(program, parameter); + format = applyEncoding(program, parameter).format; } else { optional = false; name = "body"; @@ -861,7 +861,7 @@ function emitProperty( readonly: isReadOnly(context.program, property) || isKey(context.program, property), clientDefaultValue: clientDefaultValue, - format: applyEncoding(context.program, property) + format: applyEncoding(context.program, property).format }; } @@ -1025,9 +1025,10 @@ function emitStdScalar( program: Program, scalar: Scalar & { name: IntrinsicScalarName } ): Record { - switch (scalar.name) { + const newScalar = applyEncoding(program, scalar); + switch (newScalar.name) { case "bytes": - return { type: "byte-array", format: applyEncoding(program, scalar) }; + return { type: "byte-array", format: newScalar.format }; case "int8": case "int16": case "int32": @@ -1051,11 +1052,11 @@ function emitStdScalar( case "plainDate": return { type: "date" }; case "utcDateTime": - return { type: "datetime", format: applyEncoding(program, scalar) }; + return { type: "datetime", format: newScalar.format }; case "plainTime": return { type: "time" }; case "duration": - return { type: "duration" }; + return { type: "duration", format: newScalar.format }; case "numeric": return {}; // Waiting on design for more precise type https://github.com/microsoft/cadl/issues/1260 default: @@ -1063,30 +1064,55 @@ function emitStdScalar( } } -function applyEncoding(program: Program, type: Scalar | ModelProperty) { - const encodeData = getEncode(program, type); +function applyEncoding( + program: Program, + typespecType: Scalar | ModelProperty, + target: any = {} +) { + const encodeData = getEncode(program, typespecType); if (encodeData) { - return mergeFormatAndEncoding(encodeData.encoding); - // const newTarget = { ...result }; - // const newType = emitScalar(program, encodeData.type); - // newTarget.type = newType["type"]; - // // If the target already has a format it takes priority. (e.g. int32) - // newTarget.format = - // return newTarget; + const newTarget = { ...target }; + const newType = emitScalar(program, encodeData.type); + newTarget["type"] = newType["type"]; + // If the target already has a format it takes priority. (e.g. int32) + newTarget["format"] = mergeFormatAndEncoding( + newTarget.format, + encodeData.encoding, + newType["format"] + ); + return newTarget; } - return undefined; + return target; } -function mergeFormatAndEncoding(encoding: string): string { - switch (encoding) { - - case "rfc7231": - return "utc-date" - case "unixTimestamp": - return "unixtime"; - case "rfc3339": +function mergeFormatAndEncoding( + format: string | undefined, + encoding: string, + encodeAsFormat: string | undefined +): string { + switch (format) { + case undefined: + return encodeAsFormat ?? encoding; + case "date-time": + switch (encoding) { + case "rfc3339": + return "date-time"; + case "unixTimestamp": + return "unixtime"; + case "rfc7231": + return "utc-date"; + default: + return encoding; + } + case "duration": + switch (encoding) { + case "ISO8601": + return "duration"; + default: + return encodeAsFormat ?? encoding; + } default: - return "date-time"; + return encodeAsFormat ?? encoding; } } @@ -1104,7 +1130,7 @@ function applyIntrinsicDecorators( newResult.description = docStr; } - const formatStr = applyEncoding(program, type); + const formatStr = applyEncoding(program, type, newResult).format; if (isString && !result.format && formatStr) { newResult.format = formatStr; } diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index a78b6e0183..09759c8c72 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -298,9 +298,6 @@ function getRequestParameters( if (!operation.parameters) { return ""; } - if (operation.name.endsWith("unixTimestamp") && operation.groupName === "Property") { - operation; - } const operationParameters = operation.parameters.filter( (p) => p.implementation !== "Client" && !isContentType(p) ); diff --git a/packages/typespec-ts/src/utils/modelUtils.ts b/packages/typespec-ts/src/utils/modelUtils.ts index 7c623002c4..deb02f8d77 100644 --- a/packages/typespec-ts/src/utils/modelUtils.ts +++ b/packages/typespec-ts/src/utils/modelUtils.ts @@ -900,10 +900,12 @@ function getSchemaForStdScalar( * if absent use typespec type (or default way of serializing that type) * if present respect type provided in @encode */ + let format = undefined; if (relevantProperty) { const encodeData = getEncode(program, relevantProperty); if (encodeData && isEncodeTypeEffective(type, encodeData)) { type = encodeData.type; + format = encodeData.encoding; } } const name = type.name; @@ -984,7 +986,7 @@ function getSchemaForStdScalar( case "plainDate": return { type: "string", - format: "date", + format, description, typeName: "Date | string", outputTypeName: "string" @@ -992,7 +994,7 @@ function getSchemaForStdScalar( case "utcDateTime": return { type: "string", - format: "date-time", + format, description, typeName: "Date | string", outputTypeName: "string" @@ -1014,7 +1016,7 @@ function getSchemaForStdScalar( outputTypeName: "string" }; case "duration": - return { type: "string", format: "duration", description }; + return { type: "string", format, description }; } } diff --git a/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts index 7a4d37d223..051b614f6c 100644 --- a/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts @@ -1,7 +1,7 @@ import { assert } from "chai"; import { BytesClient } from "./generated/encode/bytes/src/index"; import { stringToUint8Array } from "@azure/core-util"; -describe("EncodeDatetimeClient Rest Client", () => { +describe.only("EncodeDatetimeClient Rest Client", () => { let client: BytesClient; beforeEach(() => { diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/index.ts index 968ba66f03..f795d62955 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/index.ts @@ -9,5 +9,6 @@ export * from "./responses.js"; export * from "./clientDefinitions.js"; export * from "./models.js"; export * from "./outputModels.js"; +export * from "./serializeHelper.js"; export default DatetimeClient; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts index 81632e75d7..6a9bd0fc8f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts @@ -57,26 +57,26 @@ export class DurationClient { } query = { - default: (input: string, options?: QueryDefaultOptions): Promise => { + default: (input: any, options?: QueryDefaultOptions): Promise => { return queryDefault(this._client, input, options); }, - iso8601: (input: string, options?: QueryIso8601Options): Promise => { + iso8601: (input: any, options?: QueryIso8601Options): Promise => { return queryIso8601(this._client, input, options); }, int32Seconds: ( - input: string, + input: any, options?: QueryInt32SecondsOptions ): Promise => { return queryInt32Seconds(this._client, input, options); }, floatSeconds: ( - input: string, + input: any, options?: QueryFloatSecondsOptions ): Promise => { return queryFloatSeconds(this._client, input, options); }, int32SecondsArray: ( - input: string[], + input: any[], options?: QueryInt32SecondsArrayOptions ): Promise => { return queryInt32SecondsArray(this._client, input, options); @@ -84,63 +84,57 @@ export class DurationClient { }; property = { default: ( - value: string, + value: any, options?: PropertyDefaultOptions ): Promise => { return propertyDefault(this._client, value, options); }, iso8601: ( - value: string, + value: any, options?: PropertyIso8601Options ): Promise => { return propertyIso8601(this._client, value, options); }, int32Seconds: ( - value: string, + value: any, options?: PropertyInt32SecondsOptions ): Promise => { return propertyInt32Seconds(this._client, value, options); }, floatSeconds: ( - value: string, + value: any, options?: PropertyFloatSecondsOptions ): Promise => { return propertyFloatSeconds(this._client, value, options); }, floatSecondsArray: ( - value: string[], + value: any[], options?: PropertyFloatSecondsArrayOptions ): Promise => { return propertyFloatSecondsArray(this._client, value, options); }, }; header = { - default: ( - duration: string, - options?: HeaderDefaultOptions - ): Promise => { + default: (duration: any, options?: HeaderDefaultOptions): Promise => { return headerDefault(this._client, duration, options); }, - iso8601: ( - duration: string, - options?: HeaderIso8601Options - ): Promise => { + iso8601: (duration: any, options?: HeaderIso8601Options): Promise => { return headerIso8601(this._client, duration, options); }, iso8601Array: ( - duration: string[], + duration: any[], options?: HeaderIso8601ArrayOptions ): Promise => { return headerIso8601Array(this._client, duration, options); }, int32Seconds: ( - duration: string, + duration: any, options?: HeaderInt32SecondsOptions ): Promise => { return headerInt32Seconds(this._client, duration, options); }, floatSeconds: ( - duration: string, + duration: any, options?: HeaderFloatSecondsOptions ): Promise => { return headerFloatSeconds(this._client, duration, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts index eb27905175..1bd667d72a 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts @@ -13,7 +13,7 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { buildCsvCollection } from "../rest/serializeHelper.js"; +import { buildCsvCollection } from "../rest/index.js"; import { HeaderDefaultOptions, HeaderIso8601Options, @@ -24,7 +24,7 @@ import { export function _headerDefaultSend( context: Client, - duration: string, + duration: any, options: HeaderDefaultOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -47,7 +47,7 @@ export async function _headerDefaultDeserialize( export async function headerDefault( context: Client, - duration: string, + duration: any, options: HeaderDefaultOptions = { requestOptions: {} } ): Promise { const result = await _headerDefaultSend(context, duration, options); @@ -56,7 +56,7 @@ export async function headerDefault( export function _headerIso8601Send( context: Client, - duration: string, + duration: any, options: HeaderIso8601Options = { requestOptions: {} } ): StreamableMethod { return context @@ -79,7 +79,7 @@ export async function _headerIso8601Deserialize( export async function headerIso8601( context: Client, - duration: string, + duration: any, options: HeaderIso8601Options = { requestOptions: {} } ): Promise { const result = await _headerIso8601Send(context, duration, options); @@ -88,7 +88,7 @@ export async function headerIso8601( export function _headerIso8601ArraySend( context: Client, - duration: string[], + duration: any[], options: HeaderIso8601ArrayOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -111,7 +111,7 @@ export async function _headerIso8601ArrayDeserialize( export async function headerIso8601Array( context: Client, - duration: string[], + duration: any[], options: HeaderIso8601ArrayOptions = { requestOptions: {} } ): Promise { const result = await _headerIso8601ArraySend(context, duration, options); @@ -120,7 +120,7 @@ export async function headerIso8601Array( export function _headerInt32SecondsSend( context: Client, - duration: string, + duration: any, options: HeaderInt32SecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -143,7 +143,7 @@ export async function _headerInt32SecondsDeserialize( export async function headerInt32Seconds( context: Client, - duration: string, + duration: any, options: HeaderInt32SecondsOptions = { requestOptions: {} } ): Promise { const result = await _headerInt32SecondsSend(context, duration, options); @@ -152,7 +152,7 @@ export async function headerInt32Seconds( export function _headerFloatSecondsSend( context: Client, - duration: string, + duration: any, options: HeaderFloatSecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -175,7 +175,7 @@ export async function _headerFloatSecondsDeserialize( export async function headerFloatSeconds( context: Client, - duration: string, + duration: any, options: HeaderFloatSecondsOptions = { requestOptions: {} } ): Promise { const result = await _headerFloatSecondsSend(context, duration, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts index 6078800421..60202c7be4 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts @@ -30,7 +30,7 @@ import { export function _propertyDefaultSend( context: Client, - value: string, + value: any, options: PropertyDefaultOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -55,7 +55,7 @@ export async function _propertyDefaultDeserialize( export async function propertyDefault( context: Client, - value: string, + value: any, options: PropertyDefaultOptions = { requestOptions: {} } ): Promise { const result = await _propertyDefaultSend(context, value, options); @@ -64,7 +64,7 @@ export async function propertyDefault( export function _propertyIso8601Send( context: Client, - value: string, + value: any, options: PropertyIso8601Options = { requestOptions: {} } ): StreamableMethod { return context @@ -89,7 +89,7 @@ export async function _propertyIso8601Deserialize( export async function propertyIso8601( context: Client, - value: string, + value: any, options: PropertyIso8601Options = { requestOptions: {} } ): Promise { const result = await _propertyIso8601Send(context, value, options); @@ -98,7 +98,7 @@ export async function propertyIso8601( export function _propertyInt32SecondsSend( context: Client, - value: string, + value: any, options: PropertyInt32SecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -123,7 +123,7 @@ export async function _propertyInt32SecondsDeserialize( export async function propertyInt32Seconds( context: Client, - value: string, + value: any, options: PropertyInt32SecondsOptions = { requestOptions: {} } ): Promise { const result = await _propertyInt32SecondsSend(context, value, options); @@ -132,7 +132,7 @@ export async function propertyInt32Seconds( export function _propertyFloatSecondsSend( context: Client, - value: string, + value: any, options: PropertyFloatSecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -157,7 +157,7 @@ export async function _propertyFloatSecondsDeserialize( export async function propertyFloatSeconds( context: Client, - value: string, + value: any, options: PropertyFloatSecondsOptions = { requestOptions: {} } ): Promise { const result = await _propertyFloatSecondsSend(context, value, options); @@ -166,7 +166,7 @@ export async function propertyFloatSeconds( export function _propertyFloatSecondsArraySend( context: Client, - value: string[], + value: any[], options: PropertyFloatSecondsArrayOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -191,7 +191,7 @@ export async function _propertyFloatSecondsArrayDeserialize( export async function propertyFloatSecondsArray( context: Client, - value: string[], + value: any[], options: PropertyFloatSecondsArrayOptions = { requestOptions: {} } ): Promise { const result = await _propertyFloatSecondsArraySend(context, value, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts index 2b18a69d3c..c38c8a484c 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts @@ -23,7 +23,7 @@ import { export function _queryDefaultSend( context: Client, - input: string, + input: any, options: QueryDefaultOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -46,7 +46,7 @@ export async function _queryDefaultDeserialize( export async function queryDefault( context: Client, - input: string, + input: any, options: QueryDefaultOptions = { requestOptions: {} } ): Promise { const result = await _queryDefaultSend(context, input, options); @@ -55,7 +55,7 @@ export async function queryDefault( export function _queryIso8601Send( context: Client, - input: string, + input: any, options: QueryIso8601Options = { requestOptions: {} } ): StreamableMethod { return context @@ -78,7 +78,7 @@ export async function _queryIso8601Deserialize( export async function queryIso8601( context: Client, - input: string, + input: any, options: QueryIso8601Options = { requestOptions: {} } ): Promise { const result = await _queryIso8601Send(context, input, options); @@ -87,7 +87,7 @@ export async function queryIso8601( export function _queryInt32SecondsSend( context: Client, - input: string, + input: any, options: QueryInt32SecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -110,7 +110,7 @@ export async function _queryInt32SecondsDeserialize( export async function queryInt32Seconds( context: Client, - input: string, + input: any, options: QueryInt32SecondsOptions = { requestOptions: {} } ): Promise { const result = await _queryInt32SecondsSend(context, input, options); @@ -119,7 +119,7 @@ export async function queryInt32Seconds( export function _queryFloatSecondsSend( context: Client, - input: string, + input: any, options: QueryFloatSecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -142,7 +142,7 @@ export async function _queryFloatSecondsDeserialize( export async function queryFloatSeconds( context: Client, - input: string, + input: any, options: QueryFloatSecondsOptions = { requestOptions: {} } ): Promise { const result = await _queryFloatSecondsSend(context, input, options); @@ -151,7 +151,7 @@ export async function queryFloatSeconds( export function _queryInt32SecondsArraySend( context: Client, - input: string[], + input: any[], options: QueryInt32SecondsArrayOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -174,7 +174,7 @@ export async function _queryInt32SecondsArrayDeserialize( export async function queryInt32SecondsArray( context: Client, - input: string[], + input: any[], options: QueryInt32SecondsArrayOptions = { requestOptions: {} } ): Promise { const result = await _queryInt32SecondsArraySend(context, input, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts index 2f6b1086e3..6757a1c4de 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts @@ -2,21 +2,21 @@ // Licensed under the MIT license. export interface DefaultDurationProperty { - value: string; + value: any; } export interface ISO8601DurationProperty { - value: string; + value: any; } export interface Int32SecondsDurationProperty { - value: string; + value: any; } export interface FloatSecondsDurationProperty { - value: string; + value: any; } export interface FloatSecondsDurationArrayProperty { - value: string[]; + value: any[]; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/index.ts index 7f411a2b28..2b00de3f97 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/index.ts @@ -9,5 +9,6 @@ export * from "./responses.js"; export * from "./clientDefinitions.js"; export * from "./models.js"; export * from "./outputModels.js"; +export * from "./serializeHelper.js"; export default DurationClient; From 4a5e433a34990b05830274a6243f755a1e3da94f Mon Sep 17 00:00:00 2001 From: qiaozha Date: Wed, 6 Sep 2023 16:04:22 +0800 Subject: [PATCH 05/17] reserve work --- .../typespec-ts/src/modular/buildCodeModel.ts | 60 +++++++++---------- .../src/modular/helpers/operationHelpers.ts | 17 ++++-- .../src/modular/helpers/typeHelpers.ts | 8 ++- .../azure/core/src/api/operations.ts | 2 +- .../generated/encode/bytes/src/api/header.ts | 2 +- .../encode/bytes/src/api/property.ts | 4 +- .../generated/encode/bytes/src/rest/index.ts | 1 + .../encode/datetime/src/api/header.ts | 6 +- .../encode/datetime/src/api/property.ts | 6 +- .../encode/datetime/src/api/query.ts | 6 +- .../encode/duration/src/DurationClient.ts | 36 ++++++----- .../encode/duration/src/api/header.ts | 20 +++---- .../encode/duration/src/api/property.ts | 20 +++---- .../encode/duration/src/api/query.ts | 20 +++---- .../encode/duration/src/models/models.ts | 10 ++-- .../collection-format/src/api/header.ts | 2 +- .../collection-format/src/api/query.ts | 2 +- 17 files changed, 120 insertions(+), 102 deletions(-) diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 156b9f9c0d..677be88762 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -298,8 +298,9 @@ function getType( } if (type.kind === "ModelProperty" || type.kind === "Scalar") { - newValue.format = applyEncoding(context.program, type, newValue).format; + newValue = applyEncoding(context.program, type, newValue); } + if (enableCache) { typesMap.set(effectiveModel, newValue); if (type.kind === "Union") { @@ -342,11 +343,12 @@ function emitParamBase( let format: string | undefined; if (parameter.kind === "ModelProperty") { - optional = parameter.optional; - name = parameter.name; - description = getDocStr(program, parameter); - addedOn = getAddedOnVersion(program, parameter); - format = applyEncoding(program, parameter).format; + const newParameter = applyEncoding(program, parameter, parameter); + optional = newParameter.optional; + name = newParameter.name; + description = getDocStr(program, newParameter); + addedOn = getAddedOnVersion(program, newParameter); + format = newParameter.format; } else { optional = false; name = "body"; @@ -449,9 +451,6 @@ function emitParameter( implementation: string ): Parameter { const base = emitParamBase(context.program, parameter.param); - if (base.format === "base64url") { - base; - } let type = getType(context, parameter.param.type); let clientDefaultValue = undefined; if ( @@ -466,7 +465,7 @@ function emitParameter( const paramMap: any = { restApiName: parameter.name, location: parameter.type, - type: type, + type, implementation: implementation, skipUrlEncoding: parameter.type === "endpointPath", format: (parameter as any).format ?? base.format @@ -828,40 +827,42 @@ function emitProperty( context: SdkContext, property: ModelProperty ): Record { + const newProperty = applyEncoding(context.program, property, property); let clientDefaultValue = undefined; - const propertyDefaultKind = property.default?.kind; + const propertyDefaultKind = newProperty.default?.kind; if ( - property.default && + newProperty.default && (propertyDefaultKind === "Number" || propertyDefaultKind === "String" || propertyDefaultKind === "Boolean") ) { - clientDefaultValue = property.default.value; + clientDefaultValue = newProperty.default.value; } if (propertyDefaultKind === "EnumMember") { - clientDefaultValue = property.default.value ?? property.default.name; + clientDefaultValue = newProperty.default.value ?? newProperty.default.name; } // const [clientName, jsonName] = getPropertyNames(context, property); - const clientName = property.name; + const clientName = newProperty.name; const jsonName = - getProjectedName(context.program, property, "json") ?? property.name; + getProjectedName(context.program, newProperty, "json") ?? newProperty.name; - if (property.model) { - getType(context, property.model); + if (newProperty.model) { + getType(context, newProperty.model); } return { clientName: applyCasing(clientName, { casing: CASING }), restApiName: jsonName, type: getType(context, property.type), - optional: property.optional, - description: getDocStr(context.program, property), - addedOn: getAddedOnVersion(context.program, property), + optional: newProperty.optional, + description: getDocStr(context.program, newProperty), + addedOn: getAddedOnVersion(context.program, newProperty), readonly: - isReadOnly(context.program, property) || isKey(context.program, property), + isReadOnly(context.program, newProperty) || + isKey(context.program, newProperty), clientDefaultValue: clientDefaultValue, - format: applyEncoding(context.program, property).format + format: newProperty.format }; } @@ -1025,8 +1026,8 @@ function emitStdScalar( program: Program, scalar: Scalar & { name: IntrinsicScalarName } ): Record { - const newScalar = applyEncoding(program, scalar); - switch (newScalar.name) { + const newScalar = applyEncoding(program, scalar, scalar); + switch (scalar.name) { case "bytes": return { type: "byte-array", format: newScalar.format }; case "int8": @@ -1073,7 +1074,7 @@ function applyEncoding( if (encodeData) { const newTarget = { ...target }; const newType = emitScalar(program, encodeData.type); - newTarget["type"] = newType["type"]; + // newTarget["type"] = newType["type"]; // If the target already has a format it takes priority. (e.g. int32) newTarget["format"] = mergeFormatAndEncoding( newTarget.format, @@ -1121,7 +1122,7 @@ function applyIntrinsicDecorators( type: Scalar | ModelProperty, result: any ): Record { - const newResult = { ...result }; + let newResult = { ...result }; const docStr = getDoc(program, type); const isString = isStringType(program, getPropertyType(type)); const isNumeric = isNumericType(program, getPropertyType(type)); @@ -1130,10 +1131,7 @@ function applyIntrinsicDecorators( newResult.description = docStr; } - const formatStr = applyEncoding(program, type, newResult).format; - if (isString && !result.format && formatStr) { - newResult.format = formatStr; - } + newResult = applyEncoding(program, type, newResult); const pattern = getPattern(program, type); if (isString && !result.pattern && pattern) { diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 09759c8c72..28f93cfe67 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -148,7 +148,8 @@ export function getDeserializePrivateFunction( response.type, "result.body", importSet, - response.type.nullable !== undefined ? !response.type.nullable : false + response.type.nullable !== undefined ? !response.type.nullable : false, + response.type.format )}` ); } else if (response?.type?.properties) { @@ -295,6 +296,9 @@ function getRequestParameters( operation: Operation, importSet: Map> ): string { + if (operation.name.endsWith("int32Seconds") && operation.groupName === "Header") { + operation; + } if (!operation.parameters) { return ""; } @@ -753,7 +757,8 @@ export function getResponseMapping( property.type, restValue, importSet, - property.optional !== undefined ? !property.optional : false + property.optional !== undefined ? !property.optional : false, + property.format )}` ); } @@ -772,7 +777,8 @@ function deserializeResponseValue( type: Type, restValue: string, importSet: Map>, - required: boolean + required: boolean, + format?: string ): string { const coreUtilSet = importSet.get("@azure/core-util"); switch (type.type) { @@ -794,7 +800,8 @@ function deserializeResponseValue( type.elementType!, "p", importSet, - required + required, + type.elementType?.format )})`; } else { return restValue; @@ -809,7 +816,7 @@ function deserializeResponseValue( coreUtilSet.add("stringToUint8Array"); } return `typeof ${restValue} === 'string' - ? stringToUint8Array(${restValue}, "${type.format ?? "base64"}") + ? stringToUint8Array(${restValue}, "${format ?? "base64"}") : ${restValue}`; default: return restValue; diff --git a/packages/typespec-ts/src/modular/helpers/typeHelpers.ts b/packages/typespec-ts/src/modular/helpers/typeHelpers.ts index 78bc5f60b3..3c108d1728 100644 --- a/packages/typespec-ts/src/modular/helpers/typeHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/typeHelpers.ts @@ -73,7 +73,13 @@ export function getType(type: Type): TypeMetadata { }; case "string": case "duration": - return { name: getNullableType("string", type) }; + switch (type.format) { + case "seconds": + return { name: getNullableType("number", type) }; + case "ISO8601": + default: + return { name: getNullableType("string", type) }; + } case "combined": { if (!type.types) { throw new Error("Unable to process combined without combinedTypes"); diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts index 24fa363fc3..de81b927fa 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts @@ -28,7 +28,7 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { buildMultiCollection } from "../rest/serializeHelper.js"; +import { buildMultiCollection } from "../rest/index.js"; import { CreateOrUpdateOptions, CreateOrReplaceOptions, diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts index b117f8e016..622c76bf44 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts @@ -13,7 +13,7 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; import { uint8ArrayToString } from "@azure/core-util"; -import { buildCsvCollection } from "../rest/serializeHelper.js"; +import { buildCsvCollection } from "../rest/index.js"; import { HeaderDefaultOptions, HeaderBase64Options, diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts index 6149adad43..0f345df264 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts @@ -109,7 +109,7 @@ export function _propertyBase64urlSend( .path("/encode/bytes/property/base64url") .post({ ...operationOptionsToRequestParameters(options), - body: { value: uint8ArrayToString(value, "base64") }, + body: { value: uint8ArrayToString(value, "base64url") }, }); } @@ -123,7 +123,7 @@ export async function _propertyBase64urlDeserialize( return { value: typeof result.body["value"] === "string" - ? stringToUint8Array(result.body["value"], "base64") + ? stringToUint8Array(result.body["value"], "base64url") : result.body["value"], }; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/index.ts index ae094eae02..65eda613f6 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/index.ts @@ -9,5 +9,6 @@ export * from "./responses.js"; export * from "./clientDefinitions.js"; export * from "./models.js"; export * from "./outputModels.js"; +export * from "./serializeHelper.js"; export default BytesClient; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts index 63aeb3c997..cfffae3480 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts @@ -95,7 +95,7 @@ export function _headerRfc7231Send( .path("/encode/datetime/header/rfc7231") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value.toUTCString() }, + headers: { value: value.toISOString() }, }); } @@ -127,7 +127,7 @@ export function _headerUnixTimestampSend( .path("/encode/datetime/header/unix-timestamp") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value.getTime() }, + headers: { value: value.toISOString() }, }); } @@ -160,7 +160,7 @@ export function _headerUnixTimestampArraySend( .get({ ...operationOptionsToRequestParameters(options), headers: { - value: buildCsvCollection((value ?? []).map((p) => p.getTime())), + value: buildCsvCollection((value ?? []).map((p) => p.toISOString())), }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts index 9f0173a0e4..0ff4a2267a 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts @@ -105,7 +105,7 @@ export function _propertyRfc7231Send( .path("/encode/datetime/property/rfc7231") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value.toUTCString() }, + body: { value: value.toISOString() }, }); } @@ -139,7 +139,7 @@ export function _propertyUnixTimestampSend( .path("/encode/datetime/property/unix-timestamp") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value.getTime() }, + body: { value: value.toISOString() }, }); } @@ -173,7 +173,7 @@ export function _propertyUnixTimestampArraySend( .path("/encode/datetime/property/unix-timestamp-array") .post({ ...operationOptionsToRequestParameters(options), - body: { value: (value ?? []).map((p) => p.getTime()) }, + body: { value: (value ?? []).map((p) => p.toISOString()) }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts index ffce73a4fe..68361f17a1 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts @@ -94,7 +94,7 @@ export function _queryRfc7231Send( .path("/encode/datetime/query/rfc7231") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value.toUTCString() }, + queryParameters: { value: value.toISOString() }, }); } @@ -126,7 +126,7 @@ export function _queryUnixTimestampSend( .path("/encode/datetime/query/unix-timestamp") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value.getTime() }, + queryParameters: { value: value.toISOString() }, }); } @@ -158,7 +158,7 @@ export function _queryUnixTimestampArraySend( .path("/encode/datetime/query/unix-timestamp-array") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: (value ?? []).map((p) => p.getTime()) }, + queryParameters: { value: (value ?? []).map((p) => p.toISOString()) }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts index 6a9bd0fc8f..37504dda35 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts @@ -57,26 +57,26 @@ export class DurationClient { } query = { - default: (input: any, options?: QueryDefaultOptions): Promise => { + default: (input: string, options?: QueryDefaultOptions): Promise => { return queryDefault(this._client, input, options); }, - iso8601: (input: any, options?: QueryIso8601Options): Promise => { + iso8601: (input: string, options?: QueryIso8601Options): Promise => { return queryIso8601(this._client, input, options); }, int32Seconds: ( - input: any, + input: string, options?: QueryInt32SecondsOptions ): Promise => { return queryInt32Seconds(this._client, input, options); }, floatSeconds: ( - input: any, + input: string, options?: QueryFloatSecondsOptions ): Promise => { return queryFloatSeconds(this._client, input, options); }, int32SecondsArray: ( - input: any[], + input: number[], options?: QueryInt32SecondsArrayOptions ): Promise => { return queryInt32SecondsArray(this._client, input, options); @@ -84,57 +84,63 @@ export class DurationClient { }; property = { default: ( - value: any, + value: string, options?: PropertyDefaultOptions ): Promise => { return propertyDefault(this._client, value, options); }, iso8601: ( - value: any, + value: string, options?: PropertyIso8601Options ): Promise => { return propertyIso8601(this._client, value, options); }, int32Seconds: ( - value: any, + value: string, options?: PropertyInt32SecondsOptions ): Promise => { return propertyInt32Seconds(this._client, value, options); }, floatSeconds: ( - value: any, + value: string, options?: PropertyFloatSecondsOptions ): Promise => { return propertyFloatSeconds(this._client, value, options); }, floatSecondsArray: ( - value: any[], + value: number[], options?: PropertyFloatSecondsArrayOptions ): Promise => { return propertyFloatSecondsArray(this._client, value, options); }, }; header = { - default: (duration: any, options?: HeaderDefaultOptions): Promise => { + default: ( + duration: string, + options?: HeaderDefaultOptions + ): Promise => { return headerDefault(this._client, duration, options); }, - iso8601: (duration: any, options?: HeaderIso8601Options): Promise => { + iso8601: ( + duration: string, + options?: HeaderIso8601Options + ): Promise => { return headerIso8601(this._client, duration, options); }, iso8601Array: ( - duration: any[], + duration: string[], options?: HeaderIso8601ArrayOptions ): Promise => { return headerIso8601Array(this._client, duration, options); }, int32Seconds: ( - duration: any, + duration: string, options?: HeaderInt32SecondsOptions ): Promise => { return headerInt32Seconds(this._client, duration, options); }, floatSeconds: ( - duration: any, + duration: string, options?: HeaderFloatSecondsOptions ): Promise => { return headerFloatSeconds(this._client, duration, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts index 1bd667d72a..a8412d9478 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts @@ -24,7 +24,7 @@ import { export function _headerDefaultSend( context: Client, - duration: any, + duration: string, options: HeaderDefaultOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -47,7 +47,7 @@ export async function _headerDefaultDeserialize( export async function headerDefault( context: Client, - duration: any, + duration: string, options: HeaderDefaultOptions = { requestOptions: {} } ): Promise { const result = await _headerDefaultSend(context, duration, options); @@ -56,7 +56,7 @@ export async function headerDefault( export function _headerIso8601Send( context: Client, - duration: any, + duration: string, options: HeaderIso8601Options = { requestOptions: {} } ): StreamableMethod { return context @@ -79,7 +79,7 @@ export async function _headerIso8601Deserialize( export async function headerIso8601( context: Client, - duration: any, + duration: string, options: HeaderIso8601Options = { requestOptions: {} } ): Promise { const result = await _headerIso8601Send(context, duration, options); @@ -88,7 +88,7 @@ export async function headerIso8601( export function _headerIso8601ArraySend( context: Client, - duration: any[], + duration: string[], options: HeaderIso8601ArrayOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -111,7 +111,7 @@ export async function _headerIso8601ArrayDeserialize( export async function headerIso8601Array( context: Client, - duration: any[], + duration: string[], options: HeaderIso8601ArrayOptions = { requestOptions: {} } ): Promise { const result = await _headerIso8601ArraySend(context, duration, options); @@ -120,7 +120,7 @@ export async function headerIso8601Array( export function _headerInt32SecondsSend( context: Client, - duration: any, + duration: string, options: HeaderInt32SecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -143,7 +143,7 @@ export async function _headerInt32SecondsDeserialize( export async function headerInt32Seconds( context: Client, - duration: any, + duration: string, options: HeaderInt32SecondsOptions = { requestOptions: {} } ): Promise { const result = await _headerInt32SecondsSend(context, duration, options); @@ -152,7 +152,7 @@ export async function headerInt32Seconds( export function _headerFloatSecondsSend( context: Client, - duration: any, + duration: string, options: HeaderFloatSecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -175,7 +175,7 @@ export async function _headerFloatSecondsDeserialize( export async function headerFloatSeconds( context: Client, - duration: any, + duration: string, options: HeaderFloatSecondsOptions = { requestOptions: {} } ): Promise { const result = await _headerFloatSecondsSend(context, duration, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts index 60202c7be4..abdf67b75d 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts @@ -30,7 +30,7 @@ import { export function _propertyDefaultSend( context: Client, - value: any, + value: string, options: PropertyDefaultOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -55,7 +55,7 @@ export async function _propertyDefaultDeserialize( export async function propertyDefault( context: Client, - value: any, + value: string, options: PropertyDefaultOptions = { requestOptions: {} } ): Promise { const result = await _propertyDefaultSend(context, value, options); @@ -64,7 +64,7 @@ export async function propertyDefault( export function _propertyIso8601Send( context: Client, - value: any, + value: string, options: PropertyIso8601Options = { requestOptions: {} } ): StreamableMethod { return context @@ -89,7 +89,7 @@ export async function _propertyIso8601Deserialize( export async function propertyIso8601( context: Client, - value: any, + value: string, options: PropertyIso8601Options = { requestOptions: {} } ): Promise { const result = await _propertyIso8601Send(context, value, options); @@ -98,7 +98,7 @@ export async function propertyIso8601( export function _propertyInt32SecondsSend( context: Client, - value: any, + value: string, options: PropertyInt32SecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -123,7 +123,7 @@ export async function _propertyInt32SecondsDeserialize( export async function propertyInt32Seconds( context: Client, - value: any, + value: string, options: PropertyInt32SecondsOptions = { requestOptions: {} } ): Promise { const result = await _propertyInt32SecondsSend(context, value, options); @@ -132,7 +132,7 @@ export async function propertyInt32Seconds( export function _propertyFloatSecondsSend( context: Client, - value: any, + value: string, options: PropertyFloatSecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -157,7 +157,7 @@ export async function _propertyFloatSecondsDeserialize( export async function propertyFloatSeconds( context: Client, - value: any, + value: string, options: PropertyFloatSecondsOptions = { requestOptions: {} } ): Promise { const result = await _propertyFloatSecondsSend(context, value, options); @@ -166,7 +166,7 @@ export async function propertyFloatSeconds( export function _propertyFloatSecondsArraySend( context: Client, - value: any[], + value: number[], options: PropertyFloatSecondsArrayOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -191,7 +191,7 @@ export async function _propertyFloatSecondsArrayDeserialize( export async function propertyFloatSecondsArray( context: Client, - value: any[], + value: number[], options: PropertyFloatSecondsArrayOptions = { requestOptions: {} } ): Promise { const result = await _propertyFloatSecondsArraySend(context, value, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts index c38c8a484c..8934175b99 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts @@ -23,7 +23,7 @@ import { export function _queryDefaultSend( context: Client, - input: any, + input: string, options: QueryDefaultOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -46,7 +46,7 @@ export async function _queryDefaultDeserialize( export async function queryDefault( context: Client, - input: any, + input: string, options: QueryDefaultOptions = { requestOptions: {} } ): Promise { const result = await _queryDefaultSend(context, input, options); @@ -55,7 +55,7 @@ export async function queryDefault( export function _queryIso8601Send( context: Client, - input: any, + input: string, options: QueryIso8601Options = { requestOptions: {} } ): StreamableMethod { return context @@ -78,7 +78,7 @@ export async function _queryIso8601Deserialize( export async function queryIso8601( context: Client, - input: any, + input: string, options: QueryIso8601Options = { requestOptions: {} } ): Promise { const result = await _queryIso8601Send(context, input, options); @@ -87,7 +87,7 @@ export async function queryIso8601( export function _queryInt32SecondsSend( context: Client, - input: any, + input: string, options: QueryInt32SecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -110,7 +110,7 @@ export async function _queryInt32SecondsDeserialize( export async function queryInt32Seconds( context: Client, - input: any, + input: string, options: QueryInt32SecondsOptions = { requestOptions: {} } ): Promise { const result = await _queryInt32SecondsSend(context, input, options); @@ -119,7 +119,7 @@ export async function queryInt32Seconds( export function _queryFloatSecondsSend( context: Client, - input: any, + input: string, options: QueryFloatSecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -142,7 +142,7 @@ export async function _queryFloatSecondsDeserialize( export async function queryFloatSeconds( context: Client, - input: any, + input: string, options: QueryFloatSecondsOptions = { requestOptions: {} } ): Promise { const result = await _queryFloatSecondsSend(context, input, options); @@ -151,7 +151,7 @@ export async function queryFloatSeconds( export function _queryInt32SecondsArraySend( context: Client, - input: any[], + input: number[], options: QueryInt32SecondsArrayOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -174,7 +174,7 @@ export async function _queryInt32SecondsArrayDeserialize( export async function queryInt32SecondsArray( context: Client, - input: any[], + input: number[], options: QueryInt32SecondsArrayOptions = { requestOptions: {} } ): Promise { const result = await _queryInt32SecondsArraySend(context, input, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts index 6757a1c4de..fdca693b1d 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts @@ -2,21 +2,21 @@ // Licensed under the MIT license. export interface DefaultDurationProperty { - value: any; + value: string; } export interface ISO8601DurationProperty { - value: any; + value: string; } export interface Int32SecondsDurationProperty { - value: any; + value: string; } export interface FloatSecondsDurationProperty { - value: any; + value: string; } export interface FloatSecondsDurationArrayProperty { - value: any[]; + value: number[]; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts index 57d8b05924..ad7fad00be 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts @@ -9,7 +9,7 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { buildCsvCollection } from "../rest/serializeHelper.js"; +import { buildCsvCollection } from "../rest/index.js"; import { HeaderCsvOptions } from "../models/options.js"; export function _headerCsvSend( diff --git a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts index 7cf32f9ce3..20a00573d2 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts @@ -18,7 +18,7 @@ import { buildSsvCollection, buildTsvCollection, buildPipeCollection, -} from "../rest/serializeHelper.js"; +} from "../rest/index.js"; import { QueryMultiOptions, QuerySsvOptions, From 3b8c6d1fc4aaa275909507421c4f05972891579b Mon Sep 17 00:00:00 2001 From: qiaozha Date: Wed, 6 Sep 2023 17:56:15 +0800 Subject: [PATCH 06/17] works for duration and bytes --- .../typespec-ts/src/modular/buildCodeModel.ts | 3 ++- .../typespec-ts/src/modular/buildOperations.ts | 2 +- packages/typespec-ts/src/modular/emitModels.ts | 6 +++--- .../src/modular/helpers/clientHelpers.ts | 2 +- .../src/modular/helpers/operationHelpers.ts | 13 +++++++------ .../src/modular/helpers/typeHelpers.ts | 15 ++++++++------- .../encode/duration/src/DurationClient.ts | 12 ++++++------ .../generated/encode/duration/src/api/header.ts | 8 ++++---- .../generated/encode/duration/src/api/property.ts | 8 ++++---- .../generated/encode/duration/src/api/query.ts | 8 ++++---- .../encode/duration/src/models/models.ts | 4 ++-- 11 files changed, 42 insertions(+), 39 deletions(-) diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 677be88762..7410294dd5 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -851,10 +851,11 @@ function emitProperty( if (newProperty.model) { getType(context, newProperty.model); } + const type = getType(context, property.type); return { clientName: applyCasing(clientName, { casing: CASING }), restApiName: jsonName, - type: getType(context, property.type), + type, optional: newProperty.optional, description: getDocStr(context.program, newProperty), addedOn: getAddedOnVersion(context.program, newProperty), diff --git a/packages/typespec-ts/src/modular/buildOperations.ts b/packages/typespec-ts/src/modular/buildOperations.ts index a03ac3bcd9..e57568080e 100644 --- a/packages/typespec-ts/src/modular/buildOperations.ts +++ b/packages/typespec-ts/src/modular/buildOperations.ts @@ -171,7 +171,7 @@ export function buildOperationOptions( return { docs: getDocsFromDescription(p.description), hasQuestionToken: true, - ...buildType(p.clientName, p.type) + ...buildType(p.clientName, p.type, p.format) }; }) }); diff --git a/packages/typespec-ts/src/modular/emitModels.ts b/packages/typespec-ts/src/modular/emitModels.ts index edf8b2795a..ad43acba3c 100644 --- a/packages/typespec-ts/src/modular/emitModels.ts +++ b/packages/typespec-ts/src/modular/emitModels.ts @@ -40,7 +40,7 @@ export function buildModels( for (const model of models) { const properties = model.properties ?? []; - const typeMetadata = getType(model); + const typeMetadata = getType(model, model.format); let typeName = typeMetadata.name; if (typeMetadata.modifier === "Array") { typeName = `${typeName}[]`; @@ -77,7 +77,7 @@ export function buildModels( docs: getDocsFromDescription(model.description), extends: [] as string[], properties: properties.map((p) => { - const propertyMetadata = getType(p.type); + const propertyMetadata = getType(p.type, p.format); let propertyTypeName = propertyMetadata.name; if (isAzureCoreErrorSdkType(p.type)) { propertyTypeName = isAzureCoreErrorSdkType(p.type) @@ -98,7 +98,7 @@ export function buildModels( }; model.type === "model" ? model.parents?.forEach((p) => - modelInterface.extends.push(getType(p).name) + modelInterface.extends.push(getType(p, p.format).name) ) : undefined; modelsFile.addInterface(modelInterface); diff --git a/packages/typespec-ts/src/modular/helpers/clientHelpers.ts b/packages/typespec-ts/src/modular/helpers/clientHelpers.ts index 1770bbafa6..c4fac46752 100644 --- a/packages/typespec-ts/src/modular/helpers/clientHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/clientHelpers.ts @@ -24,7 +24,7 @@ export function getClientParameters( .map>((p) => { return { name: p.clientName, - type: getType(p.type).name + type: getType(p.type, p.format).name }; }), optionsParam diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 28f93cfe67..5030629f11 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -101,7 +101,7 @@ export function getDeserializePrivateFunction( const response = operation.responses[0]!; let returnType; if (response?.type?.type) { - returnType = buildType(response.type.name, response.type); + returnType = buildType(response.type.name, response.type, response.type.format); } else { returnType = { name: "", type: "void" }; } @@ -186,20 +186,21 @@ function getOperationSignatureParameters( (operation.bodyParameter?.type.properties ?? []) .filter((p) => !p.optional) .filter((p) => !p.readonly) - .map((p) => buildType(p.clientName, p.type)) + .map((p) => buildType(p.clientName, p.type, p.format)) .forEach((p) => parameters.set(p.name, p)); } else if (operation.bodyParameter?.type.type === "list") { const bodyArray = operation.bodyParameter; parameters.set( bodyArray.clientName, - buildType(bodyArray.clientName, bodyArray.type) + buildType(bodyArray.clientName, bodyArray.type, bodyArray.type.format) ); } else if (operation.bodyParameter?.type.type === "byte-array") { parameters.set( operation.bodyParameter.clientName, buildType( operation.bodyParameter.clientName, - operation.bodyParameter.type + operation.bodyParameter.type, + operation.bodyParameter.type.format ) ); } @@ -212,7 +213,7 @@ function getOperationSignatureParameters( p.clientDefaultValue === undefined && !p.optional ) - .map((p) => buildType(p.clientName, p.type)) + .map((p) => buildType(p.clientName, p.type, p.format)) .forEach((p) => { parameters.set(p.name, p); }); @@ -246,7 +247,7 @@ export function getOperationFunction( // TODO: Support operation overloads const response = operation.responses[0]!; const returnType = response?.type?.type - ? buildType(response.type.name, response.type) + ? buildType(response.type.name, response.type, response.type.format) : { name: "", type: "void" }; const { name, fixme = [] } = getOperationName(operation); diff --git a/packages/typespec-ts/src/modular/helpers/typeHelpers.ts b/packages/typespec-ts/src/modular/helpers/typeHelpers.ts index 3c108d1728..2f9ad75345 100644 --- a/packages/typespec-ts/src/modular/helpers/typeHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/typeHelpers.ts @@ -15,7 +15,7 @@ function getNullableType(name: string, type: Type): string { return name; } -export function getType(type: Type): TypeMetadata { +export function getType(type: Type, format?: string): TypeMetadata { switch (type.type) { case "Key": return { @@ -58,7 +58,7 @@ export function getType(type: Type): TypeMetadata { throw new Error("Unable to process Array with no elementType"); } return { - name: getNullableType(getType(type.elementType).name, type), + name: getNullableType(getType(type.elementType, type.elementType.format).name, type), modifier: "Array", originModule: type.elementType?.type === "model" ? "models.js" : undefined @@ -73,7 +73,7 @@ export function getType(type: Type): TypeMetadata { }; case "string": case "duration": - switch (type.format) { + switch (format) { case "seconds": return { name: getNullableType("number", type) }; case "ISO8601": @@ -86,7 +86,7 @@ export function getType(type: Type): TypeMetadata { } const name = type.types .map((t) => { - const sdkType = getTypeName(getType(t)); + const sdkType = getTypeName(getType(t, t.format)); return `${sdkType}`; }) .join(" | "); @@ -97,7 +97,7 @@ export function getType(type: Type): TypeMetadata { throw new Error("Unable to process dict without elemetType info"); } return { - name: `Record` + name: `Record` }; case "any": return { @@ -124,13 +124,14 @@ function getTypeName(typeMetadata: TypeMetadata) { */ export function buildType( clientName: string | undefined, - type: Type | undefined + type: Type | undefined, + format: string | undefined ) { if (!type) { throw new Error("Type should be defined"); } - const typeMetadata = getType(type); + const typeMetadata = getType(type, format); let typeName = typeMetadata.name; if (typeMetadata.modifier === "Array") { typeName = `${typeName}[]`; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts index 37504dda35..c5d57d72a9 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts @@ -64,13 +64,13 @@ export class DurationClient { return queryIso8601(this._client, input, options); }, int32Seconds: ( - input: string, + input: number, options?: QueryInt32SecondsOptions ): Promise => { return queryInt32Seconds(this._client, input, options); }, floatSeconds: ( - input: string, + input: number, options?: QueryFloatSecondsOptions ): Promise => { return queryFloatSeconds(this._client, input, options); @@ -96,13 +96,13 @@ export class DurationClient { return propertyIso8601(this._client, value, options); }, int32Seconds: ( - value: string, + value: number, options?: PropertyInt32SecondsOptions ): Promise => { return propertyInt32Seconds(this._client, value, options); }, floatSeconds: ( - value: string, + value: number, options?: PropertyFloatSecondsOptions ): Promise => { return propertyFloatSeconds(this._client, value, options); @@ -134,13 +134,13 @@ export class DurationClient { return headerIso8601Array(this._client, duration, options); }, int32Seconds: ( - duration: string, + duration: number, options?: HeaderInt32SecondsOptions ): Promise => { return headerInt32Seconds(this._client, duration, options); }, floatSeconds: ( - duration: string, + duration: number, options?: HeaderFloatSecondsOptions ): Promise => { return headerFloatSeconds(this._client, duration, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts index a8412d9478..735350471c 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts @@ -120,7 +120,7 @@ export async function headerIso8601Array( export function _headerInt32SecondsSend( context: Client, - duration: string, + duration: number, options: HeaderInt32SecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -143,7 +143,7 @@ export async function _headerInt32SecondsDeserialize( export async function headerInt32Seconds( context: Client, - duration: string, + duration: number, options: HeaderInt32SecondsOptions = { requestOptions: {} } ): Promise { const result = await _headerInt32SecondsSend(context, duration, options); @@ -152,7 +152,7 @@ export async function headerInt32Seconds( export function _headerFloatSecondsSend( context: Client, - duration: string, + duration: number, options: HeaderFloatSecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -175,7 +175,7 @@ export async function _headerFloatSecondsDeserialize( export async function headerFloatSeconds( context: Client, - duration: string, + duration: number, options: HeaderFloatSecondsOptions = { requestOptions: {} } ): Promise { const result = await _headerFloatSecondsSend(context, duration, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts index abdf67b75d..1f1f125607 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts @@ -98,7 +98,7 @@ export async function propertyIso8601( export function _propertyInt32SecondsSend( context: Client, - value: string, + value: number, options: PropertyInt32SecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -123,7 +123,7 @@ export async function _propertyInt32SecondsDeserialize( export async function propertyInt32Seconds( context: Client, - value: string, + value: number, options: PropertyInt32SecondsOptions = { requestOptions: {} } ): Promise { const result = await _propertyInt32SecondsSend(context, value, options); @@ -132,7 +132,7 @@ export async function propertyInt32Seconds( export function _propertyFloatSecondsSend( context: Client, - value: string, + value: number, options: PropertyFloatSecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -157,7 +157,7 @@ export async function _propertyFloatSecondsDeserialize( export async function propertyFloatSeconds( context: Client, - value: string, + value: number, options: PropertyFloatSecondsOptions = { requestOptions: {} } ): Promise { const result = await _propertyFloatSecondsSend(context, value, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts index 8934175b99..9ba5615fbd 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts @@ -87,7 +87,7 @@ export async function queryIso8601( export function _queryInt32SecondsSend( context: Client, - input: string, + input: number, options: QueryInt32SecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -110,7 +110,7 @@ export async function _queryInt32SecondsDeserialize( export async function queryInt32Seconds( context: Client, - input: string, + input: number, options: QueryInt32SecondsOptions = { requestOptions: {} } ): Promise { const result = await _queryInt32SecondsSend(context, input, options); @@ -119,7 +119,7 @@ export async function queryInt32Seconds( export function _queryFloatSecondsSend( context: Client, - input: string, + input: number, options: QueryFloatSecondsOptions = { requestOptions: {} } ): StreamableMethod { return context @@ -142,7 +142,7 @@ export async function _queryFloatSecondsDeserialize( export async function queryFloatSeconds( context: Client, - input: string, + input: number, options: QueryFloatSecondsOptions = { requestOptions: {} } ): Promise { const result = await _queryFloatSecondsSend(context, input, options); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts index fdca693b1d..476962243e 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts @@ -10,11 +10,11 @@ export interface ISO8601DurationProperty { } export interface Int32SecondsDurationProperty { - value: string; + value: number; } export interface FloatSecondsDurationProperty { - value: string; + value: number; } export interface FloatSecondsDurationArrayProperty { From c200ad5be729e1bb5ca7141cf432e12a17c98d80 Mon Sep 17 00:00:00 2001 From: qiaozha Date: Wed, 6 Sep 2023 18:15:55 +0800 Subject: [PATCH 07/17] works for datetime --- .../typespec-ts/src/modular/buildCodeModel.ts | 17 +---------------- .../src/modular/helpers/operationHelpers.ts | 17 ++++++++--------- .../generated/encode/datetime/src/api/header.ts | 6 +++--- .../encode/datetime/src/api/property.ts | 6 +++--- .../generated/encode/datetime/src/api/query.ts | 6 +++--- 5 files changed, 18 insertions(+), 34 deletions(-) diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 7410294dd5..0fb5694bfe 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -1096,23 +1096,8 @@ function mergeFormatAndEncoding( case undefined: return encodeAsFormat ?? encoding; case "date-time": - switch (encoding) { - case "rfc3339": - return "date-time"; - case "unixTimestamp": - return "unixtime"; - case "rfc7231": - return "utc-date"; - default: - return encoding; - } + return encoding; case "duration": - switch (encoding) { - case "ISO8601": - return "duration"; - default: - return encodeAsFormat ?? encoding; - } default: return encodeAsFormat ?? encoding; } diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 5030629f11..3dea1e8e41 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -839,16 +839,15 @@ function serializeRequestValue( const coreUtilSet = importSet.get("@azure/core-util"); switch (type.type) { case "datetime": - if (format === "date-time") { - return `${restValue}.toISOString()`; + switch(format) { + case "rfc7231": + return `${restValue}.toUTCString()`; + case "unixTimestamp": + return `${restValue}.getTime()`; + case "rfc3339": + default: + return `${restValue}.toISOString()`; } - if (format === "utc-date") { - return `${restValue}.toUTCString()`; - } - if (format === "unixtime") { - return `${restValue}.getTime()`; - } - return `${restValue}.toISOString()`; case "list": if (type.elementType?.type === "model") { return `(${restValue} ?? []).map(p => ({${getRequestModelMapping( diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts index cfffae3480..63aeb3c997 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts @@ -95,7 +95,7 @@ export function _headerRfc7231Send( .path("/encode/datetime/header/rfc7231") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value.toISOString() }, + headers: { value: value.toUTCString() }, }); } @@ -127,7 +127,7 @@ export function _headerUnixTimestampSend( .path("/encode/datetime/header/unix-timestamp") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value.toISOString() }, + headers: { value: value.getTime() }, }); } @@ -160,7 +160,7 @@ export function _headerUnixTimestampArraySend( .get({ ...operationOptionsToRequestParameters(options), headers: { - value: buildCsvCollection((value ?? []).map((p) => p.toISOString())), + value: buildCsvCollection((value ?? []).map((p) => p.getTime())), }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts index 0ff4a2267a..9f0173a0e4 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts @@ -105,7 +105,7 @@ export function _propertyRfc7231Send( .path("/encode/datetime/property/rfc7231") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value.toISOString() }, + body: { value: value.toUTCString() }, }); } @@ -139,7 +139,7 @@ export function _propertyUnixTimestampSend( .path("/encode/datetime/property/unix-timestamp") .post({ ...operationOptionsToRequestParameters(options), - body: { value: value.toISOString() }, + body: { value: value.getTime() }, }); } @@ -173,7 +173,7 @@ export function _propertyUnixTimestampArraySend( .path("/encode/datetime/property/unix-timestamp-array") .post({ ...operationOptionsToRequestParameters(options), - body: { value: (value ?? []).map((p) => p.toISOString()) }, + body: { value: (value ?? []).map((p) => p.getTime()) }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts index 68361f17a1..ffce73a4fe 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts @@ -94,7 +94,7 @@ export function _queryRfc7231Send( .path("/encode/datetime/query/rfc7231") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value.toISOString() }, + queryParameters: { value: value.toUTCString() }, }); } @@ -126,7 +126,7 @@ export function _queryUnixTimestampSend( .path("/encode/datetime/query/unix-timestamp") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: value.toISOString() }, + queryParameters: { value: value.getTime() }, }); } @@ -158,7 +158,7 @@ export function _queryUnixTimestampArraySend( .path("/encode/datetime/query/unix-timestamp-array") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { value: (value ?? []).map((p) => p.toISOString()) }, + queryParameters: { value: (value ?? []).map((p) => p.getTime()) }, }); } From 135b9c0a7336f84224566356aef90b226333badf Mon Sep 17 00:00:00 2001 From: qiaozha Date: Thu, 7 Sep 2023 11:14:50 +0800 Subject: [PATCH 08/17] try fix ci --- .../typespec-ts/src/api/operations.ts | 7 +- .../typespec-ts/src/api/operations.ts | 5 +- .../src/loadTestRun/api/operations.ts | 7 +- .../typespec-ts/src/api/operations.ts | 60 ++++++++++++-- .../typespec-ts/src/modular/buildCodeModel.ts | 17 ++-- .../src/modular/helpers/operationHelpers.ts | 80 +++++++++++++------ .../modularIntegration/encodeDuration.spec.ts | 17 ++-- 7 files changed, 138 insertions(+), 55 deletions(-) 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 a4cd1514cf..45bf0addde 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 @@ -325,7 +325,12 @@ export function _addOrUpdateBlockItemsSend( ) .post({ ...operationOptionsToRequestParameters(options), - body: { blockItems: blockItems }, + body: { + blockItems: (blockItems ?? []).map((p) => ({ + description: p["description"], + text: p["text"], + })), + }, }); } 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 4cbeee4732..9354b21e20 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 @@ -63,8 +63,7 @@ export function _publishCloudEventSend( ? uint8ArrayToString(event["dataBase64"], "base64") : undefined, type: event["type"], - time: - event["time"] !== undefined ? new Date(event["time"]) : undefined, + time: event["time"]?.toISOString(), specversion: event["specversion"], dataschema: event["dataschema"], datacontenttype: event["datacontenttype"], @@ -123,7 +122,7 @@ export function _publishCloudEventsSend( ? uint8ArrayToString(p["dataBase64"], "base64") : undefined, type: p["type"], - time: p["time"] !== undefined ? new Date(p["time"]) : undefined, + time: p["time"]?.toISOString(), specversion: p["specversion"], dataschema: p["dataschema"], datacontenttype: p["datacontenttype"], 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 c6b9f45b38..e0084b1b6d 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 @@ -1082,7 +1082,12 @@ export function _listMetricsSend( metricNamespace: options?.metricNamespace, timespan: options?.timespan, }, - body: { filters: options?.filters }, + body: { + filters: (options?.filters ?? []).map((p) => ({ + name: p["name"], + values: p["values"], + })), + }, }); } 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 b62bba1cb0..661e7bc19d 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 @@ -242,8 +242,29 @@ export function _getChatCompletionsSend( .post({ ...operationOptionsToRequestParameters(options), body: { - messages: messages, - functions: options?.functions, + messages: (messages ?? []).map((p) => ({ + role: p["role"], + content: p["content"], + name: p["name"], + function_call: !p.functionCall + ? undefined + : { + name: p.functionCall?.["name"], + arguments: p.functionCall?.["arguments"], + }, + context: !p.context + ? undefined + : { + messages: !p.context?.messages + ? undefined + : (p.context?.messages as any), + }, + })), + functions: (options?.functions ?? []).map((p) => ({ + name: p["name"], + description: p["description"], + parameters: p["parameters"], + })), function_call: options?.functionCall, max_tokens: options?.maxTokens, temperature: options?.temperature, @@ -256,7 +277,10 @@ export function _getChatCompletionsSend( frequency_penalty: options?.frequencyPenalty, stream: options?.stream, model: options?.model, - dataSources: options?.dataSources, + dataSources: (options?.dataSources ?? []).map((p) => ({ + type: p["type"], + parameters: p["parameters"], + })), }, }); } @@ -400,8 +424,29 @@ export function _getChatCompletionsWithAzureExtensionsSend( .post({ ...operationOptionsToRequestParameters(options), body: { - messages: messages, - functions: options?.functions, + messages: (messages ?? []).map((p) => ({ + role: p["role"], + content: p["content"], + name: p["name"], + function_call: !p.functionCall + ? undefined + : { + name: p.functionCall?.["name"], + arguments: p.functionCall?.["arguments"], + }, + context: !p.context + ? undefined + : { + messages: !p.context?.messages + ? undefined + : (p.context?.messages as any), + }, + })), + functions: (options?.functions ?? []).map((p) => ({ + name: p["name"], + description: p["description"], + parameters: p["parameters"], + })), function_call: options?.functionCall, max_tokens: options?.maxTokens, temperature: options?.temperature, @@ -414,7 +459,10 @@ export function _getChatCompletionsWithAzureExtensionsSend( frequency_penalty: options?.frequencyPenalty, stream: options?.stream, model: options?.model, - dataSources: options?.dataSources, + dataSources: (options?.dataSources ?? []).map((p) => ({ + type: p["type"], + parameters: p["parameters"], + })), }, }); } diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 0fb5694bfe..fa6b99b4c5 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -344,10 +344,10 @@ function emitParamBase( if (parameter.kind === "ModelProperty") { const newParameter = applyEncoding(program, parameter, parameter); - optional = newParameter.optional; - name = newParameter.name; - description = getDocStr(program, newParameter); - addedOn = getAddedOnVersion(program, newParameter); + optional = parameter.optional; + name = parameter.name; + description = getDocStr(program, parameter); + addedOn = getAddedOnVersion(program, parameter); format = newParameter.format; } else { optional = false; @@ -856,12 +856,11 @@ function emitProperty( clientName: applyCasing(clientName, { casing: CASING }), restApiName: jsonName, type, - optional: newProperty.optional, - description: getDocStr(context.program, newProperty), - addedOn: getAddedOnVersion(context.program, newProperty), + optional: property.optional, + description: getDocStr(context.program, property), + addedOn: getAddedOnVersion(context.program, property), readonly: - isReadOnly(context.program, newProperty) || - isKey(context.program, newProperty), + isReadOnly(context.program, property) || isKey(context.program, property), clientDefaultValue: clientDefaultValue, format: newProperty.format }; diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 3dea1e8e41..ae73bf9f54 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -101,7 +101,11 @@ export function getDeserializePrivateFunction( const response = operation.responses[0]!; let returnType; if (response?.type?.type) { - returnType = buildType(response.type.name, response.type, response.type.format); + returnType = buildType( + response.type.name, + response.type, + response.type.format + ); } else { returnType = { name: "", type: "void" }; } @@ -297,7 +301,10 @@ function getRequestParameters( operation: Operation, importSet: Map> ): string { - if (operation.name.endsWith("int32Seconds") && operation.groupName === "Header") { + if ( + operation.name.endsWith("int32Seconds") && + operation.groupName === "Header" + ) { operation; } if (!operation.parameters) { @@ -448,10 +455,7 @@ function getCollectionFormat( if (serializeHelperImport) { serializeHelperImport.add(collectionInfo); } else { - importSet.set( - "../rest/index.js", - new Set().add(collectionInfo) - ); + importSet.set("../rest/index.js", new Set().add(collectionInfo)); } if (!param.optional) { return `"${param.restApiName}": ${collectionInfo}(${serializeRequestValue( @@ -468,7 +472,7 @@ function getCollectionFormat( param.type, "options?." + param.clientName, importSet, - true, + false, param.format )}${additionalParam}): undefined`; } @@ -515,7 +519,7 @@ function getRequired(param: RequiredType, importSet: Map>) { } return `"${param.restApiName}": ${serializeRequestValue( param.type, - param.restApiName, + param.clientName, importSet, true, param.format @@ -563,7 +567,7 @@ function getOptional(param: OptionalType, importSet: Map>) { } return `"${param.restApiName}": ${serializeRequestValue( param.type, - `options?.${param.restApiName}`, + `options?.${param.clientName}`, importSet, false, param.format @@ -640,7 +644,7 @@ function getRequestModelMapping( if (property.readonly) { continue; } - const propertyFullName = `${propertyPath}.${property.restApiName}`; + const propertyFullName = `${propertyPath}.${property.clientName}`; if (property.type.type === "model") { let definition; if (property.type.isCoreErrorType) { @@ -650,6 +654,17 @@ function getRequestModelMapping( )} ${ !property.optional ? "" : `!${propertyFullName} ? undefined :` } ${propertyFullName}`; + } else if ( + (property.restApiName === "message" || + property.restApiName === "messages") && + (property.type.name === "ChatMessage" || + property.type.elementType?.name === "ChatMessage") + ) { + definition = `"${property.restApiName}": ${ + !property.optional + ? `${propertyFullName} as any` + : `!${propertyFullName} ? undefined : ${propertyFullName} as any` + }`; } else { definition = `"${property.restApiName}": ${getNullableCheck( propertyFullName, @@ -658,25 +673,37 @@ function getRequestModelMapping( !property.optional ? "" : `!${propertyFullName} ? undefined :` } {${getRequestModelMapping( property.type, - `${propertyPath}.${property.restApiName}${ + `${propertyPath}.${property.clientName}${ property.optional ? "?" : "" }`, importSet )}}`; } + props.push(definition); + } else if ( + (property.restApiName === "message" || + property.restApiName === "messages") && + (property.type.name === "ChatMessage" || + property.type.elementType?.name === "ChatMessage") + ) { + const definition = `"${property.restApiName}": ${ + !property.optional + ? `${propertyFullName} as any` + : `!${propertyFullName} ? undefined : ${propertyFullName} as any` + }`; props.push(definition); } else { const dot = propertyPath.endsWith("?") ? "." : ""; - const restValue = `${ + const clientValue = `${ propertyPath ? `${propertyPath}${dot}` : `${dot}` }["${property.clientName}"]`; props.push( `"${property.restApiName}": ${serializeRequestValue( property.type, - restValue, + clientValue, importSet, - !propertyPath.endsWith("?"), + !property.optional, property.format )}` ); @@ -741,7 +768,8 @@ export function getResponseMapping( propertyPath ? `${propertyPath}${dot}` : `${dot}` }["${property.restApiName}"]`; if ( - property.restApiName === "messages" && + (property.restApiName === "message" || + property.restApiName === "messages") && (property.type.name === "ChatMessage" || property.type.elementType?.name === "ChatMessage") ) { @@ -831,7 +859,7 @@ function deserializeResponseValue( */ function serializeRequestValue( type: Type, - restValue: string, + clientValue: string, importSet: Map>, required: boolean, format?: string @@ -839,24 +867,24 @@ function serializeRequestValue( const coreUtilSet = importSet.get("@azure/core-util"); switch (type.type) { case "datetime": - switch(format) { + switch (format) { case "rfc7231": - return `${restValue}.toUTCString()`; + return `${clientValue}${required ? "" : "?"}.toUTCString()`; case "unixTimestamp": - return `${restValue}.getTime()`; + return `${clientValue}${required ? "" : "?"}.getTime()`; case "rfc3339": default: - return `${restValue}.toISOString()`; + return `${clientValue}${required ? "" : "?"}.toISOString()`; } case "list": if (type.elementType?.type === "model") { - return `(${restValue} ?? []).map(p => ({${getRequestModelMapping( + return `(${clientValue} ?? []).map(p => ({${getRequestModelMapping( type.elementType, "p", importSet )}}))`; } else if (needsDeserialize(type.elementType)) { - return `(${restValue} ?? []).map(p => ${serializeRequestValue( + return `(${clientValue} ?? []).map(p => ${serializeRequestValue( type.elementType!, "p", importSet, @@ -864,7 +892,7 @@ function serializeRequestValue( type.elementType?.format )})`; } else { - return restValue; + return clientValue; } case "byte-array": if (!coreUtilSet) { @@ -876,12 +904,12 @@ function serializeRequestValue( coreUtilSet.add("uint8ArrayToString"); } return required - ? `uint8ArrayToString(${restValue}, "${format ?? "base64"}")` - : `${restValue} !== undefined ? uint8ArrayToString(${restValue}, "${ + ? `uint8ArrayToString(${clientValue}, "${format ?? "base64"}")` + : `${clientValue} !== undefined ? uint8ArrayToString(${clientValue}, "${ format ?? "base64" }"): undefined`; default: - return restValue; + return clientValue; } } diff --git a/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts index 00ad899377..a7a1ee1502 100644 --- a/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts @@ -33,7 +33,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get float seconds`, async () => { try { - const result = await client.query.floatSeconds("35.621"); + const result = await client.query.floatSeconds(35.621); assert.isUndefined(result); } catch (err) { assert.fail(err as string); @@ -42,7 +42,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get int32 seconds`, async () => { try { - const result = await client.query.int32Seconds("36"); + const result = await client.query.int32Seconds(36); assert.isUndefined(result); } catch (err) { assert.fail(err as string); @@ -51,7 +51,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get int32 seconds array`, async () => { try { - const result = await client.query.int32SecondsArray(["36", "47"]); + const result = await client.query.int32SecondsArray([36, 47]); assert.isUndefined(result); } catch (err) { assert.fail(err as string); @@ -80,7 +80,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get float seconds`, async () => { try { - const result = await client.property.floatSeconds("35.621"); + const result = await client.property.floatSeconds(35.621); assert.isUndefined(result); } catch (err) { assert.fail(err as string); @@ -89,7 +89,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get int32 seconds`, async () => { try { - const result = await client.property.int32Seconds("36"); + const result = await client.property.int32Seconds(36); assert.isUndefined(result); } catch (err) { assert.fail(err as string); @@ -99,8 +99,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get int32 seconds array`, async () => { try { const result = await client.property.floatSecondsArray([ - "35.621", - "46.781" + 35.621, 46.781 ]); assert.isUndefined(result); } catch (err) { @@ -130,7 +129,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get float seconds`, async () => { try { - const result = await client.header.floatSeconds("35.621"); + const result = await client.header.floatSeconds(35.621); assert.isUndefined(result); } catch (err) { assert.fail(err as string); @@ -139,7 +138,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get int32 seconds`, async () => { try { - const result = await client.header.int32Seconds("36"); + const result = await client.header.int32Seconds(36); assert.isUndefined(result); } catch (err) { assert.fail(err as string); From 60fec35acb93b6d704ffdf2748e78c9a201bfbed Mon Sep 17 00:00:00 2001 From: qiaozha Date: Thu, 7 Sep 2023 11:37:07 +0800 Subject: [PATCH 09/17] undo unnecessary changes --- .../typespec-ts/src/modular/buildCodeModel.ts | 27 ++++++++++++------- .../src/modular/helpers/operationHelpers.ts | 6 ----- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index fa6b99b4c5..69083db55e 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -314,6 +314,14 @@ function getType( // need to do properties after insertion to avoid infinite recursion processModelProperties(context, newValue, type); } + } else { + const key = JSON.stringify(newValue); + const value = simpleTypesMap.get(key); + if (value) { + newValue = value; + } else { + simpleTypesMap.set(key, newValue); + } } return newValue; @@ -829,33 +837,32 @@ function emitProperty( ): Record { const newProperty = applyEncoding(context.program, property, property); let clientDefaultValue = undefined; - const propertyDefaultKind = newProperty.default?.kind; + const propertyDefaultKind = property.default?.kind; if ( - newProperty.default && + property.default && (propertyDefaultKind === "Number" || propertyDefaultKind === "String" || propertyDefaultKind === "Boolean") ) { - clientDefaultValue = newProperty.default.value; + clientDefaultValue = property.default.value; } if (propertyDefaultKind === "EnumMember") { - clientDefaultValue = newProperty.default.value ?? newProperty.default.name; + clientDefaultValue = property.default.value ?? property.default.name; } // const [clientName, jsonName] = getPropertyNames(context, property); - const clientName = newProperty.name; + const clientName = property.name; const jsonName = - getProjectedName(context.program, newProperty, "json") ?? newProperty.name; + getProjectedName(context.program, property, "json") ?? property.name; - if (newProperty.model) { - getType(context, newProperty.model); + if (property.model) { + getType(context, property.model); } - const type = getType(context, property.type); return { clientName: applyCasing(clientName, { casing: CASING }), restApiName: jsonName, - type, + type: getType(context, property.type), optional: property.optional, description: getDocStr(context.program, property), addedOn: getAddedOnVersion(context.program, property), diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index ae73bf9f54..4cef0e0376 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -301,12 +301,6 @@ function getRequestParameters( operation: Operation, importSet: Map> ): string { - if ( - operation.name.endsWith("int32Seconds") && - operation.groupName === "Header" - ) { - operation; - } if (!operation.parameters) { return ""; } From 2c222a5a14bf996a9eb0c926161432abb3f06459 Mon Sep 17 00:00:00 2001 From: qiaozha Date: Thu, 7 Sep 2023 13:19:43 +0800 Subject: [PATCH 10/17] fix integration test --- .../src/modular/helpers/operationHelpers.ts | 9 +++++++-- .../test/modularIntegration/encodeBytes.spec.ts | 13 ++++++++----- .../test/modularIntegration/encodeDatetime.spec.ts | 12 ++++++------ .../test/modularIntegration/encodeDuration.spec.ts | 12 ++++++------ .../generated/encode/bytes/src/api/header.ts | 2 +- .../generated/encode/datetime/src/api/header.ts | 2 +- 6 files changed, 29 insertions(+), 21 deletions(-) diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 4cef0e0376..d9656b3bde 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -516,7 +516,9 @@ function getRequired(param: RequiredType, importSet: Map>) { param.clientName, importSet, true, - param.format + param.format === undefined && (param as Parameter).location === "header" + ? "headerDefault" + : param.format )}`; } @@ -564,7 +566,9 @@ function getOptional(param: OptionalType, importSet: Map>) { `options?.${param.clientName}`, importSet, false, - param.format + param.format === undefined && (param as Parameter).location === "header" + ? "headerDefault" + : param.format )}`; } @@ -863,6 +867,7 @@ function serializeRequestValue( case "datetime": switch (format) { case "rfc7231": + case "headerDefault": return `${clientValue}${required ? "" : "?"}.toUTCString()`; case "unixTimestamp": return `${clientValue}${required ? "" : "?"}.getTime()`; diff --git a/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts index 051b614f6c..dd1c2679a6 100644 --- a/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts @@ -1,7 +1,7 @@ import { assert } from "chai"; import { BytesClient } from "./generated/encode/bytes/src/index"; import { stringToUint8Array } from "@azure/core-util"; -describe.only("EncodeDatetimeClient Rest Client", () => { +describe("EncodeBytesClient Rest Client", () => { let client: BytesClient; beforeEach(() => { @@ -66,7 +66,7 @@ describe.only("EncodeDatetimeClient Rest Client", () => { const result = await client.property.default( stringToUint8Array("dGVzdA==", "base64") ); - assert.isUndefined(result); + assert.deepEqual(result.value, stringToUint8Array("dGVzdA==", "base64")); } catch (err) { assert.fail(err as string); } @@ -77,7 +77,7 @@ describe.only("EncodeDatetimeClient Rest Client", () => { const result = await client.property.base64( stringToUint8Array("dGVzdA==", "base64") ); - assert.isUndefined(result); + assert.deepEqual(result.value, stringToUint8Array("dGVzdA==", "base64")); } catch (err) { assert.fail(err as string); } @@ -88,7 +88,7 @@ describe.only("EncodeDatetimeClient Rest Client", () => { const result = await client.property.base64url( stringToUint8Array("dGVzdA", "base64url") ); - assert.isUndefined(result); + assert.deepEqual(result.value, stringToUint8Array("dGVzdA", "base64url")); } catch (err) { assert.fail(err as string); } @@ -100,7 +100,10 @@ describe.only("EncodeDatetimeClient Rest Client", () => { stringToUint8Array("dGVzdA", "base64url"), stringToUint8Array("dGVzdA", "base64url") ]); - assert.isUndefined(result); + assert.deepEqual(result.value, [ + stringToUint8Array("dGVzdA", "base64url"), + stringToUint8Array("dGVzdA", "base64url") + ]); } catch (err) { assert.fail(err as string); } diff --git a/packages/typespec-ts/test/modularIntegration/encodeDatetime.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeDatetime.spec.ts index 4e1872024e..6a02e0a085 100644 --- a/packages/typespec-ts/test/modularIntegration/encodeDatetime.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/encodeDatetime.spec.ts @@ -74,7 +74,7 @@ describe("EncodeDatetimeClient Rest Client", () => { const result = await client.property.default( new Date("2022-08-26T18:38:00.000Z") ); - assert.isUndefined(result); + assert.deepEqual(result.value, new Date("2022-08-26T18:38:00.000Z")); } catch (err) { assert.fail(err as string); } @@ -85,7 +85,7 @@ describe("EncodeDatetimeClient Rest Client", () => { const result = await client.property.rfc3339( new Date("2022-08-26T18:38:00.000Z") ); - assert.isUndefined(result); + assert.deepEqual(result.value, new Date("2022-08-26T18:38:00.000Z")); } catch (err) { assert.fail(err as string); } @@ -96,7 +96,7 @@ describe("EncodeDatetimeClient Rest Client", () => { const result = await client.property.rfc7231( new Date("Fri, 26 Aug 2022 14:38:00 GMT") ); - assert.isUndefined(result); + assert.deepEqual(result.value, new Date("Fri, 26 Aug 2022 14:38:00 GMT")); } catch (err) { assert.fail(err as string); } @@ -105,7 +105,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get unix timestamp`, async () => { try { const result = await client.property.unixTimestamp(new Date(1686566864)); - assert.isUndefined(result); + assert.deepEqual(result.value, new Date(1686566864)); } catch (err) { assert.fail(err as string); } @@ -117,7 +117,7 @@ describe("EncodeDatetimeClient Rest Client", () => { new Date(1686566864), new Date(1686734256) ]); - assert.isUndefined(result); + assert.deepEqual(result.value, [new Date(1686566864), new Date(1686734256)]); } catch (err) { assert.fail(err as string); } @@ -128,7 +128,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get default datetime`, async () => { try { const result = await client.header.default( - new Date("2022-08-26T18:38:00.000Z") + new Date("Fri, 26 Aug 2022 14:38:00 GMT") ); assert.isUndefined(result); } catch (err) { diff --git a/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts index a7a1ee1502..fc1e0bed00 100644 --- a/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts @@ -1,6 +1,6 @@ import { assert } from "chai"; import { DurationClient } from "./generated/encode/duration/src/index"; -describe("EncodeDatetimeClient Rest Client", () => { +describe("EncodeDurationClient Rest Client", () => { let client: DurationClient; beforeEach(() => { @@ -63,7 +63,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get default duration`, async () => { try { const result = await client.property.default("P40D"); - assert.isUndefined(result); + assert.deepEqual(result.value, "P40D"); } catch (err) { assert.fail(err as string); } @@ -72,7 +72,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get iso8601 duration`, async () => { try { const result = await client.property.iso8601("P40D"); - assert.isUndefined(result); + assert.deepEqual(result.value, "P40D"); } catch (err) { assert.fail(err as string); } @@ -81,7 +81,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get float seconds`, async () => { try { const result = await client.property.floatSeconds(35.621); - assert.isUndefined(result); + assert.deepEqual(result.value, 35.621); } catch (err) { assert.fail(err as string); } @@ -90,7 +90,7 @@ describe("EncodeDatetimeClient Rest Client", () => { it(`should get int32 seconds`, async () => { try { const result = await client.property.int32Seconds(36); - assert.isUndefined(result); + assert.deepEqual(result.value, 36); } catch (err) { assert.fail(err as string); } @@ -101,7 +101,7 @@ describe("EncodeDatetimeClient Rest Client", () => { const result = await client.property.floatSecondsArray([ 35.621, 46.781 ]); - assert.isUndefined(result); + assert.deepEqual(result.value, [35.621, 46.781]); } catch (err) { assert.fail(err as string); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts index 622c76bf44..9e2be4dbaf 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts @@ -30,7 +30,7 @@ export function _headerDefaultSend( .path("/encode/bytes/header/default") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: uint8ArrayToString(value, "base64") }, + headers: { value: uint8ArrayToString(value, "headerDefault") }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts index 63aeb3c997..1ec65cad15 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts @@ -31,7 +31,7 @@ export function _headerDefaultSend( .path("/encode/datetime/header/default") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: value.toISOString() }, + headers: { value: value.toUTCString() }, }); } From 6f841518c62ca9c742293444b9fb6d683516de70 Mon Sep 17 00:00:00 2001 From: qiaozha Date: Thu, 7 Sep 2023 14:28:44 +0800 Subject: [PATCH 11/17] fix ci --- .../src/modular/helpers/operationHelpers.ts | 12 ++++++++---- .../generated/encode/bytes/src/api/header.ts | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index d9656b3bde..f250e8529f 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -516,9 +516,11 @@ function getRequired(param: RequiredType, importSet: Map>) { param.clientName, importSet, true, - param.format === undefined && (param as Parameter).location === "header" - ? "headerDefault" - : param.format + param.format === undefined && + (param as Parameter).location === "header" && + param.type.type === "datetime" + ? "headerDefault" + : param.format )}`; } @@ -566,7 +568,9 @@ function getOptional(param: OptionalType, importSet: Map>) { `options?.${param.clientName}`, importSet, false, - param.format === undefined && (param as Parameter).location === "header" + param.format === undefined && + (param as Parameter).location === "header" && + param.type.type === "datetime" ? "headerDefault" : param.format )}`; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts index 9e2be4dbaf..622c76bf44 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts @@ -30,7 +30,7 @@ export function _headerDefaultSend( .path("/encode/bytes/header/default") .get({ ...operationOptionsToRequestParameters(options), - headers: { value: uint8ArrayToString(value, "headerDefault") }, + headers: { value: uint8ArrayToString(value, "base64") }, }); } From 3d8a2dac5498cc75264e304c6d0d24b92cad6d80 Mon Sep 17 00:00:00 2001 From: qiaozha Date: Thu, 7 Sep 2023 14:57:41 +0800 Subject: [PATCH 12/17] fix integrationgit --- .../test/integration/generated/encode/datetime/src/index.ts | 1 + .../test/integration/generated/encode/duration/src/index.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/typespec-ts/test/integration/generated/encode/datetime/src/index.ts b/packages/typespec-ts/test/integration/generated/encode/datetime/src/index.ts index 9cac785ece..9785cae7dd 100644 --- a/packages/typespec-ts/test/integration/generated/encode/datetime/src/index.ts +++ b/packages/typespec-ts/test/integration/generated/encode/datetime/src/index.ts @@ -9,5 +9,6 @@ export * from "./responses"; export * from "./clientDefinitions"; export * from "./models"; export * from "./outputModels"; +export * from "./serializeHelper"; export default DatetimeClient; diff --git a/packages/typespec-ts/test/integration/generated/encode/duration/src/index.ts b/packages/typespec-ts/test/integration/generated/encode/duration/src/index.ts index dcd6d09c74..0fc0d6db38 100644 --- a/packages/typespec-ts/test/integration/generated/encode/duration/src/index.ts +++ b/packages/typespec-ts/test/integration/generated/encode/duration/src/index.ts @@ -9,5 +9,6 @@ export * from "./responses"; export * from "./clientDefinitions"; export * from "./models"; export * from "./outputModels"; +export * from "./serializeHelper"; export default DurationClient; From 06ce70c7ec4cb807613227061d0e07b7a987b9c6 Mon Sep 17 00:00:00 2001 From: qiaozha Date: Fri, 8 Sep 2023 12:22:49 +0800 Subject: [PATCH 13/17] use auto imports --- .../src/modular/helpers/operationHelpers.ts | 6 ------ .../generated/azure/core/src/api/operations.ts | 2 +- .../generated/encode/bytes/src/api/header.ts | 2 +- .../generated/encode/datetime/src/api/header.ts | 2 +- .../generated/encode/duration/src/api/header.ts | 2 +- .../parameters/collection-format/src/api/header.ts | 2 +- .../parameters/collection-format/src/api/query.ts | 10 ++++------ 7 files changed, 9 insertions(+), 17 deletions(-) diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index f250e8529f..b74360d255 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -445,12 +445,6 @@ function getCollectionFormat( } const isMulti = (param.format ?? "").toLowerCase() === "multi"; const additionalParam = isMulti ? `, "${param.restApiName}"` : ""; - const serializeHelperImport = importSet.get("../rest/index.js"); - if (serializeHelperImport) { - serializeHelperImport.add(collectionInfo); - } else { - importSet.set("../rest/index.js", new Set().add(collectionInfo)); - } if (!param.optional) { return `"${param.restApiName}": ${collectionInfo}(${serializeRequestValue( param.type, diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts index de81b927fa..6feb3389e3 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts @@ -5,6 +5,7 @@ import { User, UserListResults, PagedUser } from "../models/models.js"; import { isUnexpected, BasicContext as Client, + buildMultiCollection, CreateOrReplace200Response, CreateOrReplace201Response, CreateOrReplaceDefaultResponse, @@ -28,7 +29,6 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { buildMultiCollection } from "../rest/index.js"; import { CreateOrUpdateOptions, CreateOrReplaceOptions, diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts index 622c76bf44..f354cd22ac 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts @@ -2,6 +2,7 @@ // Licensed under the MIT license. import { + buildCsvCollection, BytesContext as Client, HeaderBase64204Response, HeaderBase64url204Response, @@ -13,7 +14,6 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; import { uint8ArrayToString } from "@azure/core-util"; -import { buildCsvCollection } from "../rest/index.js"; import { HeaderDefaultOptions, HeaderBase64Options, diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts index 1ec65cad15..5b291b3b69 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts @@ -2,6 +2,7 @@ // Licensed under the MIT license. import { + buildCsvCollection, DatetimeContext as Client, HeaderDefault204Response, HeaderRfc3339204Response, @@ -13,7 +14,6 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { buildCsvCollection } from "../rest/index.js"; import { HeaderDefaultOptions, HeaderRfc3339Options, diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts index 735350471c..eb1de520e9 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts @@ -2,6 +2,7 @@ // Licensed under the MIT license. import { + buildCsvCollection, DurationContext as Client, HeaderDefault204Response, HeaderFloatSeconds204Response, @@ -13,7 +14,6 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { buildCsvCollection } from "../rest/index.js"; import { HeaderDefaultOptions, HeaderIso8601Options, diff --git a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts index ad7fad00be..82d2b7daf5 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/header.ts @@ -2,6 +2,7 @@ // Licensed under the MIT license. import { + buildCsvCollection, CollectionFormatContext as Client, HeaderCsv204Response, } from "../rest/index.js"; @@ -9,7 +10,6 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { buildCsvCollection } from "../rest/index.js"; import { HeaderCsvOptions } from "../models/options.js"; export function _headerCsvSend( diff --git a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts index 20a00573d2..6cb204b48f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/api/query.ts @@ -2,6 +2,10 @@ // Licensed under the MIT license. import { + buildMultiCollection, + buildPipeCollection, + buildSsvCollection, + buildTsvCollection, CollectionFormatContext as Client, QueryCsv204Response, QueryMulti204Response, @@ -13,12 +17,6 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { - buildMultiCollection, - buildSsvCollection, - buildTsvCollection, - buildPipeCollection, -} from "../rest/index.js"; import { QueryMultiOptions, QuerySsvOptions, From 18a0286e4a0a9dcd0cb357d13f6c83cae6a3c72b Mon Sep 17 00:00:00 2001 From: qiaozha Date: Fri, 8 Sep 2023 16:36:21 +0800 Subject: [PATCH 14/17] datetime ut --- packages/typespec-ts/package.json | 4 +- packages/typespec-ts/src/lib.ts | 3 +- .../typespec-ts/src/modular/buildCodeModel.ts | 11 ++- .../src/modular/buildOperations.ts | 3 + .../src/modular/helpers/operationHelpers.ts | 6 +- .../test/modularUnit/modelsGenerator.spec.ts | 85 ++++++++++++++++++- packages/typespec-ts/test/util/emitUtil.ts | 37 ++++++++ packages/typespec-ts/test/util/testUtil.ts | 11 ++- 8 files changed, 150 insertions(+), 10 deletions(-) diff --git a/packages/typespec-ts/package.json b/packages/typespec-ts/package.json index 8e9abf6052..116035cadb 100644 --- a/packages/typespec-ts/package.json +++ b/packages/typespec-ts/package.json @@ -30,7 +30,9 @@ "integration-test:alone:rlc": "cross-env TS_NODE_PROJECT=tsconfig.test.json mocha -r ts-node/register --experimental-specifier-resolution=node --timeout 4000 ./test/integration/*.spec.ts", "integration-test:alone:modular": "cross-env TS_NODE_PROJECT=tsconfig.test.json mocha -r ts-node/register --experimental-specifier-resolution=node --timeout 4000 ./test/modularIntegration/*.spec.ts", "stop-test-server": "npx cadl-ranch server stop", - "unit-test": "cross-env TS_NODE_PROJECT=tsconfig.json mocha -r ts-node/register --experimental-specifier-resolution=node --experimental-modules=true --timeout 4000 './test/unit/**/*.spec.ts' './test/modularUnit/**/*.spec.ts'" + "unit-test": "npm run unit-test:rlc && npm run unit-test:modular", + "unit-test:rlc": "cross-env TS_NODE_PROJECT=tsconfig.json mocha -r ts-node/register --experimental-specifier-resolution=node --experimental-modules=true --timeout 4000 './test/unit/**/*.spec.ts'", + "unit-test:modular": "cross-env TS_NODE_PROJECT=tsconfig.json mocha -r ts-node/register --experimental-specifier-resolution=node --experimental-modules=true --no-timeout './test/modularUnit/**/*.spec.ts'" }, "author": "Jose Heredia ", "license": "MIT", diff --git a/packages/typespec-ts/src/lib.ts b/packages/typespec-ts/src/lib.ts index c7f4cee832..a99af95975 100644 --- a/packages/typespec-ts/src/lib.ts +++ b/packages/typespec-ts/src/lib.ts @@ -200,7 +200,8 @@ export const prettierTypeScriptOptions: Options = { printWidth: 80, semi: true, singleQuote: false, - tabWidth: 2 + tabWidth: 2, + useTabs: false }; export const prettierJSONOptions: Options = { diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 69083db55e..675d9794a4 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -36,7 +36,8 @@ import { getProjectedName, isNullType, getEncode, - isTemplateDeclarationOrInstance + isTemplateDeclarationOrInstance, + getFormat } from "@typespec/compiler"; import { getAuthentication, @@ -1058,11 +1059,13 @@ function emitStdScalar( case "boolean": return { type: "boolean" }; case "plainDate": - return { type: "date" }; + return { type: "datetime", format: newScalar.format ?? "date" }; case "utcDateTime": return { type: "datetime", format: newScalar.format }; case "plainTime": - return { type: "time" }; + return { type: "datetime", format: newScalar.format ?? "time" }; + case "offsetDateTime": + return { type: "datetime", format: newScalar.format ?? "rfc7231" }; case "duration": return { type: "duration", format: newScalar.format }; case "numeric": @@ -1078,6 +1081,8 @@ function applyEncoding( target: any = {} ) { const encodeData = getEncode(program, typespecType); + const formatData = getFormat(program, typespecType); + formatData; if (encodeData) { const newTarget = { ...target }; const newType = emitScalar(program, encodeData.type); diff --git a/packages/typespec-ts/src/modular/buildOperations.ts b/packages/typespec-ts/src/modular/buildOperations.ts index e57568080e..58b9af7a61 100644 --- a/packages/typespec-ts/src/modular/buildOperations.ts +++ b/packages/typespec-ts/src/modular/buildOperations.ts @@ -23,6 +23,7 @@ export function buildOperationFiles( client: Client, needUnexpectedHelper: boolean = true ) { + const operationFiles = []; for (const operationGroup of client.operationGroups) { const importSet: Map> = new Map>(); const fileName = operationGroup.className @@ -114,7 +115,9 @@ export function buildOperationFiles( operationGroupFile.fixMissingImports(); // have to fixUnusedIdentifiers after everything get generated. operationGroupFile.fixUnusedIdentifiers(); + operationFiles.push(operationGroupFile); } + return operationFiles; } export function importModels( diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index b74360d255..e3f5cca0a3 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -863,7 +863,11 @@ function serializeRequestValue( const coreUtilSet = importSet.get("@azure/core-util"); switch (type.type) { case "datetime": - switch (format) { + switch (type.format ?? format) { + case "date": + return `${clientValue}${required ? "" : "?"}.toDateString()`; + case "time": + return `${clientValue}${required ? "" : "?"}.toTimeString()`; case "rfc7231": case "headerDefault": return `${clientValue}${required ? "" : "?"}.toUTCString()`; diff --git a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts index 87fd90aa1d..7dd63ade40 100644 --- a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts +++ b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts @@ -1,5 +1,5 @@ import { assert } from "chai"; -import { emitModularModelsFromTypeSpec } from "../util/emitUtil.js"; +import { emitModularModelsFromTypeSpec, emitModularOperationsFromTypeSpec } from "../util/emitUtil.js"; import { assertEqualContent } from "../util/testUtil.js"; describe("modular model type", () => { @@ -13,6 +13,89 @@ describe("modular model type", () => { }); }); +describe("modular encode test for property type datetime", () => { + it("should handle property type utcDateTime", async () => { + const tspContent = ` + model Foo { + prop1: plainDate; + prop2: plainTime; + prop3: utcDateTime; + prop4: offsetDateTime; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Date; + prop2: Date; + prop3: Date; + prop4: Date; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: Date, + prop2: Date, + prop3: Date, + prop4: Date, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1.toDateString(), + prop2: prop2.toTimeString(), + prop3: prop3.toISOString(), + prop4: prop4.toUTCString(), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: new Date(result.body["prop1"]), + prop2: new Date(result.body["prop2"]), + prop3: new Date(result.body["prop3"]), + prop4: new Date(result.body["prop4"]), + }; + } + + export async function read( + context: Client, + prop1: Date, + prop2: Date, + prop3: Date, + prop4: Date, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, prop2, prop3, prop4, options); + return _readDeserialize(result); + }` + ); + }); +}); + describe("inheritance & polymorphism", () => { it("should handle inheritance model", async () => { const modelFile = await emitModularModelsFromTypeSpec(` diff --git a/packages/typespec-ts/test/util/emitUtil.ts b/packages/typespec-ts/test/util/emitUtil.ts index 76d833d1d7..432ceede3e 100644 --- a/packages/typespec-ts/test/util/emitUtil.ts +++ b/packages/typespec-ts/test/util/emitUtil.ts @@ -25,6 +25,7 @@ import { expectDiagnosticEmpty } from "@typespec/compiler/testing"; import { transformHelperFunctionDetails } from "../../src/transform/transformHelperFunctionDetails.js"; import { emitCodeModel } from "../../src/modular/buildCodeModel.js"; import { buildModels } from "../../src/modular/emitModels.js"; +import { buildOperationFiles } from "../../src/modular/buildOperations.js"; import { Project } from "ts-morph"; export async function emitPageHelperFromTypeSpec( @@ -246,3 +247,39 @@ export async function emitModularModelsFromTypeSpec(tspContent: string) { expectDiagnosticEmpty(dpgContext.program.diagnostics); return undefined; } + +export async function emitModularOperationsFromTypeSpec(tspContent: string) { + const context = await rlcEmitterFor(tspContent); + const dpgContext = createDpgContextTestHelper(context.program); + const serviceNameToRlcModelsMap: Map = new Map< + string, + RLCModel + >(); + const project = new Project(); + 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] + ) { + return buildOperationFiles(dpgContext, modularCodeModel, modularCodeModel.clients[0], false); + } + } + expectDiagnosticEmpty(dpgContext.program.diagnostics); + return undefined; + +} \ No newline at end of file diff --git a/packages/typespec-ts/test/util/testUtil.ts b/packages/typespec-ts/test/util/testUtil.ts index a5d4bc12f9..1cdc02ab4f 100644 --- a/packages/typespec-ts/test/util/testUtil.ts +++ b/packages/typespec-ts/test/util/testUtil.ts @@ -71,7 +71,12 @@ export function createDpgContextTestHelper(program: Program): SdkContext { const defaultOptions = { generateProtocolMethods: true, generateConvenienceMethods: true, - emitters: [] + emitters: [ + { + main: "@azure-tools/typespec-ts", + metadata: { name: "@azure-tools/typespec-ts" } + } + ] }; const resolvedOptions = { ...defaultOptions }; program.emitters = resolvedOptions.emitters as any; @@ -86,7 +91,7 @@ export function createDpgContextTestHelper(program: Program): SdkContext { export function assertEqualContent(actual: string, expected: string) { assert.strictEqual( - format(actual, prettierTypeScriptOptions), - format(expected, prettierTypeScriptOptions) + format(actual.replace(/\n/g, ""), prettierTypeScriptOptions), + format(expected.replace(/\n/g, ""), prettierTypeScriptOptions) ); } From 32992d113951e0a9c9cf2e523c3fc3cf32b9f00b Mon Sep 17 00:00:00 2001 From: qiaozha Date: Fri, 8 Sep 2023 17:42:50 +0800 Subject: [PATCH 15/17] fix ci --- .../typespec-ts/review/load-testing.api.md | 78 ++-- .../loadTestAdministration/api/operations.ts | 199 ++++++++-- .../loadTestAdministration/models/models.ts | 24 +- .../loadTestAdministration/models/options.ts | 16 +- .../src/loadTestRun/api/operations.ts | 363 +++++++++++++++--- .../src/loadTestRun/models/models.ts | 24 +- .../src/loadTestRun/models/options.ts | 22 +- packages/typespec-ts/src/lib.ts | 3 +- .../typespec-ts/src/modular/buildCodeModel.ts | 2 + .../test/modularUnit/modelsGenerator.spec.ts | 3 +- packages/typespec-ts/test/util/testUtil.ts | 16 +- 11 files changed, 569 insertions(+), 181 deletions(-) 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 082189e673..906665a52d 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 @@ -37,9 +37,9 @@ export interface CreateOrUpdateAppComponentsOptions extends OperationOptions { // (undocumented) contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; testId?: string; } @@ -48,9 +48,9 @@ export interface CreateOrUpdateServerMetricsConfigOptions extends OperationOptio // (undocumented) contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; metrics?: Record; testId?: string; } @@ -61,7 +61,7 @@ export interface CreateOrUpdateTestOptions extends OperationOptions { // (undocumented) contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; description?: string; displayName?: string; environmentVariables?: Record; @@ -69,7 +69,7 @@ export interface CreateOrUpdateTestOptions extends OperationOptions { keyvaultReferenceIdentityId?: string; keyvaultReferenceIdentityType?: string; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestConfiguration; passFailCriteria?: PassFailCriteria; secrets?: Record; @@ -114,7 +114,7 @@ export interface ErrorDetails { // @public export interface FileInfo { - expireDateTime?: any; + expireDateTime?: Date; fileName?: string; fileType?: FileType; url?: string; @@ -187,8 +187,8 @@ export interface ListTestFilesOptions extends OperationOptions { // @public (undocumented) export interface ListTestRunsOptions extends OperationOptions { - executionFrom?: any; - executionTo?: any; + executionFrom?: Date; + executionTo?: Date; maxpagesize?: number; orderby?: string; search?: string; @@ -198,8 +198,8 @@ export interface ListTestRunsOptions extends OperationOptions { // @public (undocumented) export interface ListTestsOptions extends OperationOptions { - lastModifiedEndTime?: any; - lastModifiedStartTime?: any; + lastModifiedEndTime?: Date; + lastModifiedStartTime?: Date; maxpagesize?: number; orderby?: string; search?: string; @@ -289,9 +289,9 @@ export interface LoadTestRunClientCreateOrUpdateAppComponentsOptions extends Ope // (undocumented) contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; testRunId?: string; } @@ -300,9 +300,9 @@ export interface LoadTestRunClientCreateOrUpdateServerMetricsConfigOptions exten // (undocumented) contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; metrics?: Record; testRunId?: string; } @@ -332,7 +332,7 @@ export interface LoadTestRunClientErrorDetails { // @public export interface LoadTestRunClientFileInfo { - expireDateTime?: any; + expireDateTime?: Date; fileName?: string; fileType?: LoadTestRunClientFileType; url?: string; @@ -475,7 +475,7 @@ export type LoadTestRunClientStatus = string; export interface LoadTestRunClientTest { certificate?: LoadTestRunClientCertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; description?: string; displayName?: string; environmentVariables?: Record; @@ -483,7 +483,7 @@ export interface LoadTestRunClientTest { keyvaultReferenceIdentityId?: string; keyvaultReferenceIdentityType?: string; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; passFailCriteria?: LoadTestRunClientPassFailCriteria; secrets?: Record; @@ -504,21 +504,21 @@ export interface LoadTestRunClientTestInputArtifacts { export interface LoadTestRunClientTestRun { certificate?: LoadTestRunClientCertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; description?: string; displayName?: string; readonly duration?: number; - readonly endDateTime?: any; + readonly endDateTime?: Date; environmentVariables?: Record; readonly errorDetails?: LoadTestRunClientErrorDetails[]; - readonly executedDateTime?: any; + readonly executedDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; passFailCriteria?: LoadTestRunClientPassFailCriteria; readonly portalUrl?: string; secrets?: Record; - readonly startDateTime?: any; + readonly startDateTime?: Date; readonly status?: LoadTestRunClientStatus; readonly subnetId?: string; readonly testArtifacts?: LoadTestRunClientTestRunArtifacts; @@ -699,7 +699,7 @@ export interface StopTestRunOptions extends OperationOptions { export interface Test { certificate?: CertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; description?: string; displayName?: string; environmentVariables?: Record; @@ -707,7 +707,7 @@ export interface Test { keyvaultReferenceIdentityId?: string; keyvaultReferenceIdentityType?: string; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestConfiguration; passFailCriteria?: PassFailCriteria; secrets?: Record; @@ -719,9 +719,9 @@ export interface Test { export interface TestAppComponents { components: Record; readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; readonly testId?: string; } @@ -738,21 +738,21 @@ export interface TestInputArtifacts { export interface TestRun { certificate?: CertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; description?: string; displayName?: string; readonly duration?: number; - readonly endDateTime?: any; + readonly endDateTime?: Date; environmentVariables?: Record; readonly errorDetails?: ErrorDetails[]; - readonly executedDateTime?: any; + readonly executedDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestConfiguration; passFailCriteria?: PassFailCriteria; readonly portalUrl?: string; secrets?: Record; - readonly startDateTime?: any; + readonly startDateTime?: Date; readonly status?: Status; readonly subnetId?: string; readonly testArtifacts?: TestRunArtifacts; @@ -783,22 +783,22 @@ export interface TestRunOptions extends OperationOptions { certificate?: LoadTestRunClientCertificateMetadata; contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; description?: string; displayName?: string; duration?: number; - endDateTime?: any; + endDateTime?: Date; environmentVariables?: Record; errorDetails?: LoadTestRunClientErrorDetails[]; - executedDateTime?: any; + executedDateTime?: Date; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; oldTestRunId?: string; passFailCriteria?: LoadTestRunClientPassFailCriteria; portalUrl?: string; secrets?: Record; - startDateTime?: any; + startDateTime?: Date; status?: LoadTestRunClientStatus; subnetId?: string; testArtifacts?: LoadTestRunClientTestRunArtifacts; @@ -835,9 +835,9 @@ export interface TestRunStatistics { // @public export interface TestServerMetricConfig { readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; metrics?: Record; readonly testId?: string; } 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 1c1a4e0033..4fd7d0a0b0 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 @@ -187,7 +187,13 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -208,7 +214,13 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -229,7 +241,13 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -257,7 +275,13 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -273,7 +297,10 @@ export async function _createOrUpdateTestDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -284,9 +311,15 @@ export async function _createOrUpdateTestDeserialize( subnetId: result.body["subnetId"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -334,9 +367,15 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -389,9 +428,15 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -435,9 +480,15 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -477,9 +528,15 @@ export async function _getServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -572,7 +629,13 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -593,7 +656,13 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -614,7 +683,13 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -642,7 +717,13 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -658,7 +739,10 @@ export async function _getTestDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -669,9 +753,15 @@ export async function _getTestDeserialize( subnetId: result.body["subnetId"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -713,7 +803,10 @@ export async function _getTestFileDeserialize( url: result.body["url"], fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; @@ -757,7 +850,10 @@ export async function _listTestFilesDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -789,8 +885,8 @@ export function _listTestsSend( queryParameters: { orderby: options?.orderby, search: options?.search, - lastModifiedStartTime: options?.lastModifiedStartTime, - lastModifiedEndTime: options?.lastModifiedEndTime, + lastModifiedStartTime: options?.lastModifiedStartTime?.toUTCString(), + lastModifiedEndTime: options?.lastModifiedEndTime?.toUTCString(), maxpagesize: options?.maxpagesize, }, }); @@ -857,7 +953,12 @@ export async function _listTestsDeserialize( fileName: p.inputArtifacts?.configFileInfo?.["fileName"], fileType: p.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.configFileInfo?.["expireDateTime"], + p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.configFileInfo?.["expireDateTime"] + ) + : undefined, validationStatus: p.inputArtifacts?.configFileInfo?.["validationStatus"], validationFailureDetails: @@ -872,7 +973,14 @@ export async function _listTestsDeserialize( fileName: p.inputArtifacts?.testScriptFileInfo?.["fileName"], fileType: p.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"], + p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.inputArtifacts?.testScriptFileInfo?.["validationStatus"], validationFailureDetails: @@ -887,7 +995,12 @@ export async function _listTestsDeserialize( fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], fileType: p.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.userPropFileInfo?.["expireDateTime"], + p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] + ) + : undefined, validationStatus: p.inputArtifacts?.userPropFileInfo?.["validationStatus"], validationFailureDetails: @@ -907,7 +1020,13 @@ export async function _listTestsDeserialize( expireDateTime: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -923,7 +1042,10 @@ export async function _listTestsDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -934,9 +1056,15 @@ export async function _listTestsDeserialize( subnetId: p["subnetId"], keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], - createdDateTime: p["createdDateTime"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, createdBy: p["createdBy"], - lastModifiedDateTime: p["lastModifiedDateTime"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, lastModifiedBy: p["lastModifiedBy"], })), nextLink: result.body["nextLink"], @@ -988,7 +1116,10 @@ export async function _uploadTestFileDeserialize( url: result.body["url"], fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; 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 index adc1c2c27a..3631274756 100644 --- 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 @@ -34,11 +34,11 @@ export interface Test { /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -171,7 +171,7 @@ export interface FileInfo { /** File type */ fileType?: FileType; /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: any; + expireDateTime?: Date; /** Validation status of the file */ validationStatus?: FileStatus; /** Validation failure error details */ @@ -194,11 +194,11 @@ export interface TestAppComponents { /** Test identifier */ readonly testId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -238,11 +238,11 @@ export interface TestServerMetricConfig { */ metrics?: Record; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -326,11 +326,11 @@ export interface TestRun { /** The test run status. */ readonly status?: Status; /** The test run start DateTime(ISO 8601 literal format). */ - readonly startDateTime?: any; + readonly startDateTime?: Date; /** The test run end DateTime(ISO 8601 literal format). */ - readonly endDateTime?: any; + readonly endDateTime?: Date; /** Test run initiated time. */ - readonly executedDateTime?: any; + readonly executedDateTime?: Date; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ @@ -338,11 +338,11 @@ export interface TestRun { /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } 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/models/options.ts index 6f7df207bb..b622d3dfe4 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/models/options.ts @@ -44,11 +44,11 @@ export interface CreateOrUpdateTestOptions extends OperationOptions { /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; contentType?: string; @@ -58,11 +58,11 @@ export interface CreateOrUpdateAppComponentsOptions extends OperationOptions { /** Test identifier */ testId?: string; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; contentType?: string; @@ -79,11 +79,11 @@ export interface CreateOrUpdateServerMetricsConfigOptions */ metrics?: Record; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; contentType?: string; @@ -115,12 +115,12 @@ export interface ListTestsOptions extends OperationOptions { * Start DateTime(ISO 8601 literal format) of the last updated time range to * filter tests. */ - lastModifiedStartTime?: any; + lastModifiedStartTime?: Date; /** * End DateTime(ISO 8601 literal format) of the last updated time range to filter * tests. */ - lastModifiedEndTime?: any; + lastModifiedEndTime?: Date; /** Number of results in response. */ maxpagesize?: number; } 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 e0084b1b6d..720decaa83 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 @@ -209,7 +209,13 @@ export async function _testRunDeserialize( ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -231,7 +237,13 @@ export async function _testRunDeserialize( ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -253,7 +265,13 @@ export async function _testRunDeserialize( ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -275,7 +293,14 @@ export async function _testRunDeserialize( ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -293,7 +318,10 @@ export async function _testRunDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -315,7 +343,13 @@ export async function _testRunDeserialize( ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -337,7 +371,13 @@ export async function _testRunDeserialize( ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -353,15 +393,30 @@ export async function _testRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + 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"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -409,9 +464,15 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -464,9 +525,15 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -544,9 +611,15 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -589,9 +662,15 @@ export async function _getServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -694,7 +773,13 @@ export async function _getTestRunDeserialize( ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -716,7 +801,13 @@ export async function _getTestRunDeserialize( ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -738,7 +829,13 @@ export async function _getTestRunDeserialize( ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -760,7 +857,14 @@ export async function _getTestRunDeserialize( ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -778,7 +882,10 @@ export async function _getTestRunDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -800,7 +907,13 @@ export async function _getTestRunDeserialize( ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -822,7 +935,13 @@ export async function _getTestRunDeserialize( ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -838,15 +957,30 @@ export async function _getTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + 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"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -888,7 +1022,10 @@ export async function _getTestRunFileDeserialize( url: result.body["url"], fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; @@ -1139,8 +1276,8 @@ export function _listTestRunsSend( orderby: options?.orderby, search: options?.search, testId: options?.testId, - executionFrom: options?.executionFrom, - executionTo: options?.executionTo, + executionFrom: options?.executionFrom?.toUTCString(), + executionTo: options?.executionTo?.toUTCString(), status: options?.status, maxpagesize: options?.maxpagesize, }, @@ -1227,7 +1364,13 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -1254,7 +1397,13 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -1281,7 +1430,13 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -1305,7 +1460,14 @@ export async function _listTestRunsDeserialize( ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -1322,7 +1484,10 @@ export async function _listTestRunsDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -1348,7 +1513,13 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "validationStatus" @@ -1375,7 +1546,13 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "validationStatus" @@ -1393,15 +1570,28 @@ export async function _listTestRunsDeserialize( testId: p["testId"], description: p["description"], status: p["status"], - startDateTime: p["startDateTime"], - endDateTime: p["endDateTime"], - executedDateTime: p["executedDateTime"], + 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"], - createdDateTime: p["createdDateTime"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, createdBy: p["createdBy"], - lastModifiedDateTime: p["lastModifiedDateTime"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, lastModifiedBy: p["lastModifiedBy"], })), nextLink: result.body["nextLink"], @@ -1505,7 +1695,13 @@ export async function _stopTestRunDeserialize( ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -1527,7 +1723,13 @@ export async function _stopTestRunDeserialize( ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -1549,7 +1751,13 @@ export async function _stopTestRunDeserialize( ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -1571,7 +1779,14 @@ export async function _stopTestRunDeserialize( ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -1589,7 +1804,10 @@ export async function _stopTestRunDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -1611,7 +1829,13 @@ export async function _stopTestRunDeserialize( ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -1633,7 +1857,13 @@ export async function _stopTestRunDeserialize( ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -1649,15 +1879,30 @@ export async function _stopTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + 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"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } 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 index 753b02bd58..545db894d9 100644 --- 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 @@ -34,11 +34,11 @@ export interface Test { /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -171,7 +171,7 @@ export interface FileInfo { /** File type */ fileType?: FileType; /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: any; + expireDateTime?: Date; /** Validation status of the file */ validationStatus?: FileStatus; /** Validation failure error details */ @@ -270,11 +270,11 @@ export interface TestRun { /** The test run status. */ readonly status?: Status; /** The test run start DateTime(ISO 8601 literal format). */ - readonly startDateTime?: any; + readonly startDateTime?: Date; /** The test run end DateTime(ISO 8601 literal format). */ - readonly endDateTime?: any; + readonly endDateTime?: Date; /** Test run initiated time. */ - readonly executedDateTime?: any; + readonly executedDateTime?: Date; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ @@ -282,11 +282,11 @@ export interface TestRun { /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -375,11 +375,11 @@ export interface TestRunAppComponents { /** Test run identifier */ readonly testRunId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -395,11 +395,11 @@ export interface TestRunServerMetricConfig { */ metrics?: Record; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } 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/models/options.ts index 7be901a85c..85aa3bc985 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/models/options.ts @@ -53,11 +53,11 @@ export interface TestRunOptions extends OperationOptions { /** The test run status. */ status?: Status; /** The test run start DateTime(ISO 8601 literal format). */ - startDateTime?: any; + startDateTime?: Date; /** The test run end DateTime(ISO 8601 literal format). */ - endDateTime?: any; + endDateTime?: Date; /** Test run initiated time. */ - executedDateTime?: any; + executedDateTime?: Date; /** Portal url. */ portalUrl?: string; /** Test run duration in milliseconds. */ @@ -65,11 +65,11 @@ export interface TestRunOptions extends OperationOptions { /** Subnet ID on which the load test instances should run. */ subnetId?: string; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; /** This request has a JSON Merge Patch body. */ @@ -87,11 +87,11 @@ export interface CreateOrUpdateAppComponentsOptions extends OperationOptions { /** Test run identifier */ testRunId?: string; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; contentType?: string; @@ -108,11 +108,11 @@ export interface CreateOrUpdateServerMetricsConfigOptions */ metrics?: Record; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; contentType?: string; @@ -185,9 +185,9 @@ export interface ListTestRunsOptions extends OperationOptions { /** Unique name of an existing load test. */ testId?: string; /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionFrom?: any; + executionFrom?: Date; /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionTo?: any; + executionTo?: Date; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ diff --git a/packages/typespec-ts/src/lib.ts b/packages/typespec-ts/src/lib.ts index a99af95975..c7f4cee832 100644 --- a/packages/typespec-ts/src/lib.ts +++ b/packages/typespec-ts/src/lib.ts @@ -200,8 +200,7 @@ export const prettierTypeScriptOptions: Options = { printWidth: 80, semi: true, singleQuote: false, - tabWidth: 2, - useTabs: false + tabWidth: 2 }; export const prettierJSONOptions: Options = { diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 675d9794a4..5c477c7f94 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -1625,6 +1625,8 @@ export function emitCodeModel( project }; + typesMap.clear(); + simpleTypesMap.clear(); const allModels = getAllModels(dpgContext); for (const model of allModels) { getType(dpgContext, model); diff --git a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts index 7dd63ade40..f50ab8fb30 100644 --- a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts +++ b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts @@ -91,7 +91,8 @@ describe("modular encode test for property type datetime", () => { ): Promise { const result = await _readSend(context, prop1, prop2, prop3, prop4, options); return _readDeserialize(result); - }` + }`, + true ); }); }); diff --git a/packages/typespec-ts/test/util/testUtil.ts b/packages/typespec-ts/test/util/testUtil.ts index 1cdc02ab4f..0a060d59a3 100644 --- a/packages/typespec-ts/test/util/testUtil.ts +++ b/packages/typespec-ts/test/util/testUtil.ts @@ -89,9 +89,19 @@ export function createDpgContextTestHelper(program: Program): SdkContext { } as SdkContext; } -export function assertEqualContent(actual: string, expected: string) { +export function assertEqualContent( + actual: string, + expected: string, + ignoreWeirdLine: boolean = false +) { assert.strictEqual( - format(actual.replace(/\n/g, ""), prettierTypeScriptOptions), - format(expected.replace(/\n/g, ""), prettierTypeScriptOptions) + format( + ignoreWeirdLine ? actual.replace(/\n/g, "") : actual, + prettierTypeScriptOptions + ), + format( + ignoreWeirdLine ? expected.replace(/\n/g, "") : expected, + prettierTypeScriptOptions + ) ); } From 4448009c545b5c9cf5b7d5d80e7c49a1fa06f3b0 Mon Sep 17 00:00:00 2001 From: Qiaoqiao Zhang Date: Mon, 11 Sep 2023 10:52:38 +0800 Subject: [PATCH 16/17] add more ut --- .../typespec-ts/src/modular/buildCodeModel.ts | 5 +- .../test/modularUnit/modelsGenerator.spec.ts | 622 +++++++++++++++++- 2 files changed, 624 insertions(+), 3 deletions(-) diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 5c477c7f94..3c86c7193b 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -474,7 +474,7 @@ function emitParameter( const paramMap: any = { restApiName: parameter.name, location: parameter.type, - type, + type: base.format ? { ...type, format: base.format } : type, implementation: implementation, skipUrlEncoding: parameter.type === "endpointPath", format: (parameter as any).format ?? base.format @@ -860,10 +860,11 @@ function emitProperty( if (property.model) { getType(context, property.model); } + const type = getType(context, property.type); return { clientName: applyCasing(clientName, { casing: CASING }), restApiName: jsonName, - type: getType(context, property.type), + type: newProperty.format ? { ...type, format: newProperty.format } : type, optional: property.optional, description: getDocStr(context.program, property), addedOn: getAddedOnVersion(context.program, property), diff --git a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts index f50ab8fb30..f4ed7948d5 100644 --- a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts +++ b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts @@ -14,7 +14,7 @@ describe("modular model type", () => { }); describe("modular encode test for property type datetime", () => { - it("should handle property type utcDateTime", async () => { + it("should handle property type plainDate, plainTime, utcDateTime, offsetDatetime with default encoding", async () => { const tspContent = ` model Foo { prop1: plainDate; @@ -95,6 +95,626 @@ describe("modular encode test for property type datetime", () => { true ); }); + + it("should handle property type utcDateTime, offsetDateTime with rfc3339 encoding", async () => { + const tspContent = ` + model Foo { + @encode(DateTimeKnownEncoding.rfc3339) + prop1: utcDateTime; + @encode(DateTimeKnownEncoding.rfc3339) + prop2: offsetDateTime; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Date; + prop2: Date; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: Date, + prop2: Date, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1.toISOString(), + prop2: prop2.toISOString(), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: new Date(result.body["prop1"]), + prop2: new Date(result.body["prop2"]), + }; + } + + export async function read( + context: Client, + prop1: Date, + prop2: Date, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, prop2, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type utcDateTime, offsetDateTime with rfc7231 encoding", async () => { + const tspContent = ` + model Foo { + @encode(DateTimeKnownEncoding.rfc7231) + prop1: utcDateTime; + @encode(DateTimeKnownEncoding.rfc7231) + prop2: offsetDateTime; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Date; + prop2: Date; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: Date, + prop2: Date, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1.toUTCString(), + prop2: prop2.toUTCString(), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: new Date(result.body["prop1"]), + prop2: new Date(result.body["prop2"]), + }; + } + + export async function read( + context: Client, + prop1: Date, + prop2: Date, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, prop2, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type utcDateTime with unixTimestamp encoding", async () => { + const tspContent = ` + model Foo { + @encode(DateTimeKnownEncoding.unixTimestamp, int64) + prop1: utcDateTime; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Date; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: Date, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1.getTime(), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: new Date(result.body["prop1"]), + }; + } + + export async function read( + context: Client, + prop1: Date, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); +}); + +describe("modular encode test for property type duration", () => { + it("should handle property type duration with default encoding", async () => { + const tspContent = ` + model Foo { + prop1: duration; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: string; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: string, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1, + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: result.body["prop1"], + }; + } + + export async function read( + context: Client, + prop1: string, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type duration with ISO8601 encoding", async () => { + const tspContent = ` + model Foo { + @encode(DurationKnownEncoding.ISO8601) + prop1: duration; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: string; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: string, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1, + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: result.body["prop1"], + }; + } + + export async function read( + context: Client, + prop1: string, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type duration with seconds encoding", async () => { + const tspContent = ` + model Foo { + @encode(DurationKnownEncoding.seconds, float32) + prop1: duration; + @encode(DurationKnownEncoding.seconds, int64) + prop2: duration; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: number; + prop2: number; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: number, + prop2: number, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1, + prop2: prop2, + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: result.body["prop1"], + prop2: result.body["prop2"], + }; + } + + export async function read( + context: Client, + prop1: number, + prop2: number, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, prop2, options); + return _readDeserialize(result); + }`, + true + ); + }); +}); + +describe("modular encode test for property type bytes", () => { + it("should handle property type bytes with default encoding", async () => { + const tspContent = ` + model Foo { + prop1: bytes; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Uint8Array; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; + + export function _readSend( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: uint8ArrayToString(prop1, "base64"), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: + typeof result.body["prop1"] === "string" + ? stringToUint8Array(result.body["prop1"], "base64") + : result.body["prop1"], + }; + } + + export async function read( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type bytes with base64 encoding", async () => { + const tspContent = ` + model Foo { + @encode(BytesKnownEncoding.base64) + prop1: bytes; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Uint8Array; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; + + export function _readSend( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: uint8ArrayToString(prop1, "base64"), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: + typeof result.body["prop1"] === "string" + ? stringToUint8Array(result.body["prop1"], "base64") + : result.body["prop1"], + }; + } + + export async function read( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type bytes with base64url encoding", async () => { + const tspContent = ` + model Foo { + @encode(BytesKnownEncoding.base64url) + prop1: bytes; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Uint8Array; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; + + export function _readSend( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: uint8ArrayToString(prop1, "base64url"), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: + typeof result.body["prop1"] === "string" + ? stringToUint8Array(result.body["prop1"], "base64url") + : result.body["prop1"], + }; + } + + export async function read( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); }); describe("inheritance & polymorphism", () => { From 4508ec81b2817b1a98e8025e44872571cb6c4a33 Mon Sep 17 00:00:00 2001 From: Qiaoqiao Zhang Date: Mon, 11 Sep 2023 16:33:46 +0800 Subject: [PATCH 17/17] add header utcDateTime default encoding ut --- .../test/modularUnit/modelsGenerator.spec.ts | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts index f4ed7948d5..da395db889 100644 --- a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts +++ b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts @@ -96,6 +96,56 @@ describe("modular encode test for property type datetime", () => { ); }); + it("should handle header parameter type utcDateTime with default encoding", async () => { + const tspContent = ` + op read(@header prop: utcDateTime): OkResponse; + ` + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop: Date, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + prop: prop.toUTCString(), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return; + } + + export async function read( + context: Client, + prop: Date, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop, options); + return _readDeserialize(result); + }`, + true + ); + }); + it("should handle property type utcDateTime, offsetDateTime with rfc3339 encoding", async () => { const tspContent = ` model Foo {