diff --git a/.chronus/changes/fix_vscode_e2e_test-2025-8-15-10-18-14.md b/.chronus/changes/fix_vscode_e2e_test-2025-8-15-10-18-14.md new file mode 100644 index 00000000000..9832e3ee642 --- /dev/null +++ b/.chronus/changes/fix_vscode_e2e_test-2025-8-15-10-18-14.md @@ -0,0 +1,8 @@ +--- +# Change versionKind to one of: internal, fix, dependencies, feature, deprecation, breaking +changeKind: internal +packages: + - typespec-vscode +--- + +Fix vscode e2e test when making a release pr diff --git a/packages/typespec-vscode/package.json b/packages/typespec-vscode/package.json index ecaa2cb9e08..6859324ef65 100644 --- a/packages/typespec-vscode/package.json +++ b/packages/typespec-vscode/package.json @@ -277,6 +277,7 @@ "package-vsix": "vsce package", "deploy": "vsce publish", "open-in-browser": "vscode-test-web --extensionDevelopmentPath=. .", + "test:e2e": "pnpm test:web && pnpm test:extension", "test:web": "vscode-test-web --quality stable --extensionDevelopmentPath=. --headless --extensionTestsPath=dist/test/web/suite.js ./test/web/data", "test:extension": "vitest run --root test/extension" }, diff --git a/packages/typespec-vscode/test/extension/common/common-steps.ts b/packages/typespec-vscode/test/extension/common/common-steps.ts index 90a88fce3ee..d6301ba629f 100644 --- a/packages/typespec-vscode/test/extension/common/common-steps.ts +++ b/packages/typespec-vscode/test/extension/common/common-steps.ts @@ -1,8 +1,10 @@ +import { readdirSync } from "fs"; import { rm } from "fs/promises"; -import fs from "node:fs"; +import fs, { rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { Locator, Page } from "playwright"; -import { CaseScreenshot, retry } from "./utils"; +import { RunOptions, runOrExit } from "../../../../internal-build-utils/dist/src/index.js"; +import { CaseScreenshot, npxCmd, repoRoot, retry, tempDir } from "./utils"; /** * Waits for the specified text to appear on the page before proceeding. @@ -136,3 +138,73 @@ export function restoreTspConfigFile(folderName: string, lines: string) { const filePath = path.join(folderName, "tspconfig.yaml"); fs.writeFileSync(filePath, lines, "utf-8"); } + +/** + * Pack those packages in the repoRoot needed for testing and prepare to be linked + * @returns packages path map + */ +export async function packPackages() { + await runOrExit("pnpm", ["-w", "pack:all"], { cwd: repoRoot, stdio: "ignore" }); + const outputFolder = path.join(repoRoot, "/temp/artifacts"); + const files = readdirSync(outputFolder); + + function resolvePackage(start: string) { + const pkgName = files.find((x: string) => x.startsWith(start)); + if (pkgName === undefined) { + throw new Error(`Cannot resolve package starting with "${start}"`); + } + return path.join(outputFolder, pkgName); + } + + return { + "@typespec/compiler": resolvePackage("typespec-compiler-"), + "@typespec/openapi3": resolvePackage("typespec-openapi3-"), + "@typespec/http": resolvePackage("typespec-http-"), + "@typespec/http-client-js": resolvePackage("typespec-http-client-js-"), + }; +} + +/** + * Install those packages needed for testing in the EmitTypespecProject folder + * @param packages packages path map + */ +export async function packagesInstall(packages: { [x: string]: string }, testType: string) { + let testCurrentDir: string; + if (testType === "Emit") { + testCurrentDir = path.join(tempDir, "EmitTypespecProject"); + const outputDir = path.join(testCurrentDir, "tsp-output"); + rmSync(outputDir, { recursive: true, force: true }); + } else if (testType === "Import") { + testCurrentDir = path.join(tempDir, "ImportTypespecProjectOpenApi3"); + } else if (testType === "Preview") { + testCurrentDir = path.join(tempDir, "PreviewTypespecProject"); + } else { + throw new Error(`Unknown testType: ${testType}`); + } + const packageJson = { + name: "@typespec/e2e-test-typespec-vscode", + dependencies: { + "@typespec/compiler": packages["@typespec/compiler"], + "@typespec/http": packages["@typespec/http"], + "@typespec/openapi3": packages["@typespec/openapi3"], + "@typespec/http-client-js": packages["@typespec/http-client-js"], + }, + private: true, + }; + writeFileSync(path.join(testCurrentDir, "package.json"), JSON.stringify(packageJson, null, 2)); + + await runTypeSpec(packages["@typespec/compiler"], ["install"], { cwd: testCurrentDir }); + await runTypeSpec(packages["@typespec/http"], ["install"], { cwd: testCurrentDir }); + await runTypeSpec(packages["@typespec/openapi3"], ["install"], { cwd: testCurrentDir }); + await runTypeSpec(packages["@typespec/http-client-js"], ["install"], { cwd: testCurrentDir }); +} + +/** + * Run typespec with npx + * @param compilerTgz The path to the TypeSpec compiler package tarball. + * @param args The arguments to pass to the TypeSpec compiler. + * @param options Additional options for running the command. + */ +export async function runTypeSpec(compilerTgz: string, args: any, options: RunOptions | undefined) { + await runOrExit(npxCmd, ["-y", "-p", compilerTgz, "tsp", ...args], { ...options }); +} diff --git a/packages/typespec-vscode/test/extension/common/emit-steps.ts b/packages/typespec-vscode/test/extension/common/emit-steps.ts index 90a2d93fd0b..40a86282fd9 100644 --- a/packages/typespec-vscode/test/extension/common/emit-steps.ts +++ b/packages/typespec-vscode/test/extension/common/emit-steps.ts @@ -20,6 +20,19 @@ export async function emitSelectType(page: Page, type: string, cs: CaseScreensho "Emitting Server Stub from TypeSpec files. Supported languages are .NET, JavaScript.", }, ]; + await retry( + page, + 3, + async () => { + const selectTypeBox = await page.getByRole("textbox", { + name: "Select an emitter type - Emit", + }); + return (await selectTypeBox.count()) > 0; + }, + `Failed to find the language for code emitting.`, + 2, + cs, + ); await retry( page, 3, diff --git a/packages/typespec-vscode/test/extension/common/utils.ts b/packages/typespec-vscode/test/extension/common/utils.ts index 6b09255db1a..573c043fbae 100644 --- a/packages/typespec-vscode/test/extension/common/utils.ts +++ b/packages/typespec-vscode/test/extension/common/utils.ts @@ -5,9 +5,11 @@ import { test as baseTest, inject } from "vitest"; const __dirname = import.meta.dirname; export const projectRoot = path.resolve(__dirname, "../../../"); +export const repoRoot = path.resolve(projectRoot, "../../"); export const tempDir = path.resolve(projectRoot, "./temp"); export const testfilesDir = path.resolve(projectRoot, "./test/scenarios"); export const imagesPath = path.resolve(tempDir, "./images-linux"); +export const npxCmd = process.platform === "win32" ? "npx.cmd" : "npx"; interface Context { page: Page; diff --git a/packages/typespec-vscode/test/extension/create-typespec.test.ts b/packages/typespec-vscode/test/extension/create-typespec.test.ts index 9e6a2112d83..8cbcd06d118 100644 --- a/packages/typespec-vscode/test/extension/create-typespec.test.ts +++ b/packages/typespec-vscode/test/extension/create-typespec.test.ts @@ -5,7 +5,7 @@ import { beforeEach, describe } from "vitest"; import { contrastResult, preContrastResult, startWithCommandPalette } from "./common/common-steps"; import { inputProjectName, selectEmitters, selectTemplate } from "./common/create-steps"; import { mockShowOpenDialog } from "./common/mock-dialogs"; -import { CaseScreenshot, test, testfilesDir } from "./common/utils"; +import { CaseScreenshot, tempDir, test } from "./common/utils"; enum CreateProjectTriggerType { Click = "RightClick", @@ -21,7 +21,8 @@ type CreateConfigType = { expectedResults: string[]; }; -const CreateTypespecProjectFolderPath = path.resolve(testfilesDir, "CreateTypespecProject"); +// Move to the temp directory to execute the test +const CreateTypespecProjectFolderPath = path.resolve(tempDir, "CreateTypespecProject"); const createCase = "CreateTypespecProject"; const templateName = "Generic Rest API"; diff --git a/packages/typespec-vscode/test/extension/emit-typespec.test.ts b/packages/typespec-vscode/test/extension/emit-typespec.test.ts index dd3c6a4d697..457436d219f 100644 --- a/packages/typespec-vscode/test/extension/emit-typespec.test.ts +++ b/packages/typespec-vscode/test/extension/emit-typespec.test.ts @@ -1,23 +1,28 @@ -import { execSync } from "child_process"; import fs from "node:fs"; import path from "node:path"; -import { beforeEach, describe } from "vitest"; +import { beforeAll, beforeEach, describe } from "vitest"; import { contrastResult, + packagesInstall, + packPackages, preContrastResult, readTspConfigFile, restoreTspConfigFile, startWithCommandPalette, } from "./common/common-steps"; import { emiChooseEmitter, emitSelectLanguage, emitSelectType } from "./common/emit-steps"; -import { CaseScreenshot, test, testfilesDir } from "./common/utils"; +import { CaseScreenshot, tempDir, test, testfilesDir } from "./common/utils"; -try { - execSync("pnpm install @typespec/http-client-csharp", { stdio: "inherit" }); - execSync("pnpm install @typespec/http", { stdio: "inherit" }); -} catch (e) { - process.exit(1); -} +// Test files are copied into the temporary directory before tests run +beforeAll(async () => { + const src = path.resolve(testfilesDir, "EmitTypespecProject"); + const dest = path.resolve(tempDir, "EmitTypespecProject"); + fs.cpSync(src, dest, { recursive: true }); + + const packages = await packPackages(); + // Install those packages locally + await packagesInstall(packages, "Emit"); +}, 300000); enum EmitProjectTriggerType { Command = "Command", @@ -33,24 +38,24 @@ type EmitConfigType = { expectedResults: string[]; }; -const EmitTypespecProjectFolderPath = path.resolve(testfilesDir, "EmitTypespecProject"); +const EmitTypespecProjectFolderPath = path.resolve(tempDir, "EmitTypespecProject"); const EmitCasesConfigList: EmitConfigType[] = [ { - caseName: "EmitTypespecProject ClientCode DotNet Trigger CommandPalette TspconfigHasEmit", + caseName: "EmitTypespecProject ClientCode Js Trigger CommandPalette TspconfigHasEmit", selectType: "Client Code", - selectTypeLanguage: ".NET", + selectTypeLanguage: "JavaScript", triggerType: EmitProjectTriggerType.Command, TspConfigHasEmit: true, - expectedResults: ["http-client-csharp"], + expectedResults: ["http-client-js"], }, { - caseName: "EmitTypespecProject ClientCode DotNet Trigger CommandPalette TspconfigNoEmit", + caseName: "EmitTypespecProject ClientCode Js Trigger CommandPalette TspconfigNoEmit", selectType: "Client Code", - selectTypeLanguage: ".NET", + selectTypeLanguage: "JavaScript", triggerType: EmitProjectTriggerType.Command, TspConfigHasEmit: false, - expectedResults: ["http-client-csharp"], + expectedResults: ["http-client-js"], }, ]; @@ -100,16 +105,5 @@ describe.each(EmitCasesConfigList)("EmitTypespecProject", async (item) => { const resultFilePath = path.resolve(workspacePath, "./tsp-output/@typespec"); await contrastResult(expectedResults, resultFilePath, cs); app.close(); - - try { - execSync("git restore ./package.json", { stdio: "inherit" }); - } catch (e) { - process.exit(1); - } - try { - execSync("git restore ../../pnpm-lock.yaml", { stdio: "inherit" }); - } catch (e) { - process.exit(1); - } }); }); diff --git a/packages/typespec-vscode/test/extension/import-typespec.test.ts b/packages/typespec-vscode/test/extension/import-typespec.test.ts index 3cf76bcc1c5..e1c6a241f66 100644 --- a/packages/typespec-vscode/test/extension/import-typespec.test.ts +++ b/packages/typespec-vscode/test/extension/import-typespec.test.ts @@ -1,17 +1,26 @@ -import { execSync } from "child_process"; import fs from "node:fs"; import path from "node:path"; -import { beforeEach, describe } from "vitest"; -import { contrastResult, preContrastResult, startWithRightClick } from "./common/common-steps"; +import { beforeAll, beforeEach, describe } from "vitest"; +import { + contrastResult, + packagesInstall, + packPackages, + preContrastResult, + startWithRightClick, +} from "./common/common-steps"; import { mockShowOpenDialog } from "./common/mock-dialogs"; -import { CaseScreenshot, test, testfilesDir } from "./common/utils"; +import { CaseScreenshot, tempDir, test, testfilesDir } from "./common/utils"; -try { - execSync("pnpm install @typespec/openapi3", { stdio: "inherit" }); - execSync("pnpm install @typespec/http", { stdio: "inherit" }); -} catch (e) { - process.exit(1); -} +// Test files are copied into the temporary directory before tests run +beforeAll(async () => { + const src = path.resolve(testfilesDir, "ImportTypespecProjectOpenApi3"); + const dest = path.resolve(tempDir, "ImportTypespecProjectOpenApi3"); + fs.cpSync(src, dest, { recursive: true }); + + const packages = await packPackages(); + // Install those packages locally + await packagesInstall(packages, "Import"); +}, 300000); enum ImportProjectTriggerType { CommandPalette = "CommandPalette", @@ -26,9 +35,9 @@ type ImportConfigType = { expectedResults: string[]; }; -const ImportTypespecProjectFolderPath = path.resolve(testfilesDir, "ImportTypespecProjectOpenApi3"); +const ImportTypespecProjectFolderPath = path.resolve(tempDir, "ImportTypespecProjectOpenApi3"); const ImportTypespecProjectEmptyFolderPath = path.resolve( - testfilesDir, + tempDir, "ImportTypespecProjectOpenApi3/ImportTypespecProjectEmptyFolder", ); @@ -38,7 +47,7 @@ ImportCasesConfigList.push({ caseName: "ImportTypespecProject Trigger RightClickOnFolder EmptyFolder", triggerType: ImportProjectTriggerType.RightClickOnFolder, selectFolderEmptyOrNonEmpty: "empty", - expectedResults: ["openapi.3.0.yaml", "ImportTypespecProjectEmptyFolder"], + expectedResults: ["main.tsp"], }); beforeEach(() => { @@ -49,9 +58,6 @@ beforeEach(() => { for (const file of fs.readdirSync(importTypespec)) { if (file === "openapi.3.0.yaml") { hasOpenapi3File = true; - } else if (file !== "ImportTypespecProjectEmptyFolder") { - const filePath = path.resolve(importTypespec, file); - fs.rmSync(filePath, { recursive: true, force: true }); } } if (!hasOpenapi3File) { @@ -91,17 +97,8 @@ describe.each(ImportCasesConfigList)("ImportTypespecFromOpenApi3", async (item) cs, app, ); - await contrastResult(expectedResults, workspacePath, cs); + const resultFilePath = path.resolve(workspacePath, "./ImportTypespecProjectEmptyFolder"); + await contrastResult(expectedResults, resultFilePath, cs); app.close(); - try { - execSync("git restore ./package.json", { stdio: "inherit" }); - } catch (e) { - process.exit(1); - } - try { - execSync("git restore ../../pnpm-lock.yaml", { stdio: "inherit" }); - } catch (e) { - process.exit(1); - } }); }); diff --git a/packages/typespec-vscode/test/extension/preview-typespec.test.ts b/packages/typespec-vscode/test/extension/preview-typespec.test.ts index a256b8a648a..1e11cf61ace 100644 --- a/packages/typespec-vscode/test/extension/preview-typespec.test.ts +++ b/packages/typespec-vscode/test/extension/preview-typespec.test.ts @@ -1,17 +1,20 @@ -import { execSync } from "child_process"; import { rm } from "fs/promises"; import fs from "node:fs"; import path from "node:path"; -import { beforeEach, describe } from "vitest"; -import { startWithCommandPalette } from "./common/common-steps"; -import { CaseScreenshot, retry, test, testfilesDir } from "./common/utils"; +import { beforeAll, beforeEach, describe } from "vitest"; +import { packagesInstall, packPackages, startWithCommandPalette } from "./common/common-steps"; +import { CaseScreenshot, retry, tempDir, test, testfilesDir } from "./common/utils"; -try { - execSync("pnpm install @typespec/http", { stdio: "inherit" }); - execSync("pnpm install @typespec/openapi3", { stdio: "inherit" }); -} catch (e) { - process.exit(1); -} +// Test files are copied into the temporary directory before tests run +beforeAll(async () => { + const src = path.resolve(testfilesDir, "PreviewTypespecProject"); + const dest = path.resolve(tempDir, "PreviewTypespecProject"); + fs.cpSync(src, dest, { recursive: true }); + + const packages = await packPackages(); + // Install those packages locally + await packagesInstall(packages, "Preview"); +}, 300000); export enum PreviewProjectTriggerType { Command = "CommandPalette", @@ -23,7 +26,7 @@ type PreviewConfigType = { triggerType: PreviewProjectTriggerType; }; -const PreviewTypespecProjectFolderPath = path.resolve(testfilesDir, "PreviewTypespecProject"); +const PreviewTypespecProjectFolderPath = path.resolve(tempDir, "PreviewTypespecProject"); const PreviewCaseName = `PreviewTypespecProject`; const PreviewCasesConfigList: PreviewConfigType[] = []; @@ -40,9 +43,6 @@ beforeEach(() => { for (const file of fs.readdirSync(previewTypespec)) { if (file === "main.tsp") { hasMainTsp = true; - } else { - const filePath = path.resolve(previewTypespec, file); - fs.rmSync(filePath, { recursive: true, force: true }); } } if (!hasMainTsp) { @@ -81,15 +81,5 @@ describe.each(PreviewCasesConfigList)("PreviewAPIDocument", async (item) => { ); await rm(cs.caseDir, { recursive: true }); app.close(); - try { - execSync("git restore ./package.json", { stdio: "inherit" }); - } catch (e) { - process.exit(1); - } - try { - execSync("git restore ../../pnpm-lock.yaml", { stdio: "inherit" }); - } catch (e) { - process.exit(1); - } }); }); diff --git a/packages/typespec-vscode/test/scenarios/EmitTypespecProject/tspconfig.yaml b/packages/typespec-vscode/test/scenarios/EmitTypespecProject/tspconfig.yaml index 726ce12d301..6e6e81a0bcb 100644 --- a/packages/typespec-vscode/test/scenarios/EmitTypespecProject/tspconfig.yaml +++ b/packages/typespec-vscode/test/scenarios/EmitTypespecProject/tspconfig.yaml @@ -1,8 +1,8 @@ emit: - "@typespec/openapi3" - - "@typespec/http-client-csharp" + - "@typespec/http-client-js" options: "@typespec/openapi3": emitter-output-dir: "{output-dir}/{emitter-name}" - "@typespec/http-client-csharp": + "@typespec/http-client-js": emitter-output-dir: "{output-dir}/{emitter-name}" diff --git a/packages/typespec-vscode/test/scenarios/ImportTypespecProjectOpenApi3/openapi.3.0.yaml b/packages/typespec-vscode/test/scenarios/ImportTypespecProjectOpenApi3/openapi.3.0.yaml index 4890601e2e9..7968ec98936 100644 --- a/packages/typespec-vscode/test/scenarios/ImportTypespecProjectOpenApi3/openapi.3.0.yaml +++ b/packages/typespec-vscode/test/scenarios/ImportTypespecProjectOpenApi3/openapi.3.0.yaml @@ -1,1208 +1,5 @@ openapi: 3.0.0 info: - title: Text Translation - description: |- - Text translation is a cloud-based REST API feature of the Translator service that uses neural - machine translation technology to enable quick and accurate source-to-target text translation - in real time across all supported languages. - - The following methods are supported by the Text Translation feature: - - Languages. Returns a list of languages supported by Translate, Transliterate, and Dictionary Lookup operations. - - Translate. Renders single source-language text to multiple target-language texts with a single request. - - Transliterate. Converts characters or letters of a source language to the corresponding characters or letters of a target language. - - Detect. Returns the source code language code and a boolean variable denoting whether the detected language is supported for text translation and transliteration. - - Dictionary lookup. Returns equivalent words for the source term in the target language. - - Dictionary example Returns grammatical structure and context examples for the source term and target term pair. - version: "3.0" -tags: [] -paths: - /breaksentence: - post: - operationId: findSentenceBoundaries - summary: Find Sentence Boundaries - description: Find Sentence Boundaries - parameters: - - name: X-ClientTraceId - in: header - required: false - description: A client-generated GUID to uniquely identify the request. - schema: - type: string - - $ref: "#/components/parameters/BreakSentenceParameters.language" - - $ref: "#/components/parameters/BreakSentenceParameters.script" - - name: api-version - in: query - required: true - description: Mandatory API version parameter - schema: - type: string - explode: false - responses: - "200": - description: Response for the Break SEntence API. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/BreakSentenceItem" - default: - description: An unexpected error response. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - content: - application/json: - schema: - $ref: "#/components/schemas/ErrorResponse" - requestBody: - required: true - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/InputTextItem" - description: Defines the content of the request - /dictionary/examples: - post: - operationId: lookupDictionaryExamples - summary: Lookup Dictionary Examples - description: Lookup Dictionary Examples - parameters: - - name: X-ClientTraceId - in: header - required: false - description: A client-generated GUID to uniquely identify the request. - schema: - type: string - - $ref: "#/components/parameters/DictionaryExamplesParameters.from" - - $ref: "#/components/parameters/DictionaryExamplesParameters.to" - - name: api-version - in: query - required: true - description: Mandatory API version parameter - schema: - type: string - explode: false - responses: - "200": - description: Response for the dictionary examples API. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/DictionaryExampleItem" - default: - description: An unexpected error response. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - content: - application/json: - schema: - $ref: "#/components/schemas/ErrorResponse" - requestBody: - required: true - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/DictionaryExampleTextItem" - description: Defines the content of the request - /dictionary/lookup: - post: - operationId: lookupDictionaryEntries - summary: Lookup Dictionary Entries - description: Lookup Dictionary Entries - parameters: - - name: X-ClientTraceId - in: header - required: false - description: A client-generated GUID to uniquely identify the request. - schema: - type: string - - $ref: "#/components/parameters/DictionaryLookupParameters.from" - - $ref: "#/components/parameters/DictionaryLookupParameters.to" - - name: api-version - in: query - required: true - description: Mandatory API version parameter - schema: - type: string - explode: false - responses: - "200": - description: Response for the dictionary lookup API. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/DictionaryLookupItem" - default: - description: An unexpected error response. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - content: - application/json: - schema: - $ref: "#/components/schemas/ErrorResponse" - requestBody: - required: true - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/InputTextItem" - description: Defines the content of the request - /languages: - get: - operationId: getSupportedLanguages - summary: Gets the set of languages currently supported by other operations of the Translator. - description: Gets the set of languages currently supported by other operations of the Translator. - parameters: - - name: X-ClientTraceId - in: header - required: false - description: A client-generated GUID to uniquely identify the request. - schema: - type: string - - $ref: "#/components/parameters/GetSupportedLanguagesParameters.scope" - - $ref: "#/components/parameters/GetSupportedLanguagesParameters.acceptLanguage" - - $ref: "#/components/parameters/GetSupportedLanguagesParameters.ifNoneMatch" - - name: api-version - in: query - required: true - description: Mandatory API version parameter - schema: - type: string - explode: false - responses: - "200": - description: The request has succeeded. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - ETag: - required: true - description: |- - Current value of the entity tag for the requested groups of supported languages. - To make subsequent requests more efficient, the client may send the `ETag` value in an - `If-None-Match` header field. - schema: - type: string - content: - application/json: - schema: - $ref: "#/components/schemas/GetSupportedLanguagesResult" - default: - description: An unexpected error response. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - content: - application/json: - schema: - $ref: "#/components/schemas/ErrorResponse" - /translate: - post: - operationId: translate - summary: Translate Text - description: Translate Text - parameters: - - name: X-ClientTraceId - in: header - required: false - description: A client-generated GUID to uniquely identify the request. - schema: - type: string - - $ref: "#/components/parameters/TranslateParameters.to" - - $ref: "#/components/parameters/TranslateParameters.from" - - $ref: "#/components/parameters/TranslateParameters.textType" - - $ref: "#/components/parameters/TranslateParameters.category" - - $ref: "#/components/parameters/TranslateParameters.profanityAction" - - $ref: "#/components/parameters/TranslateParameters.profanityMarker" - - $ref: "#/components/parameters/TranslateParameters.includeAlignment" - - $ref: "#/components/parameters/TranslateParameters.includeSentenceLength" - - $ref: "#/components/parameters/TranslateParameters.suggestedFrom" - - $ref: "#/components/parameters/TranslateParameters.fromScript" - - $ref: "#/components/parameters/TranslateParameters.toScript" - - $ref: "#/components/parameters/TranslateParameters.allowFallback" - - name: api-version - in: query - required: true - description: Mandatory API version parameter - schema: - type: string - explode: false - responses: - "200": - description: Response for the translation API. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - x-mt-system: - required: true - description: |- - Specifies the system type that was used for translation for each 'to' language requested for translation. - The value is a comma-separated list of strings. Each string indicates a type: - - * Custom - Request includes a custom system and at least one custom system was used during translation. - * Team - All other requests - schema: - type: string - x-metered-usage: - required: true - description: |- - Specifies consumption (the number of characters for which the user will be charged) for the translation - job request. For example, if the word "Hello" is translated from English (en) to French (fr), - this field will return the value '5'. - schema: - type: integer - format: int32 - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/TranslatedTextItem" - default: - description: An unexpected error response. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - content: - application/json: - schema: - $ref: "#/components/schemas/ErrorResponse" - requestBody: - required: true - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/InputTextItem" - description: Defines the content of the request - /transliterate: - post: - operationId: transliterate - summary: Transliterate Text - description: Transliterate Text - parameters: - - name: X-ClientTraceId - in: header - required: false - description: A client-generated GUID to uniquely identify the request. - schema: - type: string - - $ref: "#/components/parameters/TransliterateParameters.language" - - $ref: "#/components/parameters/TransliterateParameters.fromScript" - - $ref: "#/components/parameters/TransliterateParameters.toScript" - - name: api-version - in: query - required: true - description: Mandatory API version parameter - schema: - type: string - explode: false - responses: - "200": - description: Response for the transliteration API. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/TransliteratedText" - default: - description: An unexpected error response. - headers: - X-RequestId: - required: true - description: Value generated by the service to identify the request. It is used for troubleshooting purposes. - schema: - type: string - content: - application/json: - schema: - $ref: "#/components/schemas/ErrorResponse" - requestBody: - required: true - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/InputTextItem" - description: Defines the content of the request -components: - parameters: - BreakSentenceParameters.language: - name: language - in: query - required: false - description: |- - Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. - schema: - type: string - explode: false - BreakSentenceParameters.script: - name: script - in: query - required: false - description: |- - Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. - schema: - type: string - explode: false - DictionaryExamplesParameters.from: - name: from - in: query - required: true - description: |- - Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - schema: - type: string - explode: false - DictionaryExamplesParameters.to: - name: to - in: query - required: true - description: |- - Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - schema: - type: string - explode: false - DictionaryLookupParameters.from: - name: from - in: query - required: true - description: |- - Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - schema: - type: string - explode: false - DictionaryLookupParameters.to: - name: to - in: query - required: true - description: |- - Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - schema: - type: string - explode: false - GetSupportedLanguagesParameters.acceptLanguage: - name: Accept-Language - in: header - required: false - description: |- - The language to use for user interface strings. Some of the fields in the response are names of languages or - names of regions. Use this parameter to define the language in which these names are returned. - The language is specified by providing a well-formed BCP 47 language tag. For instance, use the value `fr` - to request names in French or use the value `zh-Hant` to request names in Chinese Traditional. - Names are provided in the English language when a target language is not specified or when localization - is not available. - schema: - type: string - default: en - GetSupportedLanguagesParameters.ifNoneMatch: - name: If-None-Match - in: header - required: false - description: |- - Passing the value of the ETag response header in an If-None-Match field will allow the service to optimize the response. - If the resource has not been modified, the service will return status code 304 and an empty response body. - schema: - type: string - GetSupportedLanguagesParameters.scope: - name: scope - in: query - required: false - description: |- - A comma-separated list of names defining the group of languages to return. - Allowed group names are: `translation`, `transliteration` and `dictionary`. - If no scope is given, then all groups are returned, which is equivalent to passing - `scope=translation,transliteration,dictionary`. To decide which set of supported languages - is appropriate for your scenario, see the description of the [response object](#response-body). - schema: - type: string - explode: false - TranslateParameters.allowFallback: - name: allowFallback - in: query - required: false - description: |- - Specifies that the service is allowed to fall back to a general system when a custom system doesn't exist. - Possible values are: true (default) or false. - - allowFallback=false specifies that the translation should only use systems trained for the category specified - by the request. If a translation for language X to language Y requires chaining through a pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same category. - If no system is found with the specific category, the request will return a 400 status code. allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system doesn't exist. - schema: - type: boolean - default: true - explode: false - TranslateParameters.category: - name: category - in: query - required: false - description: |- - A string specifying the category (domain) of the translation. This parameter is used to get translations - from a customized system built with Custom Translator. Add the Category ID from your Custom Translator - project details to this parameter to use your deployed customized system. Default value is: general. - schema: - type: string - default: general - explode: false - TranslateParameters.from: - name: from - in: query - required: false - description: |- - Specifies the language of the input text. Find which languages are available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary feature. - Note: the dynamic dictionary feature is case-sensitive. - schema: - type: string - explode: false - TranslateParameters.fromScript: - name: fromScript - in: query - required: false - description: Specifies the script of the input text. - schema: - type: string - explode: false - TranslateParameters.includeAlignment: - name: includeAlignment - in: query - required: false - description: |- - Specifies whether to include alignment projection from source text to translated text. - Possible values are: true or false (default). - schema: - type: boolean - default: false - explode: false - TranslateParameters.includeSentenceLength: - name: includeSentenceLength - in: query - required: false - description: |- - Specifies whether to include sentence boundaries for the input text and the translated text. - Possible values are: true or false (default). - schema: - type: boolean - default: false - explode: false - TranslateParameters.profanityAction: - name: profanityAction - in: query - required: false - description: |- - Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. - schema: - $ref: "#/components/schemas/ProfanityAction" - default: NoAction - explode: false - TranslateParameters.profanityMarker: - name: profanityMarker - in: query - required: false - description: |- - Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. - schema: - $ref: "#/components/schemas/ProfanityMarker" - default: Asterisk - explode: false - TranslateParameters.suggestedFrom: - name: suggestedFrom - in: query - required: false - description: |- - Specifies a fallback language if the language of the input text can't be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. - schema: - type: string - explode: false - TranslateParameters.textType: - name: textType - in: query - required: false - description: |- - Defines whether the text being translated is plain text or HTML text. Any HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. - schema: - $ref: "#/components/schemas/TextType" - default: Plain - explode: false - TranslateParameters.to: - name: to - in: query - required: true - description: |- - Specifies the language of the output text. The target language must be one of the supported languages included - in the translation scope. For example, use to=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in the query string. - For example, use to=de&to=it to translate to German and Italian. - schema: - type: array - items: - type: string - TranslateParameters.toScript: - name: toScript - in: query - required: false - description: Specifies the script of the translated text. - schema: - type: string - explode: false - TransliterateParameters.fromScript: - name: fromScript - in: query - required: true - description: |- - Specifies the script used by the input text. Look up supported languages using the transliteration scope, - to find input scripts available for the selected language. - schema: - type: string - explode: false - TransliterateParameters.language: - name: language - in: query - required: true - description: |- - Specifies the language of the text to convert from one script to another. - Possible languages are listed in the transliteration scope obtained by querying the service - for its supported languages. - schema: - type: string - explode: false - TransliterateParameters.toScript: - name: toScript - in: query - required: true - description: |- - Specifies the output script. Look up supported languages using the transliteration scope, to find output - scripts available for the selected combination of input language and input script. - schema: - type: string - explode: false - schemas: - APIVersion: - type: string - enum: - - "3.0" - description: Text Translation supported versions - BackTranslation: - type: object - required: - - normalizedText - - displayText - - numExamples - - frequencyCount - properties: - normalizedText: - type: string - description: |- - A string giving the normalized form of the source term that is a back-translation of the target. - This value should be used as input to lookup examples. - displayText: - type: string - description: |- - A string giving the source term that is a back-translation of the target in a form best - suited for end-user display. - numExamples: - type: integer - format: int32 - description: |- - An integer representing the number of examples that are available for this translation pair. - Actual examples must be retrieved with a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user interface may add a hyperlink - to the back-translation if the number of examples is greater than zero and show the back-translation - as plain text if there are no examples. Note that the actual number of examples returned - by a call to lookup examples may be less than numExamples, because additional filtering may be - applied on the fly to remove "bad" examples. - frequencyCount: - type: integer - format: int32 - description: |- - An integer representing the frequency of this translation pair in the data. The main purpose of this - field is to provide a user interface with a means to sort back-translations so the most frequent terms are first. - description: Back Translation - BreakSentenceItem: - type: object - required: - - sentLen - properties: - detectedLanguage: - allOf: - - $ref: "#/components/schemas/DetectedLanguage" - description: The detectedLanguage property is only present in the result object when language auto-detection is requested. - sentLen: - type: array - items: - type: integer - format: int32 - description: |- - An integer array representing the lengths of the sentences in the input text. - The length of the array is the number of sentences, and the values are the length of each sentence. - description: Item containing break sentence result. - DetectedLanguage: - type: object - required: - - language - - score - properties: - language: - type: string - description: A string representing the code of the detected language. - score: - type: number - format: float - description: |- - A float value indicating the confidence in the result. - The score is between zero and one and a low score indicates a low confidence. - description: An object describing the detected language. - DictionaryExample: - type: object - required: - - sourcePrefix - - sourceTerm - - sourceSuffix - - targetPrefix - - targetTerm - - targetSuffix - properties: - sourcePrefix: - type: string - description: |- - The string to concatenate before the value of sourceTerm to form a complete example. - Do not add a space character, since it is already there when it should be. - This value may be an empty string. - sourceTerm: - type: string - description: |- - A string equal to the actual term looked up. The string is added with sourcePrefix - and sourceSuffix to form the complete example. Its value is separated so it can be - marked in a user interface, e.g., by bolding it. - sourceSuffix: - type: string - description: |- - The string to concatenate after the value of sourceTerm to form a complete example. - Do not add a space character, since it is already there when it should be. - This value may be an empty string. - targetPrefix: - type: string - description: A string similar to sourcePrefix but for the target. - targetTerm: - type: string - description: A string similar to sourceTerm but for the target. - targetSuffix: - type: string - description: A string similar to sourceSuffix but for the target. - description: Dictionary Example - DictionaryExampleItem: - type: object - required: - - normalizedSource - - normalizedTarget - - examples - properties: - normalizedSource: - type: string - description: |- - A string giving the normalized form of the source term. Generally, this should be identical - to the value of the Text field at the matching list index in the body of the request. - normalizedTarget: - type: string - description: |- - A string giving the normalized form of the target term. Generally, this should be identical - to the value of the Translation field at the matching list index in the body of the request. - examples: - type: array - items: - $ref: "#/components/schemas/DictionaryExample" - description: A list of examples for the (source term, target term) pair. - description: Dictionary Example element - DictionaryExampleTextItem: - type: object - required: - - translation - properties: - translation: - type: string - description: |- - A string specifying the translated text previously returned by the Dictionary lookup operation. - This should be the value from the normalizedTarget field in the translations list of the Dictionary - lookup response. The service will return examples for the specific source-target word-pair. - allOf: - - $ref: "#/components/schemas/InputTextItem" - description: Element containing the text with translation. - DictionaryLookupItem: - type: object - required: - - normalizedSource - - displaySource - - translations - properties: - normalizedSource: - type: string - description: |- - A string giving the normalized form of the source term. - For example, if the request is "JOHN", the normalized form will be "john". - The content of this field becomes the input to lookup examples. - displaySource: - type: string - description: |- - A string giving the source term in a form best suited for end-user display. - For example, if the input is "JOHN", the display form will reflect the usual - spelling of the name: "John". - translations: - type: array - items: - $ref: "#/components/schemas/DictionaryTranslation" - description: A list of translations for the source term. - description: Dictionary Lookup Element - DictionaryTranslation: - type: object - required: - - normalizedTarget - - displayTarget - - posTag - - confidence - - prefixWord - - backTranslations - properties: - normalizedTarget: - type: string - description: |- - A string giving the normalized form of this term in the target language. - This value should be used as input to lookup examples. - displayTarget: - type: string - description: |- - A string giving the term in the target language and in a form best suited - for end-user display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" will have - normalizedTarget = "juan" and displayTarget = "Juan". - posTag: - type: string - description: A string associating this term with a part-of-speech tag. - confidence: - type: number - format: float - description: |- - A value between 0.0 and 1.0 which represents the "confidence" - (or perhaps more accurately, "probability in the training data") of that translation pair. - The sum of confidence scores for one source word may or may not sum to 1.0. - prefixWord: - type: string - description: |- - A string giving the word to display as a prefix of the translation. Currently, - this is the gendered determiner of nouns, in languages that have gendered determiners. - For example, the prefix of the Spanish word "mosca" is "la", since "mosca" is a feminine noun in Spanish. - This is only dependent on the translation, and not on the source. - If there is no prefix, it will be the empty string. - backTranslations: - type: array - items: - $ref: "#/components/schemas/BackTranslation" - description: |- - A list of "back translations" of the target. For example, source words that the target can translate to. - The list is guaranteed to contain the source word that was requested (e.g., if the source word being - looked up is "fly", then it is guaranteed that "fly" will be in the backTranslations list). - However, it is not guaranteed to be in the first position, and often will not be. - description: Translation source term. - ErrorDetails: - type: object - required: - - code - - message - properties: - code: - type: integer - format: int32 - description: Number identifier of the error. - message: - type: string - description: Human readable error description. - description: Error details as returned by Translator Service. - ErrorResponse: - type: object - required: - - error - properties: - error: - allOf: - - $ref: "#/components/schemas/ErrorDetails" - description: Error details. - description: Representation of the Error Response from Translator Service. - GetSupportedLanguagesResult: - type: object - properties: - translation: - type: object - additionalProperties: - $ref: "#/components/schemas/TranslationLanguage" - description: Languages that support translate API. - transliteration: - type: object - additionalProperties: - $ref: "#/components/schemas/TransliterationLanguage" - description: Languages that support transliteration API. - dictionary: - type: object - additionalProperties: - $ref: "#/components/schemas/SourceDictionaryLanguage" - description: Languages that support dictionary API. - description: Response for the languages API. - InputTextItem: - type: object - required: - - text - properties: - text: - type: string - description: Text to translate. - description: Element containing the text for translation. - LanguageDirectionality: - type: string - enum: - - ltr - - rtl - description: Language Directionality - LanguageScript: - type: object - required: - - code - - name - - nativeName - - dir - properties: - code: - type: string - description: Code identifying the script. - name: - type: string - description: Display name of the script in the locale requested via Accept-Language header. - nativeName: - type: string - description: Display name of the language in the locale native for the language. - dir: - allOf: - - $ref: "#/components/schemas/LanguageDirectionality" - description: Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - description: Common properties of language script - ProfanityAction: - type: string - enum: - - NoAction - - Marked - - Deleted - description: Translator profanity actions - ProfanityMarker: - type: string - enum: - - Asterisk - - Tag - description: Translator profanity markers - SentenceBoundaries: - type: object - required: - - srcSentLen - - transSentLen - properties: - srcSentLen: - type: array - items: - type: integer - format: int32 - description: |- - An integer array representing the lengths of the sentences in the input text. - The length of the array is the number of sentences, and the values are the length of each sentence. - transSentLen: - type: array - items: - type: integer - format: int32 - description: |- - An integer array representing the lengths of the sentences in the translated text. - The length of the array is the number of sentences, and the values are the length of each sentence. - description: An object returning sentence boundaries in the input and output texts. - SourceDictionaryLanguage: - type: object - required: - - name - - nativeName - - dir - - translations - properties: - name: - type: string - description: Display name of the language in the locale requested via Accept-Language header. - nativeName: - type: string - description: Display name of the language in the locale native for this language. - dir: - allOf: - - $ref: "#/components/schemas/LanguageDirectionality" - description: Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - translations: - type: array - items: - $ref: "#/components/schemas/TargetDictionaryLanguage" - description: List of languages with alterative translations and examples for the query expressed in the source language. - description: Properties ot the source dictionary language - SourceText: - type: object - required: - - text - properties: - text: - type: string - description: Input text in the default script of the source language. - description: "Input text in the default script of the source language. " - TargetDictionaryLanguage: - type: object - required: - - name - - nativeName - - dir - - code - properties: - name: - type: string - description: Display name of the language in the locale requested via Accept-Language header. - nativeName: - type: string - description: Display name of the language in the locale native for this language. - dir: - allOf: - - $ref: "#/components/schemas/LanguageDirectionality" - description: Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - code: - type: string - description: Language code identifying the target language. - description: Properties of the target dictionary language - TextType: - anyOf: - - type: string - - type: string - enum: - - Plain - - Html - description: Translation text type - TranslatedTextAlignment: - type: object - required: - - proj - properties: - proj: - type: string - description: |- - Maps input text to translated text. The alignment information is only provided when the request - parameter includeAlignment is true. Alignment is returned as a string value of the following - format: [[SourceTextStartIndex]:[SourceTextEndIndex]–[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the languages, and space separates the words. - One word may align with zero, one, or multiple words in the other language, and the aligned words may - be non-contiguous. When no alignment information is available, the alignment element will be empty. - description: Alignment information object. - TranslatedTextItem: - type: object - required: - - translations - properties: - detectedLanguage: - allOf: - - $ref: "#/components/schemas/DetectedLanguage" - description: The detectedLanguage property is only present in the result object when language auto-detection is requested. - translations: - type: array - items: - $ref: "#/components/schemas/TranslationText" - description: |- - An array of translation results. The size of the array matches the number of target - languages specified through the to query parameter. - sourceText: - allOf: - - $ref: "#/components/schemas/SourceText" - description: |- - Input text in the default script of the source language. sourceText property is present only when - the input is expressed in a script that's not the usual script for the language. For example, - if the input were Arabic written in Latin script, then sourceText.text would be the same Arabic text - converted into Arab script. - description: Element containing the translated text - TranslationLanguage: - type: object - required: - - name - - nativeName - - dir - properties: - name: - type: string - description: Display name of the language in the locale requested via Accept-Language header. - nativeName: - type: string - description: Display name of the language in the locale native for this language. - dir: - allOf: - - $ref: "#/components/schemas/LanguageDirectionality" - description: Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - description: |- - The value of the translation property is a dictionary of (key, value) pairs. Each key is a BCP 47 language tag. - A key identifies a language for which text can be translated to or translated from. - TranslationText: - type: object - required: - - to - - text - properties: - to: - type: string - description: A string representing the language code of the target language. - text: - type: string - description: A string giving the translated text. - transliteration: - allOf: - - $ref: "#/components/schemas/TransliteratedText" - description: An object giving the translated text in the script specified by the toScript parameter. - alignment: - allOf: - - $ref: "#/components/schemas/TranslatedTextAlignment" - description: Alignment information. - sentLen: - allOf: - - $ref: "#/components/schemas/SentenceBoundaries" - description: Sentence boundaries in the input and output texts. - description: Translation result - TransliterableScript: - type: object - required: - - toScripts - properties: - toScripts: - type: array - items: - $ref: "#/components/schemas/LanguageScript" - description: List of scripts available to convert text to. - allOf: - - $ref: "#/components/schemas/LanguageScript" - description: Script definition with list of script into which given script can be translitered. - TransliteratedText: - type: object - required: - - text - - script - properties: - text: - type: string - description: A string which is the result of converting the input string to the output script. - script: - type: string - description: A string specifying the script used in the output. - description: Transliterated text element. - TransliterationLanguage: - type: object - required: - - name - - nativeName - - scripts - properties: - name: - type: string - description: Display name of the language in the locale requested via Accept-Language header. - nativeName: - type: string - description: Display name of the language in the locale native for this language. - scripts: - type: array - items: - $ref: "#/components/schemas/TransliterableScript" - description: List of scripts to convert from. - description: |- - The value of the transliteration property is a dictionary of (key, value) pairs. - Each key is a BCP 47 language tag. A key identifies a language for which text can be converted from one script - to another script. -servers: - - url: "{Endpoint}" - description: Text translation is a cloud-based REST API feature of the Translator service that uses neural machine translation technology to enable quick and accurate source-to-target text translation in real time across all supported languages. - variables: - Endpoint: - default: "" - description: |- - Supported Text Translation endpoints (protocol and hostname, for example: - https://api.cognitive.microsofttranslator.com). + title: Minimal API + version: "1.0.0" +paths: {}