Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix named union issue and integrate the test case for unions #2154

Merged
merged 8 commits into from
Dec 5, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions packages/typespec-ts/src/transform/transformSchemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,9 @@ export function transformSchemas(
getGeneratedModels(indexer.value, context);
}
for (const prop of model.properties) {
const [, propType] = prop;
if (
prop[1].type.kind === "Model" &&
propType.type.kind === "Model" &&
MaryGao marked this conversation as resolved.
Show resolved Hide resolved
(!program.stateMap(modelKey).get(prop[1].type) ||
!program.stateMap(modelKey).get(prop[1].type)?.includes(context))
) {
Expand All @@ -141,12 +142,11 @@ export function transformSchemas(
getGeneratedModels(prop[1].type, context);
}
if (
prop[1].type.kind === "Union" &&
propType.type.kind === "Union" &&
(!program.stateMap(modelKey).get(prop[1].type) ||
!program.stateMap(modelKey).get(prop[1].type)?.includes(context))
) {
const variants = Array.from(prop[1].type.variants.values());
let hasModels = false;
const variants = Array.from(propType.type.variants.values());
for (const variant of variants) {
if (
(variant.type.kind === "Model" ||
Expand All @@ -157,12 +157,12 @@ export function transformSchemas(
.get(variant.type)
?.includes(context))
) {
hasModels = true;
getGeneratedModels(variant.type, context);
}
}
if (hasModels) {
setModelMap(prop[1].type, context);
// build type details for named union
if (!propType.type.expression) {
setModelMap(propType.type, context);
}
}
}
Expand All @@ -189,18 +189,17 @@ export function transformSchemas(
}
} else if (model.kind === "Union") {
const variants = Array.from(model.variants.values());
let hasModels = false;
for (const variant of variants) {
if (
(variant.type.kind === "Model" || variant.type.kind === "Union") &&
(!program.stateMap(modelKey).get(variant.type) ||
!program.stateMap(modelKey).get(variant.type)?.includes(context))
) {
hasModels = true;
getGeneratedModels(variant.type, context);
}
}
if (hasModels) {
// build type details for named union
if (!model.expression) {
setModelMap(model, context);
}
}
Expand Down
9 changes: 4 additions & 5 deletions packages/typespec-ts/test/commands/cadl-ranch-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,10 @@ export const rlcTsps: TypeSpecRanchConfig[] = [
outputPath: "specialWords",
inputPath: "special-words"
},
// TODO: union has issues need to fix in https://github.com/Azure/autorest.typescript/issues/2141
// {
// outputPath: "unions",
// inputPath: "type/union"
// },
{
outputPath: "unions",
inputPath: "type/union"
},
{
outputPath: "parameters/collection-format",
inputPath: "parameters/collection-format"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"plugins": ["@azure/azure-sdk"],
"extends": ["plugin:@azure/azure-sdk/azure-sdk-base"],
"rules": {
"@azure/azure-sdk/ts-modules-only-named": "warn",
"@azure/azure-sdk/ts-apiextractor-json-types": "warn",
"@azure/azure-sdk/ts-package-json-types": "warn",
"@azure/azure-sdk/ts-package-json-engine-is-present": "warn",
"tsdoc/syntax": "warn"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Unions REST client library for JavaScript

Describe scenarios for various combinations of unions.

**Please rely heavily on our [REST client docs](https://github.com/Azure/azure-sdk-for-js/blob/main/documentation/rest-clients.md) to use this library**

Key links:

- [Package (NPM)](https://www.npmjs.com/package/@msinternal/unions)

## Getting started

### Currently supported environments

- LTS versions of Node.js

### Prerequisites

- You must have an [Azure subscription](https://azure.microsoft.com/free/) to use this package.

### Install the `@msinternal/unions` package

Install the Unions REST client REST client library for JavaScript with `npm`:

```bash
npm install @msinternal/unions
```

### Create and authenticate a `UnionsClient`

To use an [Azure Active Directory (AAD) token credential](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-a-pre-fetched-access-token),
provide an instance of the desired credential type obtained from the
[@azure/identity](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#credentials) library.

To authenticate with AAD, you must first `npm` install [`@azure/identity`](https://www.npmjs.com/package/@azure/identity)

After setup, you can choose which type of [credential](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#credentials) from `@azure/identity` to use.
As an example, [DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential)
can be used to authenticate the client.

Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables:
AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET

## Troubleshooting

### Logging

Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`:

```javascript
const { setLogLevel } = require("@azure/logger");

setLogLevel("info");
```

For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger).
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
"mainEntryPointFilePath": "./types/index.d.ts",
"docModel": { "enabled": true },
"apiReport": { "enabled": true, "reportFolder": "./review" },
"dtsRollup": {
"enabled": true,
"untrimmedFilePath": "",
"publicTrimmedFilePath": "./types/unions.d.ts"
},
"messages": {
"tsdocMessageReporting": { "default": { "logLevel": "none" } },
"extractorMessageReporting": {
"ae-missing-release-tag": { "logLevel": "none" },
"ae-unresolved-link": { "logLevel": "none" }
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
{
"name": "@msinternal/unions",
"sdk-type": "client",
"author": "Microsoft Corporation",
"version": "1.0.0-beta.1",
"description": "Unions Test Service",
"keywords": ["node", "azure", "cloud", "typescript", "browser", "isomorphic"],
"license": "MIT",
"main": "dist/index.js",
"module": "./dist-esm/index.js",
"types": "./types/unions.d.ts",
"repository": "github:Azure/azure-sdk-for-js",
"bugs": { "url": "https://github.com/Azure/azure-sdk-for-js/issues" },
"files": [
"dist/",
"dist-esm/",
"types/unions.d.ts",
"README.md",
"LICENSE",
"review/*"
],
"engines": { "node": ">=18.0.0" },
"scripts": {
"audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit",
"build:browser": "echo skipped.",
"build:node": "echo skipped.",
"build:samples": "echo skipped.",
"build:test": "echo skipped.",
"build:debug": "echo skipped.",
"check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"samples-dev/**/*.ts\"",
"clean": "rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz *.log",
"execute:samples": "echo skipped",
"extract-api": "rimraf review && mkdirp ./review && api-extractor run --local",
"format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"samples-dev/**/*.ts\"",
"generate:client": "echo skipped",
"integration-test:browser": "echo skipped",
"integration-test:node": "echo skipped",
"integration-test": "echo skipped",
"lint:fix": "eslint package.json api-extractor.json src --ext .ts --fix --fix-type [problem,suggestion]",
"lint": "eslint package.json api-extractor.json src --ext .ts",
"pack": "npm pack 2>&1",
"test:browser": "echo skipped",
"test:node": "echo skipped",
"test": "echo \"Error: no test specified\" && exit 1",
"unit-test": "echo skipped",
"unit-test:node": "echo skipped",
"unit-test:browser": "echo skipped",
"build": "npm run clean && tsc && rollup -c 2>&1 && npm run minify && mkdirp ./review && npm run extract-api",
"minify": "uglifyjs -c -m --comments --source-map \"content='./dist/index.js.map'\" -o ./dist/index.min.js ./dist/index.js"
},
"sideEffects": false,
"autoPublish": false,
"dependencies": {
"@azure/core-auth": "^1.3.0",
"@azure-rest/core-client": "^1.1.4",
"@azure/core-rest-pipeline": "^1.12.0",
"@azure/logger": "^1.0.0",
"tslib": "^2.2.0"
},
"devDependencies": {
"@microsoft/api-extractor": "^7.31.1",
"autorest": "latest",
"@types/node": "^18.0.0",
"dotenv": "^16.0.0",
"eslint": "^8.0.0",
"mkdirp": "^2.1.2",
"prettier": "^2.5.1",
"rimraf": "^5.0.0",
"source-map-support": "^0.5.9",
"typescript": "~5.2.0",
"@rollup/plugin-commonjs": "^24.0.0",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-multi-entry": "^6.0.0",
"@rollup/plugin-node-resolve": "^13.1.3",
"rollup": "^2.66.1",
"rollup-plugin-sourcemaps": "^0.6.3",
"uglify-js": "^3.4.9"
},
"type": "module",
"//sampleConfiguration": {
"productName": "TypeUnion",
"productSlugs": ["azure"],
"disableDocsMs": true,
"apiRefLink": "https://docs.microsoft.com/javascript/api/@msinternal/unions?view=azure-node-preview"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import nodeResolve from "@rollup/plugin-node-resolve";
import cjs from "@rollup/plugin-commonjs";
import sourcemaps from "rollup-plugin-sourcemaps";
import multiEntry from "@rollup/plugin-multi-entry";
import json from "@rollup/plugin-json";

import nodeBuiltins from "builtin-modules";

// #region Warning Handler

/**
* A function that can determine whether a rollup warning should be ignored. If
* the function returns `true`, then the warning will not be displayed.
*/

function ignoreNiseSinonEval(warning) {
return (
warning.code === "EVAL" &&
warning.id &&
(warning.id.includes("node_modules/nise") ||
warning.id.includes("node_modules/sinon")) === true
);
}

function ignoreChaiCircularDependency(warning) {
return (
warning.code === "CIRCULAR_DEPENDENCY" &&
warning.importer &&
warning.importer.includes("node_modules/chai") === true
);
}

const warningInhibitors = [ignoreChaiCircularDependency, ignoreNiseSinonEval];

/**
* Construct a warning handler for the shared rollup configuration
* that ignores certain warnings that are not relevant to testing.
*/
function makeOnWarnForTesting() {
return (warning, warn) => {
// If every inhibitor returns false (i.e. no inhibitors), then show the warning
if (warningInhibitors.every((inhib) => !inhib(warning))) {
warn(warning);
}
};
}

// #endregion

function makeBrowserTestConfig() {
const config = {
input: {
include: ["dist-esm/test/**/*.spec.js"],
exclude: ["dist-esm/test/**/node/**"],
},
output: {
file: `dist-test/index.browser.js`,
format: "umd",
sourcemap: true,
},
preserveSymlinks: false,
plugins: [
multiEntry({ exports: false }),
nodeResolve({
mainFields: ["module", "browser"],
}),
cjs(),
json(),
sourcemaps(),
//viz({ filename: "dist-test/browser-stats.html", sourcemap: true })
],
onwarn: makeOnWarnForTesting(),
// Disable tree-shaking of test code. In rollup-plugin-node-resolve@5.0.0,
// rollup started respecting the "sideEffects" field in package.json. Since
// our package.json sets "sideEffects=false", this also applies to test
// code, which causes all tests to be removed by tree-shaking.
treeshake: false,
};

return config;
}

const defaultConfigurationOptions = {
disableBrowserBundle: false,
};

export function makeConfig(pkg, options) {
options = {
...defaultConfigurationOptions,
...(options || {}),
};

const baseConfig = {
// Use the package's module field if it has one
input: pkg["module"] || "dist-esm/src/index.js",
external: [
...nodeBuiltins,
...Object.keys(pkg.dependencies),
...Object.keys(pkg.devDependencies),
],
output: { file: "dist/index.js", format: "cjs", sourcemap: true },
preserveSymlinks: false,
plugins: [sourcemaps(), nodeResolve()],
};

const config = [baseConfig];

if (!options.disableBrowserBundle) {
config.push(makeBrowserTestConfig());
}

return config;
}

export default makeConfig(require("./package.json"));
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import createUnionsClient from "@msinternal/unions";
import * as dotenv from "dotenv";

dotenv.config();

/**
* This sample demonstrates how to call operation Get
*
* @summary call operation Get
*/
async function enumsOnlyGetSample() {
const client = createUnionsClient();
const result = await client.path("/type/union/enums-only").get();
console.log(result);
}

async function main() {
enumsOnlyGetSample();
}

main().catch(console.error);
Loading
Loading