зеркало из https://github.com/Azure/autorest.git
Merge openapi to cadl plugin (#4664)
This commit is contained in:
Родитель
391dc5ca05
Коммит
90437047e9
|
@ -337,3 +337,6 @@ packages/extensions/core/test/plugins/*/expected/*.json
|
|||
|
||||
# MICROSOFT SECURITY.md
|
||||
/SECURITY.md
|
||||
|
||||
# Generated cadl
|
||||
packages/extensions/openapi-to-cadl/test/**/*.cadl
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"changes": [
|
||||
{
|
||||
"packageName": "@autorest/openapi-to-cadl",
|
||||
"comment": "Introducing the OpenAPI to CADL plugin",
|
||||
"type": "patch"
|
||||
}
|
||||
],
|
||||
"packageName": "@autorest/openapi-to-cadl"
|
||||
}
|
|
@ -37,5 +37,8 @@
|
|||
// "typescript": [
|
||||
// "~2.4.0"
|
||||
// ]
|
||||
"@cadl-lang/compiler": ["~0.31.0"],
|
||||
"@azure-tools/cadl-autorest": ["^0.22.0"],
|
||||
"ts-node": ["^10.9.1"]
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,11 +2,19 @@ lockfileVersion: 5.3
|
|||
|
||||
specifiers:
|
||||
'@azure-tools/async-io': ~3.0.0
|
||||
'@azure-tools/cadl-autorest': ^0.20.0
|
||||
'@azure-tools/cadl-azure-core': ^0.9.0
|
||||
'@azure-tools/cadl-python': ^0.4.10
|
||||
'@azure-tools/object-comparison': ~3.0.0
|
||||
'@azure-tools/tasks': ~3.0.0
|
||||
'@azure-tools/uri': ~3.1.1
|
||||
'@azure/logger': ^1.0.2
|
||||
'@cadl-lang/compiler': ~0.31.0
|
||||
'@cadl-lang/compiler': ^0.37.0
|
||||
'@cadl-lang/openapi': ^0.11.0
|
||||
'@cadl-lang/openapi3': ^0.14.0
|
||||
'@cadl-lang/prettier-plugin-cadl': ^0.5.17
|
||||
'@cadl-lang/rest': ^0.19.0
|
||||
'@cadl-lang/versioning': ^0.10.0
|
||||
'@rush-temp/autorest': file:./projects/autorest.tgz
|
||||
'@rush-temp/cadl': file:./projects/cadl.tgz
|
||||
'@rush-temp/codegen': file:./projects/codegen.tgz
|
||||
|
@ -25,6 +33,7 @@ specifiers:
|
|||
'@rush-temp/modelerfour': file:./projects/modelerfour.tgz
|
||||
'@rush-temp/oai2-to-oai3': file:./projects/oai2-to-oai3.tgz
|
||||
'@rush-temp/openapi': file:./projects/openapi.tgz
|
||||
'@rush-temp/openapi-to-cadl': file:./projects/openapi-to-cadl.tgz
|
||||
'@rush-temp/schemas': file:./projects/schemas.tgz
|
||||
'@rush-temp/system-requirements': file:./projects/system-requirements.tgz
|
||||
'@rush-temp/test-public-packages': file:./projects/test-public-packages.tgz
|
||||
|
@ -34,6 +43,7 @@ specifiers:
|
|||
'@types/command-exists': ~1.2.0
|
||||
'@types/commonmark': ^0.27.0
|
||||
'@types/diff': ^4.0.2
|
||||
'@types/fs-extra': ^9.0.13
|
||||
'@types/glob': ^7.1.3
|
||||
'@types/jest': ^29.2.3
|
||||
'@types/js-yaml': ~4.0.0
|
||||
|
@ -41,6 +51,7 @@ specifiers:
|
|||
'@types/node': ~14.14.20
|
||||
'@types/npm-package-arg': ^6.1.0
|
||||
'@types/pacote': 11.1.3
|
||||
'@types/prettier': ^2.7.0
|
||||
'@types/semver': 5.5.0
|
||||
'@types/source-map-support': ^0.5.3
|
||||
'@types/webpack': ~4.41.26
|
||||
|
@ -65,6 +76,7 @@ specifiers:
|
|||
eslint-plugin-prettier: ~4.2.1
|
||||
eslint-plugin-unicorn: ~44.0.2
|
||||
expect: ~26.6.2
|
||||
fs-extra: ^10.1.0
|
||||
glob: ~7.1.4
|
||||
jest: ^29.3.1
|
||||
jest-snapshot: ~26.6.2
|
||||
|
@ -104,11 +116,19 @@ specifiers:
|
|||
|
||||
dependencies:
|
||||
'@azure-tools/async-io': 3.0.254
|
||||
'@azure-tools/cadl-autorest': 0.20.0_7bb8c157cd14650f0893a032b45ea3ab
|
||||
'@azure-tools/cadl-azure-core': 0.9.0_d21a2f9719b9a9b97180252366891ee1
|
||||
'@azure-tools/cadl-python': 0.4.10_e47e309b36bca5141b312b3070791b1c
|
||||
'@azure-tools/object-comparison': 3.0.253
|
||||
'@azure-tools/tasks': 3.0.255
|
||||
'@azure-tools/uri': 3.1.1
|
||||
'@azure/logger': 1.0.3
|
||||
'@cadl-lang/compiler': 0.31.0
|
||||
'@cadl-lang/compiler': 0.37.0
|
||||
'@cadl-lang/openapi': 0.11.0_d21a2f9719b9a9b97180252366891ee1
|
||||
'@cadl-lang/openapi3': 0.14.0_54d7e0469b3f026a67a13d2bc5d9b3d4
|
||||
'@cadl-lang/prettier-plugin-cadl': 0.5.17
|
||||
'@cadl-lang/rest': 0.19.0_@cadl-lang+compiler@0.37.0
|
||||
'@cadl-lang/versioning': 0.10.0
|
||||
'@rush-temp/autorest': file:projects/autorest.tgz_ts-node@9.1.1
|
||||
'@rush-temp/cadl': file:projects/cadl.tgz_ts-node@9.1.1+webpack@5.40.0
|
||||
'@rush-temp/codegen': file:projects/codegen.tgz_prettier@2.7.1+ts-node@9.1.1
|
||||
|
@ -127,6 +147,7 @@ dependencies:
|
|||
'@rush-temp/modelerfour': file:projects/modelerfour.tgz_ts-node@9.1.1
|
||||
'@rush-temp/oai2-to-oai3': file:projects/oai2-to-oai3.tgz_prettier@2.7.1+ts-node@9.1.1
|
||||
'@rush-temp/openapi': file:projects/openapi.tgz_prettier@2.7.1+ts-node@9.1.1
|
||||
'@rush-temp/openapi-to-cadl': file:projects/openapi-to-cadl.tgz_jest@29.3.1
|
||||
'@rush-temp/schemas': file:projects/schemas.tgz
|
||||
'@rush-temp/system-requirements': file:projects/system-requirements.tgz_prettier@2.7.1+ts-node@9.1.1
|
||||
'@rush-temp/test-public-packages': file:projects/test-public-packages.tgz_prettier@2.7.1
|
||||
|
@ -136,6 +157,7 @@ dependencies:
|
|||
'@types/command-exists': 1.2.0
|
||||
'@types/commonmark': 0.27.5
|
||||
'@types/diff': 4.0.2
|
||||
'@types/fs-extra': 9.0.13
|
||||
'@types/glob': 7.2.0
|
||||
'@types/jest': 29.2.3
|
||||
'@types/js-yaml': 4.0.5
|
||||
|
@ -143,6 +165,7 @@ dependencies:
|
|||
'@types/node': 14.14.45
|
||||
'@types/npm-package-arg': 6.1.1
|
||||
'@types/pacote': 11.1.3
|
||||
'@types/prettier': 2.7.1
|
||||
'@types/semver': 5.5.0
|
||||
'@types/source-map-support': 0.5.6
|
||||
'@types/webpack': 4.41.33
|
||||
|
@ -167,6 +190,7 @@ dependencies:
|
|||
eslint-plugin-prettier: 4.2.1_eslint@8.28.0+prettier@2.7.1
|
||||
eslint-plugin-unicorn: 44.0.2_eslint@8.28.0
|
||||
expect: 26.6.2
|
||||
fs-extra: 10.1.0
|
||||
glob: 7.1.7
|
||||
jest: 29.3.1_5076b77de2277d7bd3e529e70437d1c6
|
||||
jest-snapshot: 26.6.2
|
||||
|
@ -214,6 +238,22 @@ packages:
|
|||
'@jridgewell/trace-mapping': 0.3.17
|
||||
dev: false
|
||||
|
||||
/@autorest/python/6.2.9:
|
||||
resolution: {integrity: sha512-qaxuB+UJ6Ab8s8B0kwxvvrkWfWb33g8ed25NnetTxXE5RZKBouplMcDl6AWhWAWwRknEZQQAfdBbPF9QGBR0RA==}
|
||||
requiresBuild: true
|
||||
dependencies:
|
||||
'@autorest/system-requirements': 1.0.1
|
||||
dev: false
|
||||
|
||||
/@autorest/system-requirements/1.0.1:
|
||||
resolution: {integrity: sha512-DD/hU9ZhsTFGd8Y/AwbFSpKRxpX0mEJ7COTjpQLYQaWXzJXHSmTe3gOUpi+O0whEP9F3drTS5Ob0CirEkaGa4w==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
dependencies:
|
||||
'@azure/logger': 1.0.3
|
||||
command-exists: 1.2.9
|
||||
semver: 7.3.8
|
||||
dev: false
|
||||
|
||||
/@azure-tools/async-io/3.0.254:
|
||||
resolution: {integrity: sha512-X1C7XdyCuo50ch9FzKtTvmK18FgDxxf1Bbt3cSoknQqeDaRegHSSCO+zByq2YA4NvUzKXeZ1engh29IDxZXgpQ==}
|
||||
engines: {node: '>=10.12.0'}
|
||||
|
@ -222,6 +262,63 @@ packages:
|
|||
proper-lockfile: 2.0.1
|
||||
dev: false
|
||||
|
||||
/@azure-tools/cadl-autorest/0.20.0_7bb8c157cd14650f0893a032b45ea3ab:
|
||||
resolution: {integrity: sha512-2nwa0yLJqUAyQ41oS6sNiKdjlMI2sX6qFJfb4SBoWQhxSiX67V5cbJ3b+fqCRherjYB4geF5s61DjOKgjh40zg==}
|
||||
engines: {node: '>=16.0.0'}
|
||||
peerDependencies:
|
||||
'@azure-tools/cadl-azure-core': ~0.7.0
|
||||
'@cadl-lang/compiler': ~0.35.0
|
||||
'@cadl-lang/openapi': ~0.12.0
|
||||
'@cadl-lang/rest': ~0.17.0
|
||||
'@cadl-lang/versioning': ~0.8.0
|
||||
dependencies:
|
||||
'@azure-tools/cadl-azure-core': 0.9.0_d21a2f9719b9a9b97180252366891ee1
|
||||
'@cadl-lang/compiler': 0.37.0
|
||||
'@cadl-lang/openapi': 0.11.0_d21a2f9719b9a9b97180252366891ee1
|
||||
'@cadl-lang/rest': 0.19.0_@cadl-lang+compiler@0.37.0
|
||||
'@cadl-lang/versioning': 0.10.0
|
||||
dev: false
|
||||
|
||||
/@azure-tools/cadl-azure-core/0.9.0_d21a2f9719b9a9b97180252366891ee1:
|
||||
resolution: {integrity: sha512-iGBI9YmRIoUpM0aDC0jhv9IIDQgA3f32h3af/8dBZ38b8TPmFkWaA3nw9BVsG5sPiTNfxUDEwLqKI+/wKo5H8A==}
|
||||
engines: {node: '>=16.0.0'}
|
||||
peerDependencies:
|
||||
'@cadl-lang/compiler': ~0.37.0
|
||||
'@cadl-lang/rest': ~0.19.0
|
||||
dependencies:
|
||||
'@cadl-lang/compiler': 0.37.0
|
||||
'@cadl-lang/lint': 0.3.0_@cadl-lang+compiler@0.37.0
|
||||
'@cadl-lang/rest': 0.19.0_@cadl-lang+compiler@0.37.0
|
||||
dev: false
|
||||
|
||||
/@azure-tools/cadl-dpg/0.3.0_d21a2f9719b9a9b97180252366891ee1:
|
||||
resolution: {integrity: sha512-iASCQ1v01+kWGmFMN4TNTVos1SkYeM5ajoYeiZuU35yFkOXaUo3cBEAK2qabRzZHqsQ/yz6p7u9OrgUoyUdHPw==}
|
||||
engines: {node: '>=16.0.0'}
|
||||
peerDependencies:
|
||||
'@cadl-lang/compiler': ~0.37.0
|
||||
'@cadl-lang/rest': ~0.19.0
|
||||
dependencies:
|
||||
'@cadl-lang/compiler': 0.37.0
|
||||
'@cadl-lang/rest': 0.19.0_@cadl-lang+compiler@0.37.0
|
||||
dev: false
|
||||
|
||||
/@azure-tools/cadl-python/0.4.10_e47e309b36bca5141b312b3070791b1c:
|
||||
resolution: {integrity: sha512-Y4NidNtvpQmz88d02UWEYyy/iYkqtqC8DvU8pqICXSjeYhZGShQ286drmJU6ZmKi/ju3uMSpK5tTHOL5IbsQ8w==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
peerDependencies:
|
||||
'@azure-tools/cadl-azure-core': ~0.9.0
|
||||
'@cadl-lang/rest': ~0.19.0
|
||||
'@cadl-lang/versioning': ~0.10.0
|
||||
dependencies:
|
||||
'@autorest/python': 6.2.9
|
||||
'@azure-tools/cadl-azure-core': 0.9.0_d21a2f9719b9a9b97180252366891ee1
|
||||
'@azure-tools/cadl-dpg': 0.3.0_d21a2f9719b9a9b97180252366891ee1
|
||||
'@cadl-lang/compiler': 0.37.0
|
||||
'@cadl-lang/rest': 0.19.0_@cadl-lang+compiler@0.37.0
|
||||
'@cadl-lang/versioning': 0.10.0
|
||||
js-yaml: 4.1.0
|
||||
dev: false
|
||||
|
||||
/@azure-tools/object-comparison/3.0.253:
|
||||
resolution: {integrity: sha512-lpsO1TJmHvcXO8aDWyLeGx9H37AjGXyH0tMa56JbqV2xZRDzzJ5IuAcTjweP9g5WTShLGBvzp/nbODeQkakTjQ==}
|
||||
engines: {node: '>=10.12.0'}
|
||||
|
@ -609,6 +706,85 @@ packages:
|
|||
yargs: 17.3.1
|
||||
dev: false
|
||||
|
||||
/@cadl-lang/compiler/0.37.0:
|
||||
resolution: {integrity: sha512-jHMqPZmM4evQlu7oY9vj6PEM+f+OhnfPqAdwxALrU2gwsLcwYG1h8rkjX/iK2KfeewCbXuRT/hztOTo3pcbYWA==}
|
||||
engines: {node: '>=16.0.0'}
|
||||
hasBin: true
|
||||
dependencies:
|
||||
'@babel/code-frame': 7.16.7
|
||||
ajv: 8.9.0
|
||||
change-case: 4.1.2
|
||||
globby: 13.1.2
|
||||
js-yaml: 4.1.0
|
||||
mkdirp: 1.0.4
|
||||
mustache: 4.2.0
|
||||
node-fetch: 3.2.8
|
||||
node-watch: 0.7.3
|
||||
picocolors: 1.0.0
|
||||
prettier: 2.7.1
|
||||
prompts: 2.4.2
|
||||
vscode-languageserver: 7.0.0
|
||||
vscode-languageserver-textdocument: 1.0.7
|
||||
yargs: 17.3.1
|
||||
dev: false
|
||||
|
||||
/@cadl-lang/lint/0.3.0_@cadl-lang+compiler@0.37.0:
|
||||
resolution: {integrity: sha512-CWqkD+O/sltXzuFcc2ucPf4b1E3ozIqukkFlhwDUXs5DvQIGDTEeekPVBn2kJAFj15kKHGDssp7tAQGzucmPdQ==}
|
||||
engines: {node: '>=16.0.0'}
|
||||
peerDependencies:
|
||||
'@cadl-lang/compiler': ~0.37.0
|
||||
dependencies:
|
||||
'@cadl-lang/compiler': 0.37.0
|
||||
dev: false
|
||||
|
||||
/@cadl-lang/openapi/0.11.0_d21a2f9719b9a9b97180252366891ee1:
|
||||
resolution: {integrity: sha512-miVNnGNq1VOdirTEStKIi00AMxPi/C53bGizrdqBUS7ZJ1vDQR7pq9hbPNYX8K7qAjMMSrJQykZc0xTOB/Jlow==}
|
||||
engines: {node: '>=16.0.0'}
|
||||
peerDependencies:
|
||||
'@cadl-lang/compiler': ~0.34.0
|
||||
'@cadl-lang/rest': ~0.16.0
|
||||
dependencies:
|
||||
'@cadl-lang/compiler': 0.37.0
|
||||
'@cadl-lang/rest': 0.19.0_@cadl-lang+compiler@0.37.0
|
||||
dev: false
|
||||
|
||||
/@cadl-lang/openapi3/0.14.0_54d7e0469b3f026a67a13d2bc5d9b3d4:
|
||||
resolution: {integrity: sha512-NLNeVIBFmpy3KNy1T8coftynVLOUOk4HBWYtqsaciEkrbAGRbJrNfzbC42mRGqr/yBD6Iyo03B5V3H1pKcAyEA==}
|
||||
engines: {node: '>=16.0.0'}
|
||||
peerDependencies:
|
||||
'@cadl-lang/compiler': ~0.34.0
|
||||
'@cadl-lang/openapi': ~0.11.0
|
||||
'@cadl-lang/rest': ~0.16.0
|
||||
'@cadl-lang/versioning': ~0.7.0
|
||||
dependencies:
|
||||
'@cadl-lang/compiler': 0.37.0
|
||||
'@cadl-lang/openapi': 0.11.0_d21a2f9719b9a9b97180252366891ee1
|
||||
'@cadl-lang/rest': 0.19.0_@cadl-lang+compiler@0.37.0
|
||||
'@cadl-lang/versioning': 0.10.0
|
||||
dev: false
|
||||
|
||||
/@cadl-lang/prettier-plugin-cadl/0.5.17:
|
||||
resolution: {integrity: sha512-s1poDYYGJBfnz76lU82wKS6HdlBxz9Cd3/54QOudOiKn9elFsXA4LwWI2BiCPOqlJhcGTgZayrvth6cGh1mqLQ==}
|
||||
dependencies:
|
||||
prettier: 2.7.1
|
||||
dev: false
|
||||
|
||||
/@cadl-lang/rest/0.19.0_@cadl-lang+compiler@0.37.0:
|
||||
resolution: {integrity: sha512-3vMDvr8huQcH03oGYlt5uhRu5TKn6rb+rK0tmPfWgZ9EfZDMn0lR4CAjQOukFv2d93s7KE2IBVtXvQ/Z0C7kdQ==}
|
||||
engines: {node: '>=16.0.0'}
|
||||
peerDependencies:
|
||||
'@cadl-lang/compiler': ~0.37.0
|
||||
dependencies:
|
||||
'@cadl-lang/compiler': 0.37.0
|
||||
dev: false
|
||||
|
||||
/@cadl-lang/versioning/0.10.0:
|
||||
resolution: {integrity: sha512-+9gdn2N1a3VyOu1ou12U9Uq5Mfvp/1A4nfEPOoZzDDm3U2GZZuRR4ZMUU1MqlJy0jrQdpW1yBNQD3ZYy0ngS7Q==}
|
||||
engines: {node: '>=16.0.0'}
|
||||
dependencies:
|
||||
'@cadl-lang/compiler': 0.37.0
|
||||
dev: false
|
||||
|
||||
/@cnakazawa/watch/1.0.4:
|
||||
resolution: {integrity: sha512-v9kIhKwjeZThiWrLmj0y17CWoyddASLj9O2yvbZkbvw/N3rWOYy9zkV66ursAoVr0mV15bL8g0c4QZUE6cdDoQ==}
|
||||
engines: {node: '>=0.1.95'}
|
||||
|
@ -1104,6 +1280,12 @@ packages:
|
|||
resolution: {integrity: sha512-c5ciR06jK8u9BstrmJyO97m+klJrrhCf9u3rLu3DEAJBirxRqSCvDQoYKmxuYwQI5SZChAWu+tq9oVlGRuzPAg==}
|
||||
dev: false
|
||||
|
||||
/@types/fs-extra/9.0.13:
|
||||
resolution: {integrity: sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA==}
|
||||
dependencies:
|
||||
'@types/node': 14.14.45
|
||||
dev: false
|
||||
|
||||
/@types/glob/7.2.0:
|
||||
resolution: {integrity: sha512-ZUxbzKl0IfJILTS6t7ip5fQQM/J3TJYubDm3nMbgubNNYS62eXeUpoLUC8/7fJNiFYHTrGPQn7hspDUzIHX3UA==}
|
||||
dependencies:
|
||||
|
@ -3342,6 +3524,15 @@ packages:
|
|||
resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
|
||||
dev: false
|
||||
|
||||
/fs-extra/10.1.0:
|
||||
resolution: {integrity: sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==}
|
||||
engines: {node: '>=12'}
|
||||
dependencies:
|
||||
graceful-fs: 4.2.10
|
||||
jsonfile: 6.1.0
|
||||
universalify: 2.0.0
|
||||
dev: false
|
||||
|
||||
/fs-extra/8.1.0:
|
||||
resolution: {integrity: sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==}
|
||||
engines: {node: '>=6 <7 || >=8'}
|
||||
|
@ -4775,6 +4966,14 @@ packages:
|
|||
graceful-fs: 4.2.10
|
||||
dev: false
|
||||
|
||||
/jsonfile/6.1.0:
|
||||
resolution: {integrity: sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==}
|
||||
dependencies:
|
||||
universalify: 2.0.0
|
||||
optionalDependencies:
|
||||
graceful-fs: 4.2.10
|
||||
dev: false
|
||||
|
||||
/jsonparse/1.3.1:
|
||||
resolution: {integrity: sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==}
|
||||
engines: {'0': node >= 0.2.0}
|
||||
|
@ -5076,7 +5275,7 @@ packages:
|
|||
/minipass/2.9.0:
|
||||
resolution: {integrity: sha512-wxfUjg9WebH+CUDX/CdbRlh5SmfZiy/hpkxaRI16Y9W56Pa75sWgd/rvFilSgrauD9NyFymP/+JFV3KwzIsJeg==}
|
||||
dependencies:
|
||||
safe-buffer: 5.2.1
|
||||
safe-buffer: 5.2.0
|
||||
yallist: 3.1.1
|
||||
dev: false
|
||||
|
||||
|
@ -5237,6 +5436,15 @@ packages:
|
|||
formdata-polyfill: 4.0.10
|
||||
dev: false
|
||||
|
||||
/node-fetch/3.2.8:
|
||||
resolution: {integrity: sha512-KtpD1YhGszhntMpBDyp5lyagk8KIMopC1LEb7cQUAh7zcosaX5uK8HnbNb2i3NTQK3sIawCItS0uFC3QzcLHdg==}
|
||||
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
|
||||
dependencies:
|
||||
data-uri-to-buffer: 4.0.0
|
||||
fetch-blob: 3.2.0
|
||||
formdata-polyfill: 4.0.10
|
||||
dev: false
|
||||
|
||||
/node-int64/0.4.0:
|
||||
resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}
|
||||
dev: false
|
||||
|
@ -5335,7 +5543,7 @@ packages:
|
|||
lru-cache: 5.1.1
|
||||
make-fetch-happen: 5.0.2
|
||||
npm-package-arg: 6.1.1
|
||||
safe-buffer: 5.2.1
|
||||
safe-buffer: 5.2.0
|
||||
dev: false
|
||||
|
||||
/npm-run-path/2.0.2:
|
||||
|
@ -6896,6 +7104,37 @@ packages:
|
|||
code-block-writer: 11.0.3
|
||||
dev: false
|
||||
|
||||
/ts-node/10.9.1_7d52a1ab8d3f8907f176d15392128f81:
|
||||
resolution: {integrity: sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
'@swc/core': '>=1.2.50'
|
||||
'@swc/wasm': '>=1.2.50'
|
||||
'@types/node': '*'
|
||||
typescript: '>=2.7'
|
||||
peerDependenciesMeta:
|
||||
'@swc/core':
|
||||
optional: true
|
||||
'@swc/wasm':
|
||||
optional: true
|
||||
dependencies:
|
||||
'@cspotcode/source-map-support': 0.8.1
|
||||
'@tsconfig/node10': 1.0.9
|
||||
'@tsconfig/node12': 1.0.11
|
||||
'@tsconfig/node14': 1.0.3
|
||||
'@tsconfig/node16': 1.0.3
|
||||
'@types/node': 14.14.45
|
||||
acorn: 8.8.1
|
||||
acorn-walk: 8.2.0
|
||||
arg: 4.1.3
|
||||
create-require: 1.1.1
|
||||
diff: 4.0.2
|
||||
make-error: 1.3.6
|
||||
typescript: 4.9.3
|
||||
v8-compile-cache-lib: 3.0.1
|
||||
yn: 3.1.1
|
||||
dev: false
|
||||
|
||||
/ts-node/10.9.1_fed3b4cb8104197fd8996158792567a5:
|
||||
resolution: {integrity: sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==}
|
||||
hasBin: true
|
||||
|
@ -7082,6 +7321,11 @@ packages:
|
|||
engines: {node: '>= 4.0.0'}
|
||||
dev: false
|
||||
|
||||
/universalify/2.0.0:
|
||||
resolution: {integrity: sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==}
|
||||
engines: {node: '>= 10.0.0'}
|
||||
dev: false
|
||||
|
||||
/unset-value/1.0.0:
|
||||
resolution: {integrity: sha512-PcA2tsuGSF9cnySLHTLSh2qrQiJ70mn+r+Glzxv2TWZblxsxCC52BDlZoPCsz7STd9pN7EZetkWZBAvk4cgZdQ==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
@ -7383,7 +7627,7 @@ packages:
|
|||
/wide-align/1.1.5:
|
||||
resolution: {integrity: sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==}
|
||||
dependencies:
|
||||
string-width: 4.2.3
|
||||
string-width: 1.0.2
|
||||
dev: false
|
||||
|
||||
/wildcard/2.0.0:
|
||||
|
@ -8188,6 +8432,56 @@ packages:
|
|||
- ts-node
|
||||
dev: false
|
||||
|
||||
file:projects/openapi-to-cadl.tgz_jest@29.3.1:
|
||||
resolution: {integrity: sha512-c71ROqaMniMzoKbd8ISUj8c8iJ+XphRy2vmBgNZ85XNz+Z8rKouRrZVThdA64eq2ftPy+Zzz0y40wWGzCAmEWA==, tarball: file:projects/openapi-to-cadl.tgz}
|
||||
id: file:projects/openapi-to-cadl.tgz
|
||||
name: '@rush-temp/openapi-to-cadl'
|
||||
version: 0.0.0
|
||||
dependencies:
|
||||
'@azure-tools/cadl-autorest': 0.20.0_7bb8c157cd14650f0893a032b45ea3ab
|
||||
'@azure-tools/cadl-azure-core': 0.9.0_d21a2f9719b9a9b97180252366891ee1
|
||||
'@azure-tools/cadl-python': 0.4.10_e47e309b36bca5141b312b3070791b1c
|
||||
'@cadl-lang/compiler': 0.37.0
|
||||
'@cadl-lang/openapi': 0.11.0_d21a2f9719b9a9b97180252366891ee1
|
||||
'@cadl-lang/openapi3': 0.14.0_54d7e0469b3f026a67a13d2bc5d9b3d4
|
||||
'@cadl-lang/prettier-plugin-cadl': 0.5.17
|
||||
'@cadl-lang/rest': 0.19.0_@cadl-lang+compiler@0.37.0
|
||||
'@cadl-lang/versioning': 0.10.0
|
||||
'@types/fs-extra': 9.0.13
|
||||
'@types/node': 14.14.45
|
||||
'@types/prettier': 2.7.1
|
||||
'@types/webpack': 4.41.33
|
||||
'@typescript-eslint/eslint-plugin': 5.43.0_6c13c08efc22ad2f80829ce4a7a0fc7e
|
||||
'@typescript-eslint/parser': 5.43.0_eslint@8.28.0+typescript@4.9.3
|
||||
chalk: 4.1.2
|
||||
eslint: 8.28.0
|
||||
eslint-plugin-import: 2.26.0_eslint@8.28.0
|
||||
eslint-plugin-jest: 27.1.5_6ad5c3175fb58fda0c046c2cca2eca61
|
||||
eslint-plugin-node: 11.1.0_eslint@8.28.0
|
||||
eslint-plugin-prettier: 4.2.1_eslint@8.28.0+prettier@2.7.1
|
||||
eslint-plugin-unicorn: 44.0.2_eslint@8.28.0
|
||||
fs-extra: 10.1.0
|
||||
prettier: 2.7.1
|
||||
rimraf: 3.0.2
|
||||
ts-loader: 9.2.9_typescript@4.9.3+webpack@5.40.0
|
||||
ts-node: 10.9.1_7d52a1ab8d3f8907f176d15392128f81
|
||||
typescript: 4.9.3
|
||||
webpack: 5.40.0_webpack-cli@4.7.2
|
||||
webpack-cli: 4.7.2_webpack@5.40.0
|
||||
transitivePeerDependencies:
|
||||
- '@swc/core'
|
||||
- '@swc/wasm'
|
||||
- '@webpack-cli/generators'
|
||||
- '@webpack-cli/migrate'
|
||||
- esbuild
|
||||
- eslint-config-prettier
|
||||
- jest
|
||||
- supports-color
|
||||
- uglify-js
|
||||
- webpack-bundle-analyzer
|
||||
- webpack-dev-server
|
||||
dev: false
|
||||
|
||||
file:projects/openapi.tgz_prettier@2.7.1+ts-node@9.1.1:
|
||||
resolution: {integrity: sha512-1gIAqFdMdAvRBIiSVAM6fBrtubwici8zW6/WPWJDhSpCEK6fziN5vdcwp5c7v2CK4Aecc3jgl+dNpLip5CgDCQ==, tarball: file:projects/openapi.tgz}
|
||||
id: file:projects/openapi.tgz
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
dist/
|
|
@ -0,0 +1,6 @@
|
|||
parser: "@typescript-eslint/parser"
|
||||
extends:
|
||||
- "../../../.default-eslintrc.yaml"
|
||||
rules:
|
||||
# Due to the need for logging. TODO: change to winston logger.
|
||||
no-console: off
|
|
@ -0,0 +1,21 @@
|
|||
!dist/**/*
|
||||
src/
|
||||
dist/test/
|
||||
test/
|
||||
package/
|
||||
.npmignore
|
||||
*.tsbuildinfo
|
||||
tsconfig.json
|
||||
*.ts
|
||||
.eslint*
|
||||
!*.d.ts
|
||||
*.tgz
|
||||
.vscode
|
||||
.scripts
|
||||
attic/
|
||||
generated/
|
||||
notes.md
|
||||
Examples/
|
||||
samples/
|
||||
*.log
|
||||
package-deps.json
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE
|
|
@ -0,0 +1,47 @@
|
|||
## Autorest openapi-to-cadl Plugin Configuration
|
||||
|
||||
Autorest extension to scaffold a new CADL definition from an existing OpenApi document.
|
||||
|
||||
To run it
|
||||
|
||||
```bash
|
||||
autorest --openapi-to-cadl --input-file=<path-to-swagger> -namespace=<namespace> --title="<ProjectName>" --clear-output-folder=false
|
||||
```
|
||||
|
||||
or with a README config file
|
||||
|
||||
```bash
|
||||
autorest --openapi-to-cadl --require=<path-to-readme-config>.md
|
||||
```
|
||||
|
||||
This plugin will generate the following files
|
||||
|
||||
main.cadl - Entry point of the CADL project, it contains service information
|
||||
models.cadl - Contains all the model definitions
|
||||
routes.cadl - Contains all the resource endpoints
|
||||
cadl-project.yaml - Contains configuration for the CADL compiler
|
||||
package.json - Configuration of the CADL project
|
||||
|
||||
```yaml
|
||||
version: 3.6.6
|
||||
use-extension:
|
||||
"@autorest/modelerfour": "^4.23.5"
|
||||
|
||||
modelerfour:
|
||||
# this runs a pre-namer step to clean up names
|
||||
prenamer: true
|
||||
|
||||
openapi-to-cadl-scope/emitter:
|
||||
input-artifact: openapi-to-cadl-files
|
||||
|
||||
output-artifact: openapi-to-cadl-files
|
||||
|
||||
pipeline:
|
||||
openapi-to-cadl: # <- name of plugin
|
||||
input: modelerfour/identity
|
||||
output-artifact: openapi-to-cadl-files
|
||||
|
||||
openapi-to-cadl/emitter:
|
||||
input: openapi-to-cadl
|
||||
scope: openapi-to-cadl-scope/emitter
|
||||
```
|
|
@ -0,0 +1,77 @@
|
|||
{
|
||||
"name": "@autorest/openapi-to-cadl",
|
||||
"version": "0.1.0",
|
||||
"description": "Autorest plugin to scaffold a CADL definition from an OpenAPI document",
|
||||
"main": "dist/main.js",
|
||||
"typings": "dist/main.d.ts",
|
||||
"scripts": {
|
||||
"generate": "ts-node ./test/utils/generate-cadl.ts generate",
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"test:ci": "npm run generate && node ./test/utils/check-clean-tree.js",
|
||||
"clean": "rimraf ./dist ./temp",
|
||||
"start": "node --max_old_space_size=4096 ./dist/main.js",
|
||||
"debug": "node --max_old_space_size=4096 --inspect-brk=localhost:9229 ./dist/main.js",
|
||||
"watch": "tsc -p tsconfig.build.json --watch",
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"build:prod": "webpack",
|
||||
"lint:fix": "eslint ./src ./test --fix --ext .ts",
|
||||
"lint": "eslint ./src ./test --ext .ts --max-warnings=0"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Azure/autorest.git"
|
||||
},
|
||||
"keywords": [
|
||||
"Autorest",
|
||||
"cadl"
|
||||
],
|
||||
"author": "Microsoft Corporation",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Azure/autorest/issues"
|
||||
},
|
||||
"files": [
|
||||
"src",
|
||||
"dist/**",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"homepage": "https://github.com/Azure/autorest#readme",
|
||||
"dependencies": {
|
||||
"@autorest/extension-base": "~3.5.0",
|
||||
"@autorest/codemodel": "~4.19.2",
|
||||
"@cadl-lang/compiler": "^0.37.0",
|
||||
"@cadl-lang/rest": "^0.19.0",
|
||||
"@cadl-lang/versioning": "^0.10.0",
|
||||
"@cadl-lang/prettier-plugin-cadl": "^0.5.17",
|
||||
"@azure-tools/cadl-azure-core": "^0.9.0",
|
||||
"@azure-tools/cadl-autorest": "^0.22.0",
|
||||
"@azure-tools/cadl-python": "^0.4.10",
|
||||
"@cadl-lang/openapi": "^0.11.0",
|
||||
"@cadl-lang/openapi3": "^0.14.0",
|
||||
"prettier": "~2.7.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "~4.9.3",
|
||||
"@types/prettier": "^2.7.0",
|
||||
"@types/webpack": "~4.41.26",
|
||||
"rimraf": "^3.0.2",
|
||||
"ts-node": "^10.9.1",
|
||||
"@types/node": "~14.14.20",
|
||||
"fs-extra": "^10.1.0",
|
||||
"@types/fs-extra": "^9.0.13",
|
||||
"chalk": "^4.1.0",
|
||||
"@azure-tools/cadl-autorest": "^0.20.0",
|
||||
"webpack-cli": "~4.7.2",
|
||||
"webpack": "~5.40.0",
|
||||
"@typescript-eslint/eslint-plugin": "^5.27.0",
|
||||
"@typescript-eslint/parser": "^5.27.0",
|
||||
"eslint-plugin-jest": "~27.1.5",
|
||||
"eslint-plugin-node": "~11.1.0",
|
||||
"eslint-plugin-prettier": "~4.2.1",
|
||||
"eslint-plugin-unicorn": "~44.0.2",
|
||||
"eslint-plugin-import": "~2.26.0",
|
||||
"eslint": "^8.28.0",
|
||||
"ts-loader": "~9.2.3"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
import { CodeModel } from "@autorest/codemodel";
|
||||
import { Session } from "@autorest/extension-base";
|
||||
|
||||
let _session: Session<CodeModel>;
|
||||
|
||||
export function setSession(session: Session<CodeModel>): void {
|
||||
_session = session;
|
||||
}
|
||||
|
||||
export function getSession(): Session<CodeModel> {
|
||||
return _session;
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
import { CodeModel, Schema } from "@autorest/codemodel";
|
||||
import { CadlDataType } from "./interfaces";
|
||||
|
||||
const dataTypes = new WeakMap<CodeModel, WeakMap<Schema, CadlDataType>>();
|
||||
|
||||
export function getDataTypes(codeModel: CodeModel) {
|
||||
let dataTypeMap = dataTypes.get(codeModel);
|
||||
if (!dataTypeMap) {
|
||||
dataTypeMap = new WeakMap();
|
||||
dataTypes.set(codeModel, dataTypeMap);
|
||||
}
|
||||
return dataTypeMap;
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
import { writeFileSync } from "fs";
|
||||
import { formatFile } from "../utils/format";
|
||||
|
||||
export async function emitCadlConfig(filePath: string): Promise<void> {
|
||||
const content = `
|
||||
emitters:
|
||||
# "@azure-tools/cadl-autorest": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-python" to your package.json to generate Python code
|
||||
# "@azure-tools/cadl-python":
|
||||
# "basic-setup-py": true
|
||||
# "package-version":
|
||||
# "package-name":
|
||||
# "output-path":
|
||||
# Uncomment this line and add "@azure-tools/cadl-java" to your package.json to generate Java code
|
||||
# "@azure-tools/cadl-java": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-csharp" to your package.json to generate C# code
|
||||
# "@azure-tools/cadl-csharp": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-typescript" to your package.json to generate Typescript code
|
||||
# "@azure-tools/cadl-typescript": true
|
||||
`;
|
||||
|
||||
writeFileSync(filePath, formatFile(content, filePath));
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
import { writeFile } from "fs/promises";
|
||||
import { generateServiceInformation } from "../generate/generate-service-information";
|
||||
import { CadlProgram } from "../interfaces";
|
||||
import { formatCadlFile } from "../utils/format";
|
||||
|
||||
export async function emitMain(filePath: string, program: CadlProgram): Promise<void> {
|
||||
const content = getServiceInformation(program);
|
||||
await writeFile(filePath, formatCadlFile(content, filePath));
|
||||
}
|
||||
|
||||
function getServiceInformation(program: CadlProgram) {
|
||||
const imports = [`import "@cadl-lang/rest";`, `import "./routes.cadl";`, ``, `using Cadl.Rest;`, `using Cadl.Http;`];
|
||||
const content = generateServiceInformation(program);
|
||||
|
||||
return [...imports, content].join("\n");
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
import { writeFile } from "fs/promises";
|
||||
import { generateEnums } from "../generate/generate-enums";
|
||||
import { generateObject } from "../generate/generate-object";
|
||||
import { CadlEnum, CadlProgram } from "../interfaces";
|
||||
import { formatCadlFile } from "../utils/format";
|
||||
import { getModelsImports } from "../utils/imports";
|
||||
import { getNamespace } from "../utils/namespace";
|
||||
|
||||
export async function emitModels(filePath: string, program: CadlProgram): Promise<void> {
|
||||
const content = generateModels(program);
|
||||
|
||||
await writeFile(filePath, formatCadlFile(content, filePath));
|
||||
}
|
||||
|
||||
function generateModels(program: CadlProgram) {
|
||||
const { models } = program;
|
||||
const { modules, namespaces: namespacesSet } = getModelsImports(program);
|
||||
const imports = [...new Set<string>([`import "@cadl-lang/rest";`, ...modules])].join("\n");
|
||||
|
||||
const namespaces = [...new Set<string>([`using Cadl.Rest;`, ...namespacesSet])].join("\n");
|
||||
|
||||
const enums = flattenEnums(models.enums).join("");
|
||||
const objects = models.objects.map(generateObject).join("\n\n");
|
||||
return [imports, "\n", namespaces, "\n", getNamespace(program), "\n", enums, "\n", objects].join("\n");
|
||||
}
|
||||
|
||||
function flattenEnums(enums: CadlEnum[]) {
|
||||
return enums.reduce<string[]>((a, c) => {
|
||||
return [...a, ...generateEnums(c)];
|
||||
}, []);
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
import { writeFile } from "fs/promises";
|
||||
import { CadlProgram } from "../interfaces";
|
||||
import { formatFile } from "../utils/format";
|
||||
|
||||
export async function emitPackage(filePath: string, program: CadlProgram): Promise<void> {
|
||||
const name = program.serviceInformation.name.toLowerCase().replace(/ /g, "-");
|
||||
const description = program.serviceInformation.doc;
|
||||
const content = JSON.stringify(getPackage(name, description as string));
|
||||
await writeFile(filePath, formatFile(content, filePath));
|
||||
}
|
||||
|
||||
const getPackage = (name: string, description: string) => ({
|
||||
name: `@cadl-api-spec/${name}`,
|
||||
author: "Microsoft Corporation",
|
||||
description,
|
||||
license: "MIT",
|
||||
dependencies: {
|
||||
"@cadl-lang/compiler": "^0.37.0",
|
||||
"@cadl-lang/rest": "^0.19.0",
|
||||
"@cadl-lang/versioning": "^0.10.0",
|
||||
"@cadl-lang/prettier-plugin-cadl": "^0.5.17",
|
||||
"@azure-tools/cadl-azure-core": "^0.9.0",
|
||||
"@azure-tools/cadl-autorest": "^0.22.0",
|
||||
"@azure-tools/cadl-python": "^0.4.10",
|
||||
prettier: "^2.7.1",
|
||||
},
|
||||
private: true,
|
||||
});
|
|
@ -0,0 +1,19 @@
|
|||
import { writeFile } from "fs/promises";
|
||||
import { generateOperationGroup } from "../generate/generate-operations";
|
||||
import { CadlProgram } from "../interfaces";
|
||||
import { formatCadlFile } from "../utils/format";
|
||||
import { getRoutesImports } from "../utils/imports";
|
||||
import { getNamespace } from "../utils/namespace";
|
||||
|
||||
export async function emitRoutes(filePath: string, program: CadlProgram): Promise<void> {
|
||||
const content = generateRoutes(program);
|
||||
await writeFile(filePath, formatCadlFile(content, filePath));
|
||||
}
|
||||
|
||||
function generateRoutes(program: CadlProgram) {
|
||||
const { operationGroups } = program;
|
||||
const { modules, namespaces } = getRoutesImports(program);
|
||||
const content = operationGroups.map(generateOperationGroup);
|
||||
|
||||
return [...modules, "\n", ...namespaces, "\n", getNamespace(program), "\n", ...content].join("\n");
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
import { CadlEnum } from "../interfaces";
|
||||
import { generateDocs } from "../utils/docs";
|
||||
|
||||
export function generateEnums(cadlEnum: CadlEnum) {
|
||||
const definitions: string[] = [];
|
||||
const doc = generateDocs(cadlEnum);
|
||||
definitions.push(doc);
|
||||
|
||||
for (const fixme of cadlEnum.fixMe ?? []) {
|
||||
definitions.push(`\n${fixme}`);
|
||||
}
|
||||
|
||||
const enumDefinition = `
|
||||
enum ${cadlEnum.name}${cadlEnum.isExtensible ? "KnownValues" : ""} {
|
||||
${cadlEnum.members
|
||||
.map((m) => {
|
||||
return `"${m.name}"` !== m.value ? `${m.name}: ${m.value}` : m.value;
|
||||
})
|
||||
.join(", ")}
|
||||
}\n`;
|
||||
|
||||
definitions.push(enumDefinition);
|
||||
|
||||
if (cadlEnum.isExtensible) {
|
||||
const knownValues = `
|
||||
@knownValues(${cadlEnum.name}KnownValues)
|
||||
model ${cadlEnum.name} is string {}\n\n`;
|
||||
|
||||
definitions.push(knownValues);
|
||||
}
|
||||
|
||||
return definitions;
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
import { CadlObject, CadlObjectProperty } from "../interfaces";
|
||||
import { generateDecorators } from "../utils/decorators";
|
||||
import { generateDocs } from "../utils/docs";
|
||||
|
||||
export function generateObject(cadlObject: CadlObject) {
|
||||
const definitions: string[] = [];
|
||||
|
||||
const fixme = getFixme(cadlObject);
|
||||
fixme && definitions.push(fixme);
|
||||
|
||||
const doc = generateDocs(cadlObject);
|
||||
definitions.push(doc);
|
||||
|
||||
const decorators = generateDecorators(cadlObject.decorators);
|
||||
decorators && definitions.push(decorators);
|
||||
|
||||
if (cadlObject.extendedParents?.length) {
|
||||
const firstParent = cadlObject.extendedParents[0];
|
||||
definitions.push(`model ${cadlObject.name} extends ${firstParent} {`);
|
||||
} else if (cadlObject.alias) {
|
||||
const { alias, params } = cadlObject.alias;
|
||||
|
||||
definitions.push(`model ${cadlObject.name} is ${alias}${params ? `<${params.join(",")}>` : ""} {`);
|
||||
} else {
|
||||
definitions.push(`model ${cadlObject.name} {`);
|
||||
}
|
||||
|
||||
for (const parent of cadlObject.spreadParents ?? []) {
|
||||
definitions.push(`...${parent};`);
|
||||
}
|
||||
|
||||
for (const property of cadlObject.properties) {
|
||||
const propertyDoc = generateDocs(property);
|
||||
propertyDoc && definitions.push(propertyDoc);
|
||||
const decorators = generateDecorators(property.decorators);
|
||||
decorators && definitions.push(decorators);
|
||||
|
||||
definitions.push(`"${property.name}"${getOptionalOperator(property)}: ${property.type};`);
|
||||
}
|
||||
definitions.push("}");
|
||||
|
||||
return definitions.join("\n");
|
||||
}
|
||||
|
||||
function getFixme(cadlObject: CadlObject): string | undefined {
|
||||
if (!cadlObject.fixMe) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return cadlObject.fixMe.join("\n");
|
||||
}
|
||||
|
||||
function getOptionalOperator(property: CadlObjectProperty) {
|
||||
return property.isOptional ? "?" : "";
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
import { CadlOperation, CadlOperationGroup, CadlParameter } from "../interfaces";
|
||||
import { generateDocs, generateSummary } from "../utils/docs";
|
||||
|
||||
export function generateOperation(operation: CadlOperation, operationGroup: CadlOperationGroup) {
|
||||
const doc = generateDocs(operation);
|
||||
const summary = generateSummary(operation);
|
||||
const { verb, name, route, responses, parameters } = operation;
|
||||
const params = generateParameters(parameters);
|
||||
const statements: string[] = [];
|
||||
summary && statements.push(summary);
|
||||
statements.push(doc);
|
||||
generateMultiResponseWarning(responses, statements);
|
||||
for (const fixme of operation.fixMe ?? []) {
|
||||
statements.push(fixme);
|
||||
}
|
||||
|
||||
if (!operation.resource) {
|
||||
statements.push(`@route("${route}")`);
|
||||
statements.push(
|
||||
`@${verb} op ${name} is Azure.Core.Foundations.Operation<{${params ? params : ""}}, ${responses.join(
|
||||
" | ",
|
||||
)}>;\n\n\n`,
|
||||
);
|
||||
} else {
|
||||
const { resource } = operation;
|
||||
const resourceParameters = generateParameters(
|
||||
parameters.filter((param) => !["path", "body"].some((p) => p === param.location)),
|
||||
);
|
||||
|
||||
const parametersString = !resourceParameters ? `` : `, { parameters: {${resourceParameters}}}`;
|
||||
statements.push(
|
||||
`${operationGroup.name ? "" : "op "}`,
|
||||
`${name} is Azure.Core.${resource.kind}<${resource.response.name} ${parametersString}>;\n\n\n`,
|
||||
);
|
||||
}
|
||||
return statements.join("\n");
|
||||
}
|
||||
|
||||
function generateMultiResponseWarning(responses: string[], statements: string[]) {
|
||||
responses.length > 2 &&
|
||||
statements.push(
|
||||
`// FIXME: (multi-response) Swagger defines multiple requests and responses.
|
||||
// This needs to be revisited as CADL supports linking specific responses to each request`,
|
||||
);
|
||||
}
|
||||
|
||||
function generateParameters(parameters: CadlParameter[]) {
|
||||
const params: string[] = [];
|
||||
for (const parameter of parameters) {
|
||||
const location = parameter.location;
|
||||
params.push(generateDocs(parameter));
|
||||
params.push(`@${location} "${parameter.name}": ${parameter.type},`);
|
||||
}
|
||||
return params.join("\n");
|
||||
}
|
||||
|
||||
export function generateOperationGroup(operationGroup: CadlOperationGroup) {
|
||||
const statements: string[] = [];
|
||||
const doc = generateDocs(operationGroup);
|
||||
const { name, operations } = operationGroup;
|
||||
|
||||
statements.push(`${doc}`);
|
||||
const hasInterface = Boolean(name);
|
||||
hasInterface && statements.push(`interface ${name} {`);
|
||||
for (const operation of operations) {
|
||||
statements.push(generateOperation(operation, operationGroup));
|
||||
}
|
||||
hasInterface && statements.push(`}`);
|
||||
|
||||
return statements.join("\n");
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
import { CadlProgram } from "../interfaces";
|
||||
import { generateDocs } from "../utils/docs";
|
||||
import { getNamespace } from "../utils/namespace";
|
||||
|
||||
export function generateServiceInformation(program: CadlProgram) {
|
||||
const { serviceInformation } = program;
|
||||
const definitions: string[] = [];
|
||||
|
||||
definitions.push(`@service({title: "${serviceInformation.name}"})`);
|
||||
|
||||
serviceInformation.version && definitions.push(`@serviceVersion("${serviceInformation.version}")`);
|
||||
|
||||
if (serviceInformation.endpoint) {
|
||||
definitions.push(`@server("${serviceInformation.endpoint}", ${JSON.stringify(serviceInformation.doc) ?? ""}`);
|
||||
const hasParameters = serviceInformation.endpointParameters && serviceInformation.endpointParameters.length;
|
||||
|
||||
if (hasParameters) {
|
||||
definitions.push(", {");
|
||||
for (const param of serviceInformation.endpointParameters ?? []) {
|
||||
const doc = generateDocs(param);
|
||||
doc && definitions.push(doc);
|
||||
definitions.push(`${param.name}: string `);
|
||||
}
|
||||
}
|
||||
hasParameters && definitions.push("}");
|
||||
definitions.push(")");
|
||||
}
|
||||
const serviceDoc = generateDocs(serviceInformation);
|
||||
serviceDoc && definitions.push(serviceDoc);
|
||||
definitions.push(getNamespace(program));
|
||||
|
||||
return definitions.join("\n");
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
export * from "./main";
|
|
@ -0,0 +1,136 @@
|
|||
export interface CadlProgram {
|
||||
models: Models;
|
||||
operationGroups: CadlOperationGroup[];
|
||||
serviceInformation: ServiceInformation;
|
||||
}
|
||||
|
||||
export interface CadlOptions {
|
||||
isAzureSpec: boolean;
|
||||
namespace?: string;
|
||||
guessResourceKey: boolean;
|
||||
}
|
||||
|
||||
export interface CadlChoiceValue {
|
||||
name: string;
|
||||
value: string | number | boolean;
|
||||
}
|
||||
|
||||
export interface WithDoc {
|
||||
doc?: string | string[];
|
||||
}
|
||||
|
||||
export interface WithSummary {
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
export interface CadlOperationGroup extends WithDoc {
|
||||
name: string;
|
||||
operations: CadlOperation[];
|
||||
}
|
||||
|
||||
export type Extension = "Pageable" | "LRO";
|
||||
export interface CadlOperation extends WithDoc, WithSummary, WithFixMe {
|
||||
name: string;
|
||||
verb: "get" | "post" | "put" | "delete";
|
||||
route: string;
|
||||
responses: string[];
|
||||
parameters: CadlParameter[];
|
||||
extensions: Extension[];
|
||||
resource?: CadlResource;
|
||||
}
|
||||
|
||||
export type ResourceKind =
|
||||
| "ResourceCreateOrUpdate"
|
||||
| "ResourceCreateOrReplace"
|
||||
| "ResourceCreateWithServiceProvidedName"
|
||||
| "ResourceRead"
|
||||
| "ResourceDelete"
|
||||
| "ResourceList"
|
||||
| "NonPagedResourceList"
|
||||
| "ResourceAction"
|
||||
| "ResourceCollectionAction"
|
||||
| "LongRunningResourceCreateOrReplace"
|
||||
| "LongRunningResourceCreateOrUpdate"
|
||||
| "LongRunningResourceCreateWithServiceProvidedName"
|
||||
| "LongRunningResourceDelete";
|
||||
|
||||
export interface CadlResource {
|
||||
kind: ResourceKind;
|
||||
response: CadlDataType;
|
||||
}
|
||||
|
||||
export interface ServiceInformation extends WithDoc {
|
||||
name: string;
|
||||
version?: string;
|
||||
endpoint?: string;
|
||||
endpointParameters?: EndpointParameter[];
|
||||
produces?: string[];
|
||||
consumes?: string[];
|
||||
}
|
||||
|
||||
export interface EndpointParameter extends WithDoc {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface CadlDataType extends WithDoc, WithFixMe {
|
||||
kind: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface CadlWildcardType extends CadlDataType {
|
||||
kind: "wildcard";
|
||||
}
|
||||
|
||||
export interface CadlEnum extends CadlDataType {
|
||||
kind: "enum";
|
||||
members: CadlChoiceValue[];
|
||||
isExtensible: boolean;
|
||||
}
|
||||
|
||||
export interface WithFixMe {
|
||||
fixMe?: string[];
|
||||
}
|
||||
|
||||
export type CadlParameterLocation = "path" | "query" | "header" | "body";
|
||||
export interface CadlParameter extends CadlDataType {
|
||||
kind: "parameter";
|
||||
isOptional: boolean;
|
||||
type: string;
|
||||
location: CadlParameterLocation;
|
||||
}
|
||||
|
||||
export interface CadlObjectProperty extends CadlDataType {
|
||||
kind: "property";
|
||||
isOptional: boolean;
|
||||
type: string;
|
||||
decorators?: CadlDecorator[];
|
||||
visibility?: "read";
|
||||
}
|
||||
|
||||
export interface CadlDecorator extends WithFixMe {
|
||||
name: string;
|
||||
arguments?: string[];
|
||||
module?: string;
|
||||
namespace?: string;
|
||||
}
|
||||
|
||||
export interface CadlAlias {
|
||||
alias: string;
|
||||
params?: string[];
|
||||
module?: string;
|
||||
}
|
||||
|
||||
export interface CadlObject extends CadlDataType {
|
||||
kind: "object";
|
||||
properties: CadlObjectProperty[];
|
||||
parents: string[];
|
||||
extendedParents?: string[];
|
||||
spreadParents?: string[];
|
||||
decorators?: CadlDecorator[];
|
||||
alias?: CadlAlias;
|
||||
}
|
||||
|
||||
export interface Models {
|
||||
enums: CadlEnum[];
|
||||
objects: CadlObject[];
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
// Copyright (c) Microsoft Corporation.
|
||||
// Licensed under the MIT License.
|
||||
|
||||
import { existsSync, mkdirSync } from "fs";
|
||||
import { join } from "path";
|
||||
import { CodeModel, codeModelSchema } from "@autorest/codemodel";
|
||||
import { AutoRestExtension, AutorestExtensionHost, Session, startSession } from "@autorest/extension-base";
|
||||
import { setSession } from "./autorest-session";
|
||||
import { emitCadlConfig } from "./emiters/emit-cadl-config";
|
||||
import { emitMain } from "./emiters/emit-main";
|
||||
|
||||
import { emitModels } from "./emiters/emit-models";
|
||||
import { emitPackage } from "./emiters/emit-package";
|
||||
import { emitRoutes } from "./emiters/emit-routes";
|
||||
import { getModel } from "./model";
|
||||
import { markErrorModels } from "./utils/errors";
|
||||
import { markPagination } from "./utils/paging";
|
||||
import { markResources } from "./utils/resources";
|
||||
|
||||
export async function processRequest(host: AutorestExtensionHost) {
|
||||
const session = await startSession<CodeModel>(host, codeModelSchema);
|
||||
setSession(session);
|
||||
const codeModel = session.model;
|
||||
markPagination(codeModel);
|
||||
markErrorModels(codeModel);
|
||||
markResources(codeModel);
|
||||
const cadlProgramDetails = getModel(codeModel);
|
||||
createOutputFolder(getFilePath(session, ""));
|
||||
await emitModels(getFilePath(session, "models.cadl"), cadlProgramDetails);
|
||||
await emitRoutes(getFilePath(session, "routes.cadl"), cadlProgramDetails);
|
||||
await emitMain(getFilePath(session, "main.cadl"), cadlProgramDetails);
|
||||
await emitPackage(getFilePath(session, "package.json"), cadlProgramDetails);
|
||||
await emitCadlConfig(getFilePath(session, "cadl-project.yaml"));
|
||||
}
|
||||
|
||||
function createOutputFolder(dir: string) {
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
function getOutuptDirectory(session: Session<CodeModel>) {
|
||||
const outputFolder = session.configuration["output-folder"] ?? ".";
|
||||
const srcPath = session.configuration["src-path"] ?? "";
|
||||
return join(outputFolder, srcPath);
|
||||
}
|
||||
|
||||
function getFilePath(session: Session<CodeModel>, fileName: string) {
|
||||
return join(getOutuptDirectory(session), fileName);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const pluginHost = new AutoRestExtension();
|
||||
pluginHost.add("openapi-to-cadl", processRequest);
|
||||
await pluginHost.run();
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
throw new Error(e);
|
||||
});
|
|
@ -0,0 +1,59 @@
|
|||
import { CodeModel, isObjectSchema, Schema } from "@autorest/codemodel";
|
||||
import { getDataTypes } from "./data-types";
|
||||
import { CadlDataType, CadlProgram } from "./interfaces";
|
||||
import { transformEnum } from "./transforms/transform-choices";
|
||||
import { getCadlType, transformObject } from "./transforms/transform-object";
|
||||
import { transformOperationGroup } from "./transforms/transform-operations";
|
||||
import { transformServiceInformation } from "./transforms/transform-service-information";
|
||||
import { isChoiceSchema } from "./utils/schemas";
|
||||
|
||||
const models: Map<CodeModel, CadlProgram> = new Map();
|
||||
|
||||
export function getModel(codeModel: CodeModel): CadlProgram {
|
||||
let model = models.get(codeModel);
|
||||
|
||||
if (!model) {
|
||||
getDataTypes(codeModel);
|
||||
model = transformModel(codeModel);
|
||||
models.set(codeModel, model);
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
export function transformDataType(schema: Schema, codeModel: CodeModel): CadlDataType {
|
||||
if (isObjectSchema(schema)) {
|
||||
return transformObject(schema, codeModel);
|
||||
}
|
||||
|
||||
if (isChoiceSchema(schema)) {
|
||||
return transformEnum(schema, codeModel);
|
||||
}
|
||||
|
||||
return {
|
||||
name: getCadlType(schema, codeModel),
|
||||
kind: "wildcard",
|
||||
doc: schema.language.default.documentation,
|
||||
};
|
||||
}
|
||||
|
||||
function transformModel(codeModel: CodeModel): CadlProgram {
|
||||
const caldEnums = [...(codeModel.schemas.choices ?? []), ...(codeModel.schemas.sealedChoices ?? [])].map((c) =>
|
||||
transformEnum(c, codeModel),
|
||||
);
|
||||
|
||||
const cadlObjects = codeModel.schemas.objects?.map((o) => transformObject(o, codeModel)) ?? [];
|
||||
|
||||
const serviceInformation = transformServiceInformation(codeModel);
|
||||
|
||||
const cadlOperationGroups = codeModel.operationGroups.map((g) => transformOperationGroup(g, codeModel));
|
||||
|
||||
return {
|
||||
serviceInformation,
|
||||
models: {
|
||||
enums: caldEnums,
|
||||
objects: cadlObjects,
|
||||
},
|
||||
operationGroups: cadlOperationGroups,
|
||||
};
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
import { CodeModel } from "@autorest/codemodel";
|
||||
import { Session } from "@autorest/extension-base";
|
||||
import { getSession } from "./autorest-session";
|
||||
import { CadlOptions } from "./interfaces";
|
||||
|
||||
export let options: CadlOptions;
|
||||
|
||||
export function getOptions(): CadlOptions {
|
||||
if (!options) {
|
||||
const session = getSession();
|
||||
options = {
|
||||
isAzureSpec: getIsAzureSpec(session),
|
||||
namespace: getNamespace(session),
|
||||
guessResourceKey: getGuessResourceKey(session),
|
||||
};
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
export function getGuessResourceKey(session: Session<CodeModel>) {
|
||||
return session.configuration["guessResourceKey"] !== false;
|
||||
}
|
||||
|
||||
export function getIsAzureSpec(session: Session<CodeModel>) {
|
||||
return session.configuration["isAzureSpec"] !== false;
|
||||
}
|
||||
|
||||
export function getNamespace(session: Session<CodeModel>) {
|
||||
return session.configuration["namespace"];
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
import { CodeModel } from "@autorest/codemodel";
|
||||
|
||||
export interface PathDetails {}
|
||||
|
||||
export type Paths = Map<string, PathDetails>;
|
||||
|
||||
export function getAllPaths(model: CodeModel) {
|
||||
const paths: Paths = new Map();
|
||||
for (const _operationGroup of model.operationGroups) {
|
||||
for (const operation of model.operationGroups) {
|
||||
const path = operation.protocol.http?.path;
|
||||
if (!path) {
|
||||
continue;
|
||||
}
|
||||
paths.set(operation.protocol.http?.path, {});
|
||||
}
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
import { ChoiceSchema, ChoiceValue, CodeModel, SchemaType, SealedChoiceSchema } from "@autorest/codemodel";
|
||||
import { getDataTypes } from "../data-types";
|
||||
import { CadlChoiceValue, CadlEnum } from "../interfaces";
|
||||
import { transformValue } from "../utils/values";
|
||||
|
||||
export function transformEnum(schema: SealedChoiceSchema | ChoiceSchema, codeModel: CodeModel): CadlEnum {
|
||||
const dataTypes = getDataTypes(codeModel);
|
||||
|
||||
let cadlEnum = dataTypes.get(schema) as CadlEnum;
|
||||
|
||||
if (!cadlEnum) {
|
||||
cadlEnum = {
|
||||
doc: schema.language.default.documentation,
|
||||
kind: "enum",
|
||||
name: schema.language.default.name.replace(/-/g, "_"),
|
||||
members: schema.choices.map((choice) => transformChoiceMember(choice)),
|
||||
isExtensible: !isSealedChoiceSchema(schema),
|
||||
...(hasSyntheticName(schema) && {
|
||||
fixMe: [
|
||||
"// FIXME: (synthetic-name) This enum has a generated name. Please rename it to something more appropriate.",
|
||||
],
|
||||
}),
|
||||
};
|
||||
}
|
||||
return cadlEnum;
|
||||
}
|
||||
|
||||
function hasSyntheticName(schema: ChoiceSchema | SealedChoiceSchema) {
|
||||
return schema.language.default.name.startsWith("components·");
|
||||
}
|
||||
|
||||
function transformChoiceMember(member: ChoiceValue): CadlChoiceValue {
|
||||
return {
|
||||
name: member.language.default.name,
|
||||
value: transformValue(member.value),
|
||||
};
|
||||
}
|
||||
|
||||
const isSealedChoiceSchema = (schema: any): schema is SealedChoiceSchema => {
|
||||
return schema.type === SchemaType.SealedChoice;
|
||||
};
|
|
@ -0,0 +1,188 @@
|
|||
import { CodeModel, isObjectSchema, ObjectSchema, Property, Schema, SchemaType } from "@autorest/codemodel";
|
||||
import { getDataTypes } from "../data-types";
|
||||
import { CadlObject, CadlObjectProperty } from "../interfaces";
|
||||
import { addCorePageAlias } from "../utils/alias";
|
||||
import { getModelDecorators, getPropertyDecorators } from "../utils/decorators";
|
||||
import { getDiscriminator, getOwnDiscriminator } from "../utils/discriminator";
|
||||
import { getLogger } from "../utils/logger";
|
||||
import {
|
||||
isArraySchema,
|
||||
isChoiceSchema,
|
||||
isConstantSchema,
|
||||
isDictionarySchema,
|
||||
isSealedChoiceSchema,
|
||||
} from "../utils/schemas";
|
||||
import { transformValue } from "../utils/values";
|
||||
|
||||
const cadlTypes = new Map<SchemaType, string>([
|
||||
[SchemaType.Date, "plainDate"],
|
||||
[SchemaType.DateTime, "zonedDateTime"],
|
||||
[SchemaType.UnixTime, "plainTime"],
|
||||
[SchemaType.String, "string"],
|
||||
[SchemaType.Time, "plainTime"],
|
||||
[SchemaType.Uuid, "string"],
|
||||
[SchemaType.Uri, "string"],
|
||||
[SchemaType.ByteArray, "bytes"],
|
||||
[SchemaType.Binary, "bytes"],
|
||||
[SchemaType.Number, "float32"],
|
||||
[SchemaType.Integer, "int32"],
|
||||
[SchemaType.Boolean, "boolean"],
|
||||
[SchemaType.Credential, "@secret string"],
|
||||
[SchemaType.Duration, "duration"],
|
||||
[SchemaType.AnyObject, "object"],
|
||||
]);
|
||||
|
||||
export function transformObject(schema: ObjectSchema, codeModel: CodeModel): CadlObject {
|
||||
const cadlTypes = getDataTypes(codeModel);
|
||||
let visited: Partial<CadlObject> = cadlTypes.get(schema) as CadlObject;
|
||||
if (visited) {
|
||||
return visited as CadlObject;
|
||||
}
|
||||
|
||||
const logger = getLogger("transformOperationGroup");
|
||||
|
||||
logger.info(`Transforming object ${schema.language.default.name}`);
|
||||
|
||||
const name = schema.language.default.name.replace(/-/g, "_");
|
||||
const doc = schema.language.default.description;
|
||||
|
||||
// Marking as visited before processing properties to avoid infinite recursion
|
||||
// when transforming properties that reference this object.
|
||||
visited = { name, doc };
|
||||
cadlTypes.set(schema, visited as any);
|
||||
|
||||
const properties = (schema.properties ?? [])
|
||||
.filter((p) => !p.isDiscriminator)
|
||||
.map((p) => transformObjectProperty(p, codeModel));
|
||||
|
||||
const ownDiscriminator = getOwnDiscriminator(schema);
|
||||
if (!ownDiscriminator) {
|
||||
const discriminatorProperty = getDiscriminator(schema);
|
||||
discriminatorProperty && properties.push(discriminatorProperty);
|
||||
}
|
||||
|
||||
const updatedVisited: CadlObject = {
|
||||
name,
|
||||
doc,
|
||||
kind: "object",
|
||||
properties,
|
||||
parents: getParents(schema),
|
||||
extendedParents: getExtendedParents(schema),
|
||||
spreadParents: getSpreadParents(schema),
|
||||
decorators: getModelDecorators(schema),
|
||||
};
|
||||
|
||||
addCorePageAlias(updatedVisited);
|
||||
addFixmes(updatedVisited);
|
||||
|
||||
cadlTypes.set(schema, updatedVisited);
|
||||
return updatedVisited;
|
||||
}
|
||||
|
||||
function addFixmes(cadlObject: CadlObject): void {
|
||||
cadlObject.fixMe = cadlObject.fixMe ?? [];
|
||||
|
||||
if ((cadlObject.extendedParents ?? []).length > 1) {
|
||||
cadlObject.fixMe
|
||||
.push(`// FIXME: (multiple-inheritance) Multiple inheritance is not supported in CADL, so this type will only inherit from one parent.
|
||||
// this may happen because of multiple parents having discriminator properties.
|
||||
// Parents not included ${cadlObject.extendedParents?.join(", ")}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function transformObjectProperty(propertySchema: Property, codeModel: CodeModel): CadlObjectProperty {
|
||||
const name = propertySchema.serializedName;
|
||||
const doc = propertySchema.language.default.description;
|
||||
if (isObjectSchema(propertySchema.schema)) {
|
||||
const dataTypes = getDataTypes(codeModel);
|
||||
let visited = dataTypes.get(propertySchema.schema) as CadlObject;
|
||||
if (!visited) {
|
||||
visited = transformObject(propertySchema.schema, codeModel);
|
||||
dataTypes.set(propertySchema.schema, visited);
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "property",
|
||||
name: name,
|
||||
doc: doc,
|
||||
isOptional: propertySchema.required !== true,
|
||||
type: visited.name,
|
||||
decorators: getPropertyDecorators(propertySchema),
|
||||
...(propertySchema.readOnly === true && { visibility: "read" }),
|
||||
};
|
||||
}
|
||||
|
||||
const logger = getLogger("getDiscriminatorProperty");
|
||||
|
||||
logger.info(`Transforming property ${propertySchema.language.default.name} of type ${propertySchema.schema.type}`);
|
||||
return {
|
||||
kind: "property",
|
||||
doc,
|
||||
name,
|
||||
isOptional: propertySchema.required !== true,
|
||||
type: getCadlType(propertySchema.schema, codeModel),
|
||||
decorators: getPropertyDecorators(propertySchema),
|
||||
};
|
||||
}
|
||||
|
||||
function getParents(schema: ObjectSchema): string[] {
|
||||
const immediateParents = schema.parents?.immediate ?? [];
|
||||
|
||||
return immediateParents
|
||||
.filter((p) => p.language.default.name !== schema.language.default.name)
|
||||
.map((p) => p.language.default.name);
|
||||
}
|
||||
|
||||
function getExtendedParents(schema: ObjectSchema): string[] {
|
||||
const immediateParents = schema.parents?.immediate ?? [];
|
||||
return immediateParents
|
||||
.filter((p) => p.language.default.name !== schema.language.default.name)
|
||||
.filter((p) => getOwnDiscriminator(p as ObjectSchema))
|
||||
.map((p) => p.language.default.name);
|
||||
}
|
||||
|
||||
function getSpreadParents(schema: ObjectSchema): string[] {
|
||||
const immediateParents = schema.parents?.immediate ?? [];
|
||||
return immediateParents
|
||||
.filter((p) => p.language.default.name !== schema.language.default.name)
|
||||
.filter((p) => !getOwnDiscriminator(p as ObjectSchema))
|
||||
.map((p) => p.language.default.name);
|
||||
}
|
||||
|
||||
export function getCadlType(schema: Schema, codeModel: CodeModel): string {
|
||||
const schemaType = schema.type;
|
||||
const visited = getDataTypes(codeModel).get(schema);
|
||||
|
||||
if (visited) {
|
||||
return visited.name;
|
||||
}
|
||||
|
||||
if (isConstantSchema(schema)) {
|
||||
return `${transformValue(schema.value.value as any)}`;
|
||||
}
|
||||
|
||||
if (isArraySchema(schema)) {
|
||||
const elementType = getCadlType(schema.elementType, codeModel);
|
||||
return `${elementType}[]`;
|
||||
}
|
||||
|
||||
if (isObjectSchema(schema)) {
|
||||
return schema.language.default.name.replace(/-/g, "_");
|
||||
}
|
||||
|
||||
if (isChoiceSchema(schema) || isSealedChoiceSchema(schema)) {
|
||||
return schema.language.default.name.replace(/-/g, "_");
|
||||
}
|
||||
|
||||
if (isDictionarySchema(schema)) {
|
||||
return `Record<${getCadlType(schema.elementType, codeModel)}>`;
|
||||
}
|
||||
|
||||
const cadlType = cadlTypes.get(schemaType);
|
||||
|
||||
if (!cadlType) {
|
||||
throw new Error(`Unknown type ${schema.type}`);
|
||||
}
|
||||
|
||||
return cadlType;
|
||||
}
|
|
@ -0,0 +1,198 @@
|
|||
import {
|
||||
CodeModel,
|
||||
Operation,
|
||||
OperationGroup,
|
||||
Parameter,
|
||||
ParameterLocation,
|
||||
Protocols,
|
||||
Request,
|
||||
Schema,
|
||||
SchemaResponse,
|
||||
} from "@autorest/codemodel";
|
||||
import { getDataTypes } from "../data-types";
|
||||
import { CadlOperation, CadlOperationGroup, CadlParameter, CadlParameterLocation, Extension } from "../interfaces";
|
||||
import { transformDataType } from "../model";
|
||||
import { getLogger } from "../utils/logger";
|
||||
import { getLanguageMetadata } from "../utils/metadata";
|
||||
import { isConstantSchema } from "../utils/schemas";
|
||||
|
||||
export function transformOperationGroup(
|
||||
{ language, operations }: OperationGroup,
|
||||
codeModel: CodeModel,
|
||||
): CadlOperationGroup {
|
||||
const name = language.default.name ? `${language.default.name}Operations` : "";
|
||||
const doc = language.default.description;
|
||||
const ops = operations.reduce<CadlOperation[]>((acc, op) => {
|
||||
acc = [...acc, ...transformOperation(op, codeModel)];
|
||||
return acc;
|
||||
}, []);
|
||||
return {
|
||||
name,
|
||||
doc,
|
||||
operations: ops,
|
||||
};
|
||||
}
|
||||
|
||||
function transformRoute(protocol?: Protocols) {
|
||||
return protocol?.http?.path;
|
||||
}
|
||||
|
||||
function transformVerb(protocol?: Protocols) {
|
||||
return protocol?.http?.method;
|
||||
}
|
||||
|
||||
function transformResponses(responses: SchemaResponse[] = [], codeModel: CodeModel) {
|
||||
const dataTypes = getDataTypes(codeModel);
|
||||
return responses.map(({ schema }) => {
|
||||
const responseName = dataTypes.get(schema)?.name;
|
||||
|
||||
if (!responseName) {
|
||||
return "void";
|
||||
}
|
||||
|
||||
if (schema.language.default.paging?.isPageable && schema.language.default.resource) {
|
||||
return `Azure.Core.ResourceList<${responseName}>`;
|
||||
}
|
||||
|
||||
return responseName;
|
||||
});
|
||||
}
|
||||
|
||||
export function transformOperation(operation: Operation, codeModel: CodeModel): CadlOperation[] {
|
||||
return (operation.requests ?? []).map((r) => transformRequest(r, operation, codeModel));
|
||||
}
|
||||
|
||||
function transformRequest(_request: Request, operation: Operation, codeModel: CodeModel): CadlOperation {
|
||||
const { language, responses, requests } = operation;
|
||||
const name = language.default.name;
|
||||
const doc = language.default.description;
|
||||
const summary = language.default.summary;
|
||||
const { paging } = getLanguageMetadata(operation.language);
|
||||
const transformedResponses = transformResponses([...(responses ?? [])] as SchemaResponse[], codeModel);
|
||||
const visitedParameter: Set<Parameter> = new Set();
|
||||
let parameters = (operation.parameters ?? [])
|
||||
.filter((p) => filterOperationParameters(p, visitedParameter))
|
||||
.map((v) => transformParameter(v, codeModel));
|
||||
|
||||
parameters = [
|
||||
...parameters,
|
||||
...getRequestParameters(operation)
|
||||
.filter((p) => filterOperationParameters(p, visitedParameter))
|
||||
.map((v) => transformParameter(v, codeModel)),
|
||||
];
|
||||
|
||||
const extensions: Extension[] = [];
|
||||
|
||||
if (paging) {
|
||||
extensions.push("Pageable");
|
||||
}
|
||||
|
||||
const resource = operation.language.default.resource;
|
||||
|
||||
return {
|
||||
name,
|
||||
doc,
|
||||
summary,
|
||||
parameters,
|
||||
verb: transformVerb(requests?.[0].protocol),
|
||||
route: transformRoute(requests?.[0].protocol),
|
||||
responses: [...new Set(transformedResponses)],
|
||||
extensions: [],
|
||||
resource,
|
||||
};
|
||||
}
|
||||
|
||||
function constantValueEquals(schema: Schema, match: string) {
|
||||
if (isConstantSchema(schema)) {
|
||||
const value = schema.value.value;
|
||||
if (typeof value === "string") {
|
||||
return value.toLowerCase() === match.toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function filterOperationParameters(parameter: Parameter, visitedParameters: Set<Parameter>): boolean {
|
||||
if (
|
||||
parameter.protocol.http?.in === ParameterLocation.Query &&
|
||||
parameter.language.default.serializedName === "api-version"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
parameter.origin === "modelerfour:synthesized/accept" &&
|
||||
constantValueEquals(parameter.schema, "application/json")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (visitedParameters.has(parameter)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const shouldVisit = ["path", "body", "header", "query"].includes(parameter.protocol.http?.in);
|
||||
|
||||
if (shouldVisit) {
|
||||
visitedParameters.add(parameter);
|
||||
}
|
||||
|
||||
return shouldVisit;
|
||||
}
|
||||
|
||||
export function transformParameter(parameter: Parameter, codeModel: CodeModel): CadlParameter {
|
||||
// Body parameter doesn't have a serializedName, in that case we get the name
|
||||
const name = parameter.language.default.serializedName ?? parameter.language.default.name;
|
||||
const doc = parameter.language.default.description;
|
||||
|
||||
const dataTypes = getDataTypes(codeModel);
|
||||
const visited = dataTypes.get(parameter.schema) ?? transformDataType(parameter.schema, codeModel);
|
||||
|
||||
return {
|
||||
kind: "parameter",
|
||||
doc,
|
||||
name,
|
||||
isOptional: parameter.required !== true,
|
||||
type: visited.name,
|
||||
location: transformParameterLocation(parameter),
|
||||
};
|
||||
}
|
||||
|
||||
function getRequestParameters(operation: Operation): Parameter[] {
|
||||
const logger = getLogger("getRequestParameters");
|
||||
if (!operation.requests?.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (operation.requests.length > 1) {
|
||||
const message = `Operation ${operation.language.default.name} has more than one request`;
|
||||
logger.info(message);
|
||||
}
|
||||
|
||||
const parameters = operation.requests[0].parameters ?? [];
|
||||
const signatureParameters = operation.requests[0].signatureParameters ?? [];
|
||||
|
||||
return [...parameters, ...signatureParameters];
|
||||
}
|
||||
|
||||
function transformParameterLocation(parameter: Parameter): CadlParameterLocation {
|
||||
const location: ParameterLocation = parameter.protocol.http?.in;
|
||||
|
||||
if (!location) {
|
||||
throw new Error(`Parameter ${parameter.language.default.name} has no location defined`);
|
||||
}
|
||||
|
||||
switch (location) {
|
||||
case ParameterLocation.Path:
|
||||
return "path";
|
||||
case ParameterLocation.Query:
|
||||
return "query";
|
||||
case ParameterLocation.Header:
|
||||
return "header";
|
||||
case ParameterLocation.Body:
|
||||
return "body";
|
||||
default:
|
||||
throw new Error(`Unknown location ${location}`);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
import { CodeModel, ImplementationLocation, ParameterLocation } from "@autorest/codemodel";
|
||||
import { EndpointParameter, ServiceInformation } from "../interfaces";
|
||||
import { getFirstEndpoint } from "../utils/get-endpoint";
|
||||
import { isConstantSchema } from "../utils/schemas";
|
||||
|
||||
export function transformServiceInformation(model: CodeModel): ServiceInformation {
|
||||
return {
|
||||
name: model.info.title,
|
||||
doc: model.info.description ?? "// FIXME: (miissing-service-description) Add service description",
|
||||
endpoint: getFirstEndpoint(model),
|
||||
endpointParameters: transformEndpointParameters(model),
|
||||
version: getApiVersion(model),
|
||||
};
|
||||
}
|
||||
|
||||
export function transformEndpointParameters(model: CodeModel): EndpointParameter[] {
|
||||
const globalParameters = (model.globalParameters ?? []).filter(
|
||||
(p) => p.implementation === "Client" && p.protocol?.http?.in === "uri",
|
||||
);
|
||||
|
||||
return globalParameters.map((p) => ({
|
||||
doc: p.language.default.description ?? "",
|
||||
name: p.language.default.serializedName,
|
||||
}));
|
||||
}
|
||||
|
||||
function getApiVersion(model: CodeModel): string | undefined {
|
||||
if (!model.globalParameters || !model.globalParameters.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const apiVersionParam = model.globalParameters
|
||||
.filter(
|
||||
(gp) => gp.implementation === ImplementationLocation.Client && gp.protocol.http?.in === ParameterLocation.Query,
|
||||
)
|
||||
.find((param) => param.language.default.serializedName === "api-version");
|
||||
|
||||
if (apiVersionParam && isConstantSchema(apiVersionParam.schema)) {
|
||||
return apiVersionParam.schema.value.value.toString();
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
import { CadlAlias, CadlObject } from "../interfaces";
|
||||
|
||||
export function addCorePageAlias(cadlObject: CadlObject): CadlAlias | undefined {
|
||||
if (!cadlObject.decorators?.some((d) => d.name === "pagedResult")) {
|
||||
return;
|
||||
}
|
||||
const value = cadlObject.properties.filter((p) => p.name === "value");
|
||||
if (!cadlObject.properties.some((p) => p.name === "nextLink") || !value.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
cadlObject.decorators = cadlObject.decorators.filter((d) => d.name !== "pagedResult");
|
||||
cadlObject.properties = cadlObject.properties.filter((p) => p.name !== "nextLink" && p.name !== "value");
|
||||
|
||||
cadlObject.alias = {
|
||||
alias: "Azure.Core.Page",
|
||||
params: [value[0].type.replace("[]", "")],
|
||||
module: "@azure-tools/cadl-azure-core",
|
||||
};
|
||||
|
||||
return;
|
||||
}
|
|
@ -0,0 +1,90 @@
|
|||
import { ObjectSchema, Property } from "@autorest/codemodel";
|
||||
import { CadlDecorator } from "../interfaces";
|
||||
import { getOwnDiscriminator } from "./discriminator";
|
||||
|
||||
export function getModelDecorators(model: ObjectSchema): CadlDecorator[] {
|
||||
const decorators: CadlDecorator[] = [];
|
||||
|
||||
const paging = model.language.default.paging ?? {};
|
||||
if (paging.isPageable) {
|
||||
decorators.push({
|
||||
name: "pagedResult",
|
||||
module: "@azure-tools/cadl-azure-core",
|
||||
namespace: "Azure.Core",
|
||||
});
|
||||
}
|
||||
|
||||
const ownDiscriminator = getOwnDiscriminator(model);
|
||||
|
||||
if (ownDiscriminator) {
|
||||
decorators.push({
|
||||
name: "discriminator",
|
||||
arguments: [ownDiscriminator.serializedName],
|
||||
});
|
||||
}
|
||||
|
||||
if (model.language.default.isError) {
|
||||
decorators.push({ name: "error" });
|
||||
}
|
||||
|
||||
let resource = model.language.default.resource;
|
||||
if (resource) {
|
||||
if (resource.startsWith("/")) {
|
||||
// Remove the leading
|
||||
resource = resource.slice(1);
|
||||
}
|
||||
decorators.push({
|
||||
name: "resource",
|
||||
module: "@azure-tools/cadl-azure-core",
|
||||
namespace: "Azure.Core",
|
||||
arguments: [resource],
|
||||
});
|
||||
}
|
||||
|
||||
return decorators;
|
||||
}
|
||||
|
||||
export function getPropertyDecorators(property: Property): CadlDecorator[] {
|
||||
const decorators: CadlDecorator[] = [];
|
||||
|
||||
const paging = property.language.default.paging ?? {};
|
||||
|
||||
if (property.readOnly) {
|
||||
decorators.push({ name: "visibility", arguments: ["read"] });
|
||||
}
|
||||
|
||||
if (paging.isNextLink) {
|
||||
decorators.push({ name: "nextLink" });
|
||||
}
|
||||
|
||||
if (paging.isValue) {
|
||||
decorators.push({ name: "items" });
|
||||
}
|
||||
|
||||
if (property.language.default.isResourceKey) {
|
||||
decorators.push({
|
||||
name: "key",
|
||||
fixMe: [
|
||||
"// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one",
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
return decorators;
|
||||
}
|
||||
|
||||
export function generateDecorators(decorators: CadlDecorator[] = []): string {
|
||||
const definitions: string[] = [];
|
||||
for (const decorator of decorators ?? []) {
|
||||
if (decorator.fixMe) {
|
||||
definitions.push(decorator.fixMe.join(`\n`));
|
||||
}
|
||||
if (decorator.arguments) {
|
||||
definitions.push(`@${decorator.name}(${decorator.arguments?.map((a) => `"${a}"`).join(", ")})`);
|
||||
} else {
|
||||
definitions.push(`@${decorator.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
return definitions.join("\n");
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
import { ObjectSchema, Property } from "@autorest/codemodel";
|
||||
import { CadlObjectProperty } from "../interfaces";
|
||||
import { getLogger } from "./logger";
|
||||
|
||||
export function getOwnDiscriminator(schema: ObjectSchema): Property | undefined {
|
||||
return schema.discriminator?.property;
|
||||
}
|
||||
|
||||
export function getDiscriminator(schema: ObjectSchema): CadlObjectProperty | undefined {
|
||||
if (!schema.discriminatorValue) {
|
||||
return undefined;
|
||||
}
|
||||
const { serializedName: name, language } = getDiscriminatorProperty(schema);
|
||||
const type = `"${schema.discriminatorValue}"`;
|
||||
|
||||
return {
|
||||
isOptional: false,
|
||||
name,
|
||||
type,
|
||||
kind: "property",
|
||||
doc: language.default.description,
|
||||
};
|
||||
}
|
||||
|
||||
function getDiscriminatorProperty(schema: ObjectSchema): Property {
|
||||
const logger = getLogger("getDiscriminatorProperty");
|
||||
|
||||
logger.info(`Getting discriminator property for ${schema.language.default.name}`);
|
||||
|
||||
if (schema.discriminator?.property) {
|
||||
return schema.discriminator.property;
|
||||
}
|
||||
|
||||
if (!schema.parents?.immediate || schema.parents.immediate.length === 0) {
|
||||
throw new Error("No discriminator property found");
|
||||
}
|
||||
|
||||
for (const parent of schema.parents.immediate as ObjectSchema[]) {
|
||||
const discriminator = getDiscriminatorProperty(parent);
|
||||
|
||||
if (discriminator) {
|
||||
return discriminator;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("No discriminator property found");
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
import { WithSummary } from "../interfaces";
|
||||
|
||||
interface WithDocs {
|
||||
doc?: string | string[];
|
||||
}
|
||||
|
||||
export function generateDocs({ doc }: WithDocs): string {
|
||||
if (isEmptyDoc(doc)) {
|
||||
return ``;
|
||||
}
|
||||
|
||||
let docString = Array.isArray(doc) ? doc.join("\n") : doc;
|
||||
docString = docString.replace(/\\/g, "\\\\");
|
||||
docString = docString.replace(/"/g, '\\"');
|
||||
docString = lineWrap(docString);
|
||||
|
||||
return `@doc(${docString})`;
|
||||
}
|
||||
|
||||
export function generateSummary({ summary }: WithSummary): string {
|
||||
if (isEmptyDoc(summary)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return `@summary(${lineWrap(summary)})`;
|
||||
}
|
||||
|
||||
function lineWrap(doc: string) {
|
||||
const maxLength = 80;
|
||||
|
||||
if (doc.length <= maxLength) {
|
||||
return `"${doc}"`;
|
||||
}
|
||||
|
||||
const lines: string[] = [`"""`];
|
||||
const words = doc.split(" ");
|
||||
let line = ``;
|
||||
for (const word of words) {
|
||||
if (word.length + 1 > maxLength - line.length) {
|
||||
// Don't add the leading space
|
||||
lines.push(line.substring(0, line.length - 1));
|
||||
|
||||
// Start a new line
|
||||
line = `${word} `;
|
||||
} else {
|
||||
line = `${line}${word} `;
|
||||
}
|
||||
}
|
||||
lines.push(`${line.substring(0, line.length - 1)}`);
|
||||
lines.push(`"""`);
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function isEmptyDoc(doc?: string | string[]): doc is undefined {
|
||||
if (!doc) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Array.isArray(doc) && !doc.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
import { CodeModel } from "@autorest/codemodel";
|
||||
import { isResponseSchema } from "./schemas";
|
||||
|
||||
export function markErrorModels(codeModel: CodeModel) {
|
||||
for (const operationGroup of codeModel.operationGroups) {
|
||||
for (const operation of operationGroup.operations) {
|
||||
const exceptions = operation.exceptions ?? [];
|
||||
for (const exception of exceptions) {
|
||||
if (isResponseSchema(exception)) {
|
||||
exception.schema.language.default.isError = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
import { format } from "prettier";
|
||||
import { getLogger } from "./logger";
|
||||
|
||||
export function formatFile(content: string, filepath: string) {
|
||||
return format(content, {
|
||||
filepath,
|
||||
});
|
||||
}
|
||||
|
||||
export function formatCadlFile(content: string, filepath: string): string {
|
||||
try {
|
||||
return format(content, {
|
||||
plugins: ["@cadl-lang/prettier-plugin-cadl"],
|
||||
pluginSearchDirs: ["./node_modules"],
|
||||
filepath,
|
||||
});
|
||||
} catch {
|
||||
return content;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
import { CodeModel } from "@autorest/codemodel";
|
||||
|
||||
export function getFirstEndpoint(model: CodeModel) {
|
||||
for (const group of model.operationGroups) {
|
||||
for (const operation of group.operations) {
|
||||
for (const request of operation.requests ?? []) {
|
||||
if (!request.protocol.http) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const endpoint = request.protocol.http.uri;
|
||||
if (endpoint) {
|
||||
return endpoint;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
import { CadlProgram } from "../interfaces";
|
||||
|
||||
type Imports = {
|
||||
modules: string[];
|
||||
namespaces: string[];
|
||||
};
|
||||
|
||||
export function getModelsImports(program: CadlProgram) {
|
||||
const modules = new Set<string>();
|
||||
const namespaces = new Set<string>();
|
||||
for (const model of program.models.objects) {
|
||||
model.alias?.module && modules.add(`import "${model.alias.module}";`);
|
||||
for (const decorator of model.decorators ?? []) {
|
||||
decorator.module && modules.add(`import "${decorator.module}";`);
|
||||
decorator.namespace && namespaces.add(`using ${decorator.namespace};`);
|
||||
}
|
||||
|
||||
for (const property of model.properties) {
|
||||
for (const decorator of property.decorators ?? []) {
|
||||
decorator.module && modules.add(`import "${decorator.module}";`);
|
||||
decorator.namespace && namespaces.add(`using ${decorator.namespace};`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
modules: [...modules],
|
||||
namespaces: [...namespaces],
|
||||
};
|
||||
}
|
||||
|
||||
export function getRoutesImports(_program: CadlProgram) {
|
||||
const imports: Imports = {
|
||||
modules: [`import "@azure-tools/cadl-azure-core";`, `import "@cadl-lang/rest";`, `import "./models.cadl";`],
|
||||
namespaces: [`using Cadl.Rest;`, `using Cadl.Http;`],
|
||||
};
|
||||
|
||||
return imports;
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
import { getSession } from "../autorest-session";
|
||||
|
||||
export interface Logger {
|
||||
info: (message: string) => void;
|
||||
error: (message: string) => void;
|
||||
warning: (message: string) => void;
|
||||
debug: (message: string) => void;
|
||||
verbose: (message: string) => void;
|
||||
}
|
||||
|
||||
export function getLogger(scope: string) {
|
||||
const session = getSession();
|
||||
const { error, warning, debug, verbose } = session;
|
||||
|
||||
return {
|
||||
info: function (message: string) {
|
||||
session.info(`${scope}: ${message}`);
|
||||
},
|
||||
error: (message: string) => error(`${scope}: ${message}`, []),
|
||||
warning: (message: string) => warning(`${scope}: ${message}`, []),
|
||||
debug: (message: string) => debug(`${scope}: ${message}`),
|
||||
verbose: (message: string) => verbose(`${scope}: ${message}`),
|
||||
};
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
import { CodeModel, isObjectSchema, Operation } from "@autorest/codemodel";
|
||||
import { isResponseSchema } from "./schemas";
|
||||
|
||||
export function markLRO(codeModel: CodeModel) {
|
||||
for (const operationGroup of codeModel.operationGroups) {
|
||||
for (const operation of operationGroup.operations) {
|
||||
operation.extensions ?? {};
|
||||
if (!hasLROExtension(operation)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const response of operation.responses ?? []) {
|
||||
if (!isResponseSchema(response)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isObjectSchema(response.schema)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
response.schema.language.default.lro = {
|
||||
...response.schema.language.default.lro,
|
||||
isLRO: true,
|
||||
};
|
||||
|
||||
// TODO: mark the response as an LRO
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function hasLROExtension(operation: Operation) {
|
||||
return (
|
||||
operation.extensions?.["x-ms-long-running-operation"] ||
|
||||
operation.extensions?.["x-ms-long-running-operation-options"]
|
||||
);
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
import { Language, Languages } from "@autorest/codemodel";
|
||||
|
||||
export function getLanguageMetadata(languages: Languages): Language {
|
||||
return languages.typescript || languages.javascript || languages.default;
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
import { CadlProgram } from "../interfaces";
|
||||
import { getOptions } from "../options";
|
||||
|
||||
export function getNamespace(program: CadlProgram) {
|
||||
let { namespace } = getOptions();
|
||||
|
||||
namespace = namespace ?? program.serviceInformation.name.replace(/ /g, "").replace(/-/g, "");
|
||||
|
||||
return `namespace ${namespace};`;
|
||||
}
|
|
@ -0,0 +1,118 @@
|
|||
import { CodeModel, Operation, isObjectSchema, Response, Property } from "@autorest/codemodel";
|
||||
import { getLanguageMetadata } from "./metadata";
|
||||
import { isResponseSchema } from "./schemas";
|
||||
|
||||
export interface PaginationExtension {
|
||||
/**
|
||||
* The name of the field in the response that can be paged over.
|
||||
*/
|
||||
itemName?: string;
|
||||
/**
|
||||
* Name of the field containing the nextLink value.
|
||||
* An empty object indicates a null value and that all results
|
||||
* are returned in a single page.
|
||||
*/
|
||||
nextLinkName?: string | {};
|
||||
// 'nextLinkOperation', 'group', and 'member' are used together.
|
||||
/**
|
||||
* Reference to the operation to call to get the next page.
|
||||
*/
|
||||
nextLinkOperation?: Operation;
|
||||
/**
|
||||
* The name of the operationGroup that nextLinkOperation resides in.
|
||||
*/
|
||||
group?: string;
|
||||
/**
|
||||
* The name of the operation that nextLinkOperation references.
|
||||
*/
|
||||
member?: string;
|
||||
/**
|
||||
* Indicates whether this operation is used by another operation to get pages.
|
||||
*/
|
||||
isNextLinkMethod?: boolean;
|
||||
}
|
||||
|
||||
export function isPageableOperation(operation: Operation): boolean {
|
||||
const languageMetadata = getLanguageMetadata(operation.language);
|
||||
const paginationExtension = languageMetadata.paging;
|
||||
return Boolean(paginationExtension);
|
||||
}
|
||||
|
||||
export function getPageableResponse(operation: Operation): Response | undefined {
|
||||
if (!isPageableOperation(operation)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
for (const response of operation.responses ?? []) {
|
||||
if (!isResponseSchema(response)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isObjectSchema(response.schema)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!response.schema.language.default.paging.isPageable) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function isPageValue(property: Property) {
|
||||
return Boolean(property.language.default.paging?.isValue);
|
||||
}
|
||||
|
||||
export function markPagination(codeModel: CodeModel) {
|
||||
for (const operationGroup of codeModel.operationGroups) {
|
||||
for (const operation of operationGroup.operations) {
|
||||
const languageMetadata = getLanguageMetadata(operation.language);
|
||||
const paginationExtension = languageMetadata.paging;
|
||||
if (!isPageableOperation(operation)) {
|
||||
continue;
|
||||
}
|
||||
const itemName = paginationExtension.itemName || "value";
|
||||
let nextLinkName: string | null = "nextLink";
|
||||
|
||||
if (typeof paginationExtension.nextLinkName === "string") {
|
||||
nextLinkName = paginationExtension.nextLinkName;
|
||||
} else if (typeof paginationExtension.nextLinkName === "object") {
|
||||
nextLinkName = null;
|
||||
}
|
||||
|
||||
for (const response of operation.responses ?? []) {
|
||||
if (!isResponseSchema(response)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isObjectSchema(response.schema)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
response.schema.language.default.paging = {
|
||||
...response.schema.language.default.paging,
|
||||
isPageable: true,
|
||||
};
|
||||
|
||||
for (const property of response.schema.properties ?? []) {
|
||||
if (property.serializedName === nextLinkName) {
|
||||
property.language.default.paging = {
|
||||
...property.language.default.paging,
|
||||
isNextLink: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (property.serializedName === itemName) {
|
||||
property.language.default.paging = {
|
||||
...property.language.default.paging,
|
||||
isValue: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,377 @@
|
|||
import {
|
||||
ArraySchema,
|
||||
CodeModel,
|
||||
ComplexSchema,
|
||||
HttpMethod,
|
||||
isObjectSchema,
|
||||
ObjectSchema,
|
||||
Operation,
|
||||
Property,
|
||||
Schema,
|
||||
SchemaResponse,
|
||||
} from "@autorest/codemodel";
|
||||
import { getDataTypes } from "../data-types";
|
||||
import { CadlResource } from "../interfaces";
|
||||
import { transformDataType } from "../model";
|
||||
import { getOptions } from "../options";
|
||||
import { hasLROExtension } from "./lro";
|
||||
import { getPageableResponse, isPageableOperation, isPageValue } from "./paging";
|
||||
import { isArraySchema, isResponseSchema } from "./schemas";
|
||||
|
||||
const knownResourceSchema: Map<string, Schema> = new Map();
|
||||
|
||||
export function markResources(codeModel: CodeModel) {
|
||||
for (const operationGroup of codeModel.operationGroups) {
|
||||
for (const operation of operationGroup.operations) {
|
||||
const resource = getResourceKind(codeModel, operation);
|
||||
if (resource) {
|
||||
operation.language.default.resource = resource;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Figures out if the path represents an
|
||||
*/
|
||||
// function markActionResource(codeModel: CodeModel, operation: Operation): void {
|
||||
// const method = getHttpMethod(codeModel, operation);
|
||||
// const pathParts = getResourcePath(operation).split("/");
|
||||
// const partsLastIndex = pathParts.length - 1;
|
||||
|
||||
// if (method !== HttpMethod.Post) {
|
||||
// return;
|
||||
// }
|
||||
|
||||
// const lastPart = pathParts[partsLastIndex];
|
||||
|
||||
// if (lastPart.startsWith(":")) {
|
||||
// operation.language.default.actionResource = {
|
||||
// resource: pathParts.slice(0, partsLastIndex).join("/"),
|
||||
// action: lastPart,
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
function isActionOperation(operation: Operation) {
|
||||
const path = getResourcePath(operation);
|
||||
const pathParts = path.split("/");
|
||||
const lastPart = pathParts[pathParts.length - 1];
|
||||
return lastPart.startsWith(":");
|
||||
}
|
||||
|
||||
function getResourceKind(codeModel: CodeModel, operation: Operation): CadlResource | undefined {
|
||||
if (isActionOperation(operation)) {
|
||||
// Actions are not yet supported
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const operationMethod = getHttpMethod(codeModel, operation);
|
||||
if (hasLROExtension(operation)) {
|
||||
const resource = handleLROResource(codeModel, operation);
|
||||
if (resource) {
|
||||
return resource;
|
||||
}
|
||||
}
|
||||
|
||||
if (operationMethod === HttpMethod.Get) {
|
||||
const resource = handleGetOperation(codeModel, operation);
|
||||
if (resource) {
|
||||
return resource;
|
||||
}
|
||||
}
|
||||
|
||||
if (operationMethod === HttpMethod.Patch) {
|
||||
const resource = handleResource(codeModel, operation, "ResourceCreateOrUpdate");
|
||||
if (resource) {
|
||||
return resource;
|
||||
}
|
||||
}
|
||||
|
||||
if (operationMethod === HttpMethod.Put) {
|
||||
const resource = handleResource(codeModel, operation, "ResourceCreateOrReplace");
|
||||
if (resource) {
|
||||
return resource;
|
||||
}
|
||||
}
|
||||
|
||||
if (operationMethod === HttpMethod.Post) {
|
||||
const resource = handleResource(codeModel, operation, "ResourceCreateWithServiceProvidedName");
|
||||
if (resource) {
|
||||
return resource;
|
||||
}
|
||||
}
|
||||
|
||||
if (operationMethod === HttpMethod.Delete) {
|
||||
const resource = handleResource(codeModel, operation, "ResourceDelete");
|
||||
if (resource) {
|
||||
return resource;
|
||||
}
|
||||
}
|
||||
|
||||
if (operation.language.default.actionResource) {
|
||||
return handleResource(codeModel, operation, "ResourceAction");
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function handleLROResource(codeModel: CodeModel, operation: Operation): CadlResource | undefined {
|
||||
const operationMethod = getHttpMethod(codeModel, operation);
|
||||
|
||||
if (operationMethod === HttpMethod.Patch) {
|
||||
return handleResource(codeModel, operation, "LongRunningResourceCreateOrUpdate");
|
||||
}
|
||||
|
||||
if (operationMethod === HttpMethod.Put) {
|
||||
return handleResource(codeModel, operation, "LongRunningResourceCreateOrReplace");
|
||||
}
|
||||
|
||||
if (operationMethod === HttpMethod.Post) {
|
||||
return handleResource(codeModel, operation, "LongRunningResourceCreateWithServiceProvidedName");
|
||||
}
|
||||
|
||||
if (operationMethod === HttpMethod.Delete) {
|
||||
return handleResource(codeModel, operation, "LongRunningResourceDelete");
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function handleResource(
|
||||
codeModel: CodeModel,
|
||||
operation: Operation,
|
||||
kind:
|
||||
| "ResourceRead"
|
||||
| "ResourceCreateOrUpdate"
|
||||
| "ResourceCreateOrReplace"
|
||||
| "ResourceCreateWithServiceProvidedName"
|
||||
| "ResourceDelete"
|
||||
| "LongRunningResourceCreateOrReplace"
|
||||
| "LongRunningResourceCreateOrUpdate"
|
||||
| "LongRunningResourceCreateWithServiceProvidedName"
|
||||
| "LongRunningResourceDelete"
|
||||
| "ResourceAction",
|
||||
): CadlResource | undefined {
|
||||
const dataTypes = getDataTypes(codeModel);
|
||||
for (const response of operation.responses ?? []) {
|
||||
let schema: Schema | undefined;
|
||||
if (!isResponseSchema(response)) {
|
||||
let resourcePath = getResourcePath(operation);
|
||||
schema = knownResourceSchema.get(resourcePath);
|
||||
|
||||
if (kind === "ResourceAction" && operation.language.default.actionResource?.resource) {
|
||||
resourcePath = operation.language.default.actionResource.resource;
|
||||
schema = knownResourceSchema.get(resourcePath);
|
||||
}
|
||||
|
||||
if (!schema) {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
schema = response.schema;
|
||||
}
|
||||
if (!markResource(operation, schema)) {
|
||||
return undefined;
|
||||
}
|
||||
const cadlResponse = dataTypes.get(schema) ?? transformDataType(schema, codeModel);
|
||||
return {
|
||||
kind,
|
||||
response: cadlResponse,
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getResourcePath(operation: Operation): string {
|
||||
for (const requests of operation.requests ?? []) {
|
||||
const path = requests.protocol.http?.path;
|
||||
if (path) {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Couldn't find a resource path for operation ${operation.language.default.name}`);
|
||||
}
|
||||
|
||||
function getHttpMethod(_codeModel: CodeModel, operation: Operation): HttpMethod {
|
||||
return operation.requests?.[0].protocol.http?.method;
|
||||
}
|
||||
|
||||
function getNonPageableListResource(operation: Operation): ArraySchema | undefined {
|
||||
if (!operation.responses) {
|
||||
throw new Error(`Operation ${operation.language.default.name} has no defined responses`);
|
||||
}
|
||||
for (const response of operation.responses) {
|
||||
let schema: Schema | undefined;
|
||||
if (!isResponseSchema(response)) {
|
||||
const resourcePath = getResourcePath(operation);
|
||||
schema = knownResourceSchema.get(resourcePath);
|
||||
|
||||
if (!schema) {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
schema = response.schema;
|
||||
}
|
||||
|
||||
if (!isArraySchema(schema)) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const firstResponse = operation.responses[0];
|
||||
return isResponseSchema(firstResponse) && isArraySchema(firstResponse.schema) ? firstResponse.schema : undefined;
|
||||
}
|
||||
|
||||
function handleGetOperation(codeModel: CodeModel, operation: Operation): CadlResource | undefined {
|
||||
if (isPageableOperation(operation)) {
|
||||
return getPageableResource(codeModel, operation);
|
||||
}
|
||||
|
||||
const nonPageableListResource = getNonPageableListResource(operation);
|
||||
if (nonPageableListResource) {
|
||||
if (!markResource(operation, nonPageableListResource.elementType)) {
|
||||
return undefined;
|
||||
}
|
||||
const dataTypes = getDataTypes(codeModel);
|
||||
const cadlResponse =
|
||||
dataTypes.get(nonPageableListResource.elementType) ??
|
||||
transformDataType(nonPageableListResource.elementType, codeModel);
|
||||
return {
|
||||
kind: "NonPagedResourceList",
|
||||
response: cadlResponse,
|
||||
};
|
||||
}
|
||||
|
||||
return handleResource(codeModel, operation, "ResourceRead");
|
||||
}
|
||||
|
||||
function markResource(operation: Operation, elementType: Schema) {
|
||||
if (!isObjectSchema(elementType)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const hasKey = markWithKey(elementType);
|
||||
if (hasKey) {
|
||||
markModelWithResource(elementType, getResourcePath(operation));
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function getPageableResource(codeModel: CodeModel, operation: Operation): CadlResource | undefined {
|
||||
const response = getPageableResponse(operation) as SchemaResponse;
|
||||
if (isObjectSchema(response.schema)) {
|
||||
for (const property of response.schema.properties ?? []) {
|
||||
if (isPageValue(property) && isArraySchema(property.schema)) {
|
||||
const dataTypes = getDataTypes(codeModel);
|
||||
|
||||
const elementType = property.schema.elementType;
|
||||
if (!isObjectSchema(elementType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!markResource(operation, elementType)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const cadlResponse = dataTypes.get(elementType) ?? transformDataType(elementType, codeModel);
|
||||
return {
|
||||
kind: "ResourceList",
|
||||
response: cadlResponse,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Couldn't determine the Pageable resource for the operation: ${operation.language.default.name}`);
|
||||
}
|
||||
|
||||
function markModelWithResource(elementType: Schema, resource: string) {
|
||||
knownResourceSchema.set(resource, elementType);
|
||||
elementType.language.default.resource = resource;
|
||||
}
|
||||
|
||||
function markWithKey(schema: ObjectSchema): boolean {
|
||||
const { properties, parents } = schema;
|
||||
const { guessResourceKey } = getOptions();
|
||||
|
||||
if (!guessResourceKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (parents && parents.immediate.length) {
|
||||
if (hasParentWithKey(parents.immediate)) {
|
||||
return false;
|
||||
}
|
||||
const defaultKeyInParent = shouldTryDefaultKeyInParent(schema);
|
||||
if (markParents(parents.immediate, defaultKeyInParent)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return markKeyProperty(properties ?? [], true);
|
||||
}
|
||||
|
||||
function hasParentWithKey(parents: ComplexSchema[]) {
|
||||
for (const parent of parents) {
|
||||
if (!isObjectSchema(parent)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const properties = parent.properties ?? [];
|
||||
|
||||
if (properties.some((p) => p.language.default.isResourceKey)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function markParents(parents: ComplexSchema[], defaultToFirst = false): boolean {
|
||||
for (const parent of parents) {
|
||||
if (!isObjectSchema(parent)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const properties = parent.properties ?? [];
|
||||
if (markKeyProperty(properties, defaultToFirst)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function shouldTryDefaultKeyInParent(schema: ObjectSchema) {
|
||||
if (schema.properties && schema.properties.some((p) => p.required)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function markKeyProperty(allProperties: Property[], defaultToFirst = false): boolean {
|
||||
const properties = allProperties.filter((p) => p.required && !p.isDiscriminator);
|
||||
|
||||
for (const property of properties) {
|
||||
const serializedName = property.serializedName.toLowerCase();
|
||||
if (serializedName.endsWith("name") || serializedName.endsWith("key") || serializedName.endsWith("id")) {
|
||||
property.language.default.isResourceKey = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (defaultToFirst) {
|
||||
const firstRequired = properties.find((p) => p.required);
|
||||
if (firstRequired) {
|
||||
firstRequired.language.default.isResourceKey = true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
import {
|
||||
ArraySchema,
|
||||
ChoiceSchema,
|
||||
ConstantSchema,
|
||||
DictionarySchema,
|
||||
Schema,
|
||||
SchemaResponse,
|
||||
SchemaType,
|
||||
SealedChoiceSchema,
|
||||
Response,
|
||||
} from "@autorest/codemodel";
|
||||
|
||||
export function isConstantSchema(schema: Schema): schema is ConstantSchema {
|
||||
return schema.type === SchemaType.Constant;
|
||||
}
|
||||
|
||||
export function isArraySchema(schema: Schema): schema is ArraySchema {
|
||||
return schema.type === SchemaType.Array;
|
||||
}
|
||||
|
||||
export function isChoiceSchema(schema: Schema): schema is ChoiceSchema {
|
||||
return schema.type === SchemaType.Choice;
|
||||
}
|
||||
|
||||
export function isSealedChoiceSchema(schema: Schema): schema is SealedChoiceSchema {
|
||||
return schema.type === SchemaType.SealedChoice;
|
||||
}
|
||||
|
||||
export function isDictionarySchema(schema: Schema): schema is DictionarySchema {
|
||||
return schema.type === SchemaType.Dictionary;
|
||||
}
|
||||
|
||||
export function isResponseSchema(response: Response | SchemaResponse): response is SchemaResponse {
|
||||
return (response as SchemaResponse).schema !== undefined;
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
export function transformValue(value: string | number | boolean) {
|
||||
if (typeof value === "string") {
|
||||
return `"${value}"`;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
emitters:
|
||||
# "@azure-tools/cadl-autorest": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-python" to your package.json to generate Python code
|
||||
# "@azure-tools/cadl-python":
|
||||
# "basic-setup-py": true
|
||||
# "package-version":
|
||||
# "package-name":
|
||||
# "output-path":
|
||||
# Uncomment this line and add "@azure-tools/cadl-java" to your package.json to generate Java code
|
||||
# "@azure-tools/cadl-java": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-csharp" to your package.json to generate C# code
|
||||
# "@azure-tools/cadl-csharp": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-typescript" to your package.json to generate Typescript code
|
||||
# "@azure-tools/cadl-typescript": true
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,29 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "./routes.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
@service({
|
||||
title: "Microsoft Cognitive Language Service - Analyze Text Authoring",
|
||||
})
|
||||
@serviceVersion("2022-05-01")
|
||||
@server(
|
||||
"{Endpoint}/language",
|
||||
"The language service API is a suite of natural language processing (NLP) skills built with best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction, language detection and question answering. Further documentation can be found in <a href=\"https://docs.microsoft.com/en-us/azure/cognitive-services/language-service/overview\">https://docs.microsoft.com/en-us/azure/cognitive-services/language-service/overview</a>.",
|
||||
{
|
||||
@doc("""
|
||||
Supported Cognitive Services endpoint (e.g.,
|
||||
https://<resource-name>.api.cognitiveservices.azure.com).
|
||||
""")
|
||||
Endpoint: string,
|
||||
}
|
||||
)
|
||||
@doc("""
|
||||
The language service API is a suite of natural language processing (NLP) skills
|
||||
built with best-in-class Microsoft machine learning algorithms. The API can be
|
||||
used to analyze unstructured text for tasks such as sentiment analysis, key
|
||||
phrase extraction, language detection and question answering. Further
|
||||
documentation can be found in <a
|
||||
href=\"https://docs.microsoft.com/en-us/azure/cognitive-services/language-service/overview\">https://docs.microsoft.com/en-us/azure/cognitive-services/language-service/overview</a>.
|
||||
""")
|
||||
namespace Azure.Language.Authoring;
|
|
@ -0,0 +1,960 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "@azure-tools/cadl-azure-core";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Azure.Core;
|
||||
|
||||
namespace Azure.Language.Authoring;
|
||||
|
||||
enum ProjectKindKnownValues {
|
||||
"CustomSingleLabelClassification",
|
||||
"CustomMultiLabelClassification",
|
||||
"CustomEntityRecognition",
|
||||
}
|
||||
|
||||
@knownValues(ProjectKindKnownValues)
|
||||
model ProjectKind is string;
|
||||
|
||||
enum ErrorCodeKnownValues {
|
||||
"InvalidRequest",
|
||||
"InvalidArgument",
|
||||
"Unauthorized",
|
||||
"Forbidden",
|
||||
"NotFound",
|
||||
"ProjectNotFound",
|
||||
"OperationNotFound",
|
||||
"AzureCognitiveSearchNotFound",
|
||||
"AzureCognitiveSearchIndexNotFound",
|
||||
"TooManyRequests",
|
||||
"AzureCognitiveSearchThrottling",
|
||||
"AzureCognitiveSearchIndexLimitReached",
|
||||
"InternalServerError",
|
||||
"ServiceUnavailable",
|
||||
"Timeout",
|
||||
"QuotaExceeded",
|
||||
"Conflict",
|
||||
"Warning",
|
||||
}
|
||||
|
||||
@knownValues(ErrorCodeKnownValues)
|
||||
model ErrorCode is string;
|
||||
|
||||
enum InnerErrorCodeKnownValues {
|
||||
"InvalidRequest",
|
||||
"InvalidParameterValue",
|
||||
"KnowledgeBaseNotFound",
|
||||
"AzureCognitiveSearchNotFound",
|
||||
"AzureCognitiveSearchThrottling",
|
||||
"ExtractionFailure",
|
||||
"InvalidRequestBodyFormat",
|
||||
"EmptyRequest",
|
||||
"MissingInputDocuments",
|
||||
"InvalidDocument",
|
||||
"ModelVersionIncorrect",
|
||||
"InvalidDocumentBatch",
|
||||
"UnsupportedLanguageCode",
|
||||
"InvalidCountryHint",
|
||||
}
|
||||
|
||||
@knownValues(InnerErrorCodeKnownValues)
|
||||
model InnerErrorCode is string;
|
||||
|
||||
enum StringIndexTypeKnownValues {
|
||||
"Utf16CodeUnit",
|
||||
}
|
||||
|
||||
@knownValues(StringIndexTypeKnownValues)
|
||||
model StringIndexType is string;
|
||||
|
||||
enum StringIndexTypeAutoGeneratedKnownValues {
|
||||
"Utf16CodeUnit",
|
||||
}
|
||||
|
||||
@knownValues(StringIndexTypeAutoGeneratedKnownValues)
|
||||
model StringIndexTypeAutoGenerated is string;
|
||||
|
||||
enum EvaluationKindKnownValues {
|
||||
Percentage: "percentage",
|
||||
Manual: "manual",
|
||||
}
|
||||
|
||||
@knownValues(EvaluationKindKnownValues)
|
||||
model EvaluationKind is string;
|
||||
|
||||
enum JobStatusKnownValues {
|
||||
NotStarted: "notStarted",
|
||||
Running: "running",
|
||||
Succeeded: "succeeded",
|
||||
Failed: "failed",
|
||||
Cancelled: "cancelled",
|
||||
Cancelling: "cancelling",
|
||||
PartiallyCompleted: "partiallyCompleted",
|
||||
}
|
||||
|
||||
@knownValues(JobStatusKnownValues)
|
||||
model JobStatus is string;
|
||||
|
||||
@doc("Represents a list of retrieved projects' metadata.")
|
||||
model ProjectsMetadata is Azure.Core.Page<ProjectMetadata>;
|
||||
|
||||
@doc("Represents the metadata of a project.")
|
||||
@resource("authoring/analyze-text/projects")
|
||||
model ProjectMetadata {
|
||||
@doc("Represents the project creation datetime.")
|
||||
createdDateTime: zonedDateTime;
|
||||
|
||||
@doc("Represents the project last modification datetime.")
|
||||
lastModifiedDateTime: zonedDateTime;
|
||||
|
||||
@doc("Represents the project last training datetime.")
|
||||
lastTrainedDateTime?: zonedDateTime;
|
||||
|
||||
@doc("Represents the project last deployment datetime.")
|
||||
lastDeployedDateTime?: zonedDateTime;
|
||||
|
||||
@doc("The project kind.")
|
||||
projectKind: ProjectKind;
|
||||
|
||||
@doc("The storage container name.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
storageInputContainerName: string;
|
||||
|
||||
@doc("The project settings.")
|
||||
settings?: object;
|
||||
|
||||
@doc("The new project name.")
|
||||
projectName: string;
|
||||
|
||||
@doc("Whether the project would be used for multiple languages or not.")
|
||||
multilingual?: boolean;
|
||||
|
||||
@doc("The project description.")
|
||||
description?: string;
|
||||
|
||||
@doc("""
|
||||
The project language. This is BCP-47 representation of a language. For example,
|
||||
use \"en\" for English, \"en-gb\" for English (UK), \"es\" for Spanish etc.
|
||||
""")
|
||||
language: string;
|
||||
}
|
||||
|
||||
@doc("Error response.")
|
||||
@error
|
||||
model ErrorResponse {
|
||||
@doc("The error object.")
|
||||
error: Error;
|
||||
}
|
||||
|
||||
@doc("The error object.")
|
||||
model Error {
|
||||
@doc("One of a server-defined set of error codes.")
|
||||
code: ErrorCode;
|
||||
|
||||
@doc("A human-readable representation of the error.")
|
||||
message: string;
|
||||
|
||||
@doc("The target of the error.")
|
||||
target?: string;
|
||||
|
||||
@doc("An array of details about specific errors that led to this reported error.")
|
||||
details?: Error[];
|
||||
|
||||
@doc("""
|
||||
An object containing more specific information than the current object about
|
||||
the error.
|
||||
""")
|
||||
innererror?: InnerErrorModel;
|
||||
}
|
||||
|
||||
@doc("""
|
||||
An object containing more specific information about the error. As per
|
||||
Microsoft One API guidelines -
|
||||
https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses.
|
||||
""")
|
||||
model InnerErrorModel {
|
||||
@doc("One of a server-defined set of error codes.")
|
||||
code: InnerErrorCode;
|
||||
|
||||
@doc("Error message.")
|
||||
message: string;
|
||||
|
||||
@doc("Error details.")
|
||||
details?: Record<string>;
|
||||
|
||||
@doc("Error target.")
|
||||
target?: string;
|
||||
|
||||
@doc("""
|
||||
An object containing more specific information than the current object about
|
||||
the error.
|
||||
""")
|
||||
innererror?: InnerErrorModel;
|
||||
}
|
||||
|
||||
@doc("Represents the options used to create or update a project.")
|
||||
model CreateProjectOptions {
|
||||
@doc("The project kind.")
|
||||
projectKind: ProjectKind;
|
||||
|
||||
@doc("The storage container name.")
|
||||
storageInputContainerName: string;
|
||||
|
||||
@doc("The project settings.")
|
||||
settings?: object;
|
||||
|
||||
@doc("The new project name.")
|
||||
projectName: string;
|
||||
|
||||
@doc("Whether the project would be used for multiple languages or not.")
|
||||
multilingual?: boolean;
|
||||
|
||||
@doc("The project description.")
|
||||
description?: string;
|
||||
|
||||
@doc("""
|
||||
The project language. This is BCP-47 representation of a language. For example,
|
||||
use \"en\" for English, \"en-gb\" for English (UK), \"es\" for Spanish etc.
|
||||
""")
|
||||
language: string;
|
||||
}
|
||||
|
||||
@doc("Represents an exported project.")
|
||||
model ExportedProject {
|
||||
@doc("The version of the exported file.")
|
||||
projectFileVersion: string;
|
||||
|
||||
@doc("""
|
||||
Specifies the method used to interpret string offsets. For additional
|
||||
information see https://aka.ms/text-analytics-offsets.
|
||||
""")
|
||||
stringIndexType: StringIndexTypeAutoGenerated;
|
||||
|
||||
@doc("Represents the project metadata.")
|
||||
metadata: CreateProjectOptions;
|
||||
|
||||
@doc("Represents the project assets.")
|
||||
assets?: ExportedProjectAssets;
|
||||
}
|
||||
|
||||
@doc("Represents the assets of an exported project.")
|
||||
@discriminator("projectKind")
|
||||
model ExportedProjectAssets {}
|
||||
|
||||
@doc("Represents the options for starting a new training job.")
|
||||
model TrainingJobOptions {
|
||||
@doc("Represents the output model label.")
|
||||
modelLabel: string;
|
||||
|
||||
@doc("Represents training config version.")
|
||||
trainingConfigVersion: string;
|
||||
|
||||
@doc("""
|
||||
Represents the evaluation options. By default, the evaluation kind is
|
||||
percentage, with training split percentage as 80, and testing split percentage
|
||||
as 20.
|
||||
""")
|
||||
evaluationOptions?: EvaluationOptions;
|
||||
}
|
||||
|
||||
@doc("Represents the options used running the evaluation.")
|
||||
model EvaluationOptions {
|
||||
@doc("""
|
||||
Represents the evaluation kind. By default, the evaluation kind is set to
|
||||
percentage.
|
||||
""")
|
||||
kind?: EvaluationKind;
|
||||
|
||||
@doc("""
|
||||
Represents the training dataset split percentage. Only needed in case the
|
||||
evaluation kind is percentage.
|
||||
""")
|
||||
trainingSplitPercentage?: int32;
|
||||
|
||||
@doc("""
|
||||
Represents the testing dataset split percentage. Only needed in case the
|
||||
evaluation kind is percentage.
|
||||
""")
|
||||
testingSplitPercentage?: int32;
|
||||
}
|
||||
|
||||
@doc("Represents a list of retrieved deployments.")
|
||||
model ProjectDeployments is Azure.Core.Page<ProjectDeployment>;
|
||||
|
||||
@doc("Represents a project deployment.")
|
||||
@resource("authoring/analyze-text/projects/{projectName}/deployments")
|
||||
model ProjectDeployment {
|
||||
@doc("Represents deployment name.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
deploymentName: string;
|
||||
|
||||
@doc("Represents deployment modelId.")
|
||||
modelId: string;
|
||||
|
||||
@doc("Represents deployment last trained time.")
|
||||
lastTrainedDateTime: zonedDateTime;
|
||||
|
||||
@doc("Represents deployment last deployed time.")
|
||||
lastDeployedDateTime: zonedDateTime;
|
||||
|
||||
@doc("Represents deployment expiration date in the runtime.")
|
||||
deploymentExpirationDate: plainDate;
|
||||
|
||||
@doc("Represents model training config version.")
|
||||
modelTrainingConfigVersion: string;
|
||||
}
|
||||
|
||||
@doc("Represents the options for swapping two deployments together.")
|
||||
model SwapDeploymentsOptions {
|
||||
@doc("Represents the first deployment name.")
|
||||
firstDeploymentName: string;
|
||||
|
||||
@doc("Represents the second deployment name.")
|
||||
secondDeploymentName: string;
|
||||
}
|
||||
|
||||
@doc("Represents the options for creating or updating a project deployment.")
|
||||
model CreateDeploymentOptions {
|
||||
@doc("Represents the trained model label.")
|
||||
trainedModelLabel: string;
|
||||
}
|
||||
|
||||
@doc("Represents the state of a deployment job.")
|
||||
model DeploymentJobState {
|
||||
...JobState;
|
||||
}
|
||||
|
||||
@doc("Represents a job's state.")
|
||||
model JobState {
|
||||
@doc("The job ID.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
jobId: string;
|
||||
|
||||
@doc("The creation date time of the job.")
|
||||
createdDateTime: zonedDateTime;
|
||||
|
||||
@doc("The last date time the job was updated.")
|
||||
lastUpdatedDateTime: zonedDateTime;
|
||||
|
||||
@doc("The expiration date time of the job.")
|
||||
expirationDateTime?: zonedDateTime;
|
||||
|
||||
@doc("The job status.")
|
||||
status: JobStatus;
|
||||
|
||||
@doc("The warnings that were encountered while executing the job.")
|
||||
warnings?: Warning[];
|
||||
|
||||
@doc("The errors encountered while executing the job.")
|
||||
errors?: Error[];
|
||||
}
|
||||
|
||||
@doc("Represents a warning that was encountered while executing the request.")
|
||||
model Warning {
|
||||
@doc("The warning code.")
|
||||
code: string;
|
||||
|
||||
@doc("The warning message.")
|
||||
message: string;
|
||||
}
|
||||
|
||||
@doc("Represents the state of an export job.")
|
||||
model ExportProjectJobState {
|
||||
...JobState;
|
||||
|
||||
@doc("The URL to use in order to download the exported project.")
|
||||
resultUrl?: string;
|
||||
}
|
||||
|
||||
@doc("Represents the state of an import job.")
|
||||
model ImportProjectJobState {
|
||||
...JobState;
|
||||
}
|
||||
|
||||
@doc("Represents a list of retrieved trained models.")
|
||||
model ProjectTrainedModels is Azure.Core.Page<ProjectTrainedModel>;
|
||||
|
||||
@doc("Represents a trained model.")
|
||||
@resource("authoring/analyze-text/projects/{projectName}/models")
|
||||
model ProjectTrainedModel {
|
||||
@doc("The trained model label.")
|
||||
label: string;
|
||||
|
||||
@doc("The model ID.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
modelId: string;
|
||||
|
||||
@doc("The last trained date time of the model.")
|
||||
lastTrainedDateTime: zonedDateTime;
|
||||
|
||||
@doc("The duration of the model's last training request in seconds.")
|
||||
lastTrainingDurationInSeconds: int32;
|
||||
|
||||
@doc("The model expiration date.")
|
||||
modelExpirationDate: plainDate;
|
||||
|
||||
@doc("The model training config version.")
|
||||
modelTrainingConfigVersion: string;
|
||||
}
|
||||
|
||||
@doc("Represents a list of results for an evaluation operation.")
|
||||
model EvaluationResults is Azure.Core.Page<DocumentEvaluationResult>;
|
||||
|
||||
@doc("Represents the evaluation result of a document.")
|
||||
@discriminator("projectKind")
|
||||
model DocumentEvaluationResult {
|
||||
@doc("Represents the document path.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
location: string;
|
||||
|
||||
@doc("""
|
||||
Represents the document language. This is BCP-47 representation of a language.
|
||||
For example, use \"en\" for English, \"en-gb\" for English (UK), \"es\" for
|
||||
Spanish etc.
|
||||
""")
|
||||
language: string;
|
||||
}
|
||||
|
||||
@doc("Represents the summary for an evaluation operation.")
|
||||
@discriminator("projectKind")
|
||||
model EvaluationSummary {
|
||||
@doc("Represents the options used running the evaluation.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
evaluationOptions: EvaluationOptions;
|
||||
}
|
||||
|
||||
@doc("Represents a list of retrieved training jobs.")
|
||||
model TrainingJobs is Azure.Core.Page<TrainingJobState>;
|
||||
|
||||
@doc("Represents the state of a training job.")
|
||||
model TrainingJobState {
|
||||
...JobState;
|
||||
|
||||
@doc("Represents training tasks detailed result.")
|
||||
result: TrainingJobResult;
|
||||
}
|
||||
|
||||
@doc("Represents the output of a training job.")
|
||||
model TrainingJobResult {
|
||||
@doc("Represents trained model label.")
|
||||
modelLabel: string;
|
||||
|
||||
@doc("Represents training config version.")
|
||||
trainingConfigVersion: string;
|
||||
|
||||
@doc("Represents model train status.")
|
||||
trainingStatus: SubTrainingJobState;
|
||||
|
||||
@doc("Represents model evaluation status.")
|
||||
evaluationStatus?: SubTrainingJobState;
|
||||
|
||||
@doc("Represents the estimate end date time for training and evaluation.")
|
||||
estimatedEndDateTime?: zonedDateTime;
|
||||
}
|
||||
|
||||
@doc("Represents the detailed state of a training sub-operation.")
|
||||
model SubTrainingJobState {
|
||||
@doc("Represents progress percentage.")
|
||||
percentComplete: int32;
|
||||
|
||||
@doc("Represents the start date time.")
|
||||
startDateTime?: zonedDateTime;
|
||||
|
||||
@doc("Represents the end date time.")
|
||||
endDateTime?: zonedDateTime;
|
||||
|
||||
@doc("Represents the status of the sub-operation.")
|
||||
status: JobStatus;
|
||||
}
|
||||
|
||||
@doc("Represents the state of a project deletion job.")
|
||||
model ProjectDeletionJobState {
|
||||
...JobState;
|
||||
}
|
||||
|
||||
@doc("Represents a list of retrieved languages.")
|
||||
model SupportedLanguages is Azure.Core.Page<SupportedLanguage>;
|
||||
|
||||
@doc("Represents a supported language.")
|
||||
@resource("authoring/analyze-text/projects/global/languages")
|
||||
model SupportedLanguage {
|
||||
@doc("The language name.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
languageName: string;
|
||||
|
||||
@doc("""
|
||||
The language code. This is BCP-47 representation of a language. For example,
|
||||
\"en\" for English, \"en-gb\" for English (UK), \"es\" for Spanish etc.
|
||||
""")
|
||||
languageCode: string;
|
||||
}
|
||||
|
||||
@doc("Represents a list of training config versions.")
|
||||
model TrainingConfigVersions is Azure.Core.Page<TrainingConfigVersion>;
|
||||
|
||||
@doc("Represents a training config version.")
|
||||
model TrainingConfigVersion {
|
||||
@doc("Represents the version of the config.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
trainingConfigVersion: string;
|
||||
|
||||
@doc("Represents the training config version expiration date.")
|
||||
modelExpirationDate: plainDate;
|
||||
}
|
||||
|
||||
@doc("Represents a cell in a confusion matrix.")
|
||||
model ConfusionMatrixCell {
|
||||
@doc("Represents normalized value in percentages.")
|
||||
normalizedValue: float32;
|
||||
|
||||
@doc("Represents raw value.")
|
||||
rawValue: float32;
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents the document evaluation result for a custom entity recognition
|
||||
project.
|
||||
""")
|
||||
model CustomEntityRecognitionDocumentEvaluationResult
|
||||
extends DocumentEvaluationResult {
|
||||
@doc("Represents the evaluation prediction for entity recognition.")
|
||||
customEntityRecognitionResult: DocumentEntityRecognitionEvaluationResult;
|
||||
|
||||
@doc("Represents the project kind.")
|
||||
projectKind: "CustomEntityRecognition";
|
||||
}
|
||||
|
||||
@doc("Represents the entity recognition evaluation result for a document.")
|
||||
model DocumentEntityRecognitionEvaluationResult {
|
||||
@doc("Represents the document labelled entities.")
|
||||
entities: DocumentEntityRegionEvaluationResult[];
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents the evaluation comparison between the expected and predicted
|
||||
entities of a document region.
|
||||
""")
|
||||
model DocumentEntityRegionEvaluationResult {
|
||||
@doc("Represents the region's expected entity labels.")
|
||||
expectedEntities: DocumentEntityLabelEvaluationResult[];
|
||||
|
||||
@doc("Represents the region's predicted entity labels.")
|
||||
predictedEntities: DocumentEntityLabelEvaluationResult[];
|
||||
|
||||
@doc("Represents the region offset.")
|
||||
regionOffset: int32;
|
||||
|
||||
@doc("Represents the region length.")
|
||||
regionLength: int32;
|
||||
}
|
||||
|
||||
@doc("Represents an evaluation result entity label.")
|
||||
model DocumentEntityLabelEvaluationResult {
|
||||
@doc("Represents the entity category.")
|
||||
category: string;
|
||||
|
||||
@doc("Represents the entity offset index relative to the original text.")
|
||||
offset: int32;
|
||||
|
||||
@doc("Represents the entity length.")
|
||||
length: int32;
|
||||
}
|
||||
|
||||
@doc("Represents the evaluation summary for a custom entity recognition project.")
|
||||
model CustomEntityRecognitionEvaluationSummary extends EvaluationSummary {
|
||||
@doc("Contains the data related to extraction evaluation.")
|
||||
customEntityRecognitionEvaluation: EntityRecognitionEvaluationSummary;
|
||||
|
||||
@doc("Represents the project type that the evaluation ran on.")
|
||||
projectKind: "CustomEntityRecognition";
|
||||
}
|
||||
|
||||
@doc("Represents the evaluation summary for a custom entity recognition project.")
|
||||
model EntityRecognitionEvaluationSummary {
|
||||
@doc("""
|
||||
Represents the confusion matrix between two entities (the two entities can be
|
||||
the same). The matrix is between the entity that was labelled and the entity
|
||||
that was predicted.
|
||||
""")
|
||||
confusionMatrix: Record<Record<ConfusionMatrixCell>>;
|
||||
|
||||
@doc("Represents the entities evaluation")
|
||||
entities: Record<EntityEvaluationSummary>;
|
||||
|
||||
@doc("Represents the micro F1")
|
||||
microF1: float32;
|
||||
|
||||
@doc("Represents the micro precision")
|
||||
microPrecision: float32;
|
||||
|
||||
@doc("Represents the micro recall")
|
||||
microRecall: float32;
|
||||
|
||||
@doc("Represents the macro F1")
|
||||
macroF1: float32;
|
||||
|
||||
@doc("Represents the macro precision")
|
||||
macroPrecision: float32;
|
||||
|
||||
@doc("Represents the macro recall")
|
||||
macroRecall: float32;
|
||||
}
|
||||
|
||||
@doc("Represents the evaluation summary for an entity.")
|
||||
model EntityEvaluationSummary {
|
||||
@doc("Represents the model precision")
|
||||
f1: float32;
|
||||
|
||||
@doc("Represents the model recall")
|
||||
precision: float32;
|
||||
|
||||
@doc("Represents the model F1 score")
|
||||
recall: float32;
|
||||
|
||||
@doc("Represents the count of true positive")
|
||||
truePositiveCount: int32;
|
||||
|
||||
@doc("Represents the count of true negative")
|
||||
trueNegativeCount: int32;
|
||||
|
||||
@doc("Represents the count of false positive")
|
||||
falsePositiveCount: int32;
|
||||
|
||||
@doc("Represents the count of false negative")
|
||||
falseNegativeCount: int32;
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents the document evaluation result for a custom multi-label
|
||||
classification project.
|
||||
""")
|
||||
model CustomMultiLabelClassificationDocumentEvaluationResult
|
||||
extends DocumentEvaluationResult {
|
||||
@doc("Represents the evaluation prediction for multi label classification.")
|
||||
customMultiLabelClassificationResult: DocumentMultiLabelClassificationEvaluationResult;
|
||||
|
||||
@doc("Represents the project kind.")
|
||||
projectKind: "CustomMultiLabelClassification";
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents the comparison between the expected and predicted classes that are
|
||||
result from the evaluation operation.
|
||||
""")
|
||||
model DocumentMultiLabelClassificationEvaluationResult {
|
||||
@doc("Represents the document's expected classes.")
|
||||
expectedClasses: string[];
|
||||
|
||||
@doc("Represents the document's predicted classes.")
|
||||
predictedClasses: string[];
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents the evaluation summary for a custom multi-label classification
|
||||
project.
|
||||
""")
|
||||
model CustomMultiLabelClassificationEvaluationSummary
|
||||
extends EvaluationSummary {
|
||||
@doc("Contains the data related to multi label classification evaluation.")
|
||||
customMultiLabelClassificationEvaluation: MultiLabelClassificationEvaluationSummary;
|
||||
|
||||
@doc("Represents the project type that the evaluation ran on.")
|
||||
projectKind: "CustomMultiLabelClassification";
|
||||
}
|
||||
|
||||
@doc("Represents the evaluation summary for a multi-label classification project.")
|
||||
model MultiLabelClassificationEvaluationSummary {
|
||||
@doc("Represents the classes evaluation")
|
||||
classes: Record<MultiLabelClassEvaluationSummary>;
|
||||
|
||||
@doc("Represents the micro F1")
|
||||
microF1: float32;
|
||||
|
||||
@doc("Represents the micro precision")
|
||||
microPrecision: float32;
|
||||
|
||||
@doc("Represents the micro recall")
|
||||
microRecall: float32;
|
||||
|
||||
@doc("Represents the macro F1")
|
||||
macroF1: float32;
|
||||
|
||||
@doc("Represents the macro precision")
|
||||
macroPrecision: float32;
|
||||
|
||||
@doc("Represents the macro recall")
|
||||
macroRecall: float32;
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents the evaluation summary of a class in a multi-label classification
|
||||
project.
|
||||
""")
|
||||
model MultiLabelClassEvaluationSummary {
|
||||
@doc("Represents the model precision")
|
||||
f1: float32;
|
||||
|
||||
@doc("Represents the model recall")
|
||||
precision: float32;
|
||||
|
||||
@doc("Represents the model F1 score")
|
||||
recall: float32;
|
||||
|
||||
@doc("Represents the count of true positive")
|
||||
truePositiveCount: int32;
|
||||
|
||||
@doc("Represents the count of true negative")
|
||||
trueNegativeCount: int32;
|
||||
|
||||
@doc("Represents the count of false positive")
|
||||
falsePositiveCount: int32;
|
||||
|
||||
@doc("Represents the count of false negative")
|
||||
falseNegativeCount: int32;
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents the document evaluation result for a custom single-label
|
||||
classification project.
|
||||
""")
|
||||
model CustomSingleLabelClassificationDocumentEvaluationResult
|
||||
extends DocumentEvaluationResult {
|
||||
@doc("Represents the evaluation prediction for single label classification.")
|
||||
customSingleLabelClassificationResult: DocumentSingleLabelClassificationEvaluationResult;
|
||||
|
||||
@doc("Represents the project kind.")
|
||||
projectKind: "CustomSingleLabelClassification";
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents the comparison between the expected and predicted class that result
|
||||
from an evaluation operation.
|
||||
""")
|
||||
model DocumentSingleLabelClassificationEvaluationResult {
|
||||
@doc("Represents the document's expected class.")
|
||||
expectedClass: string;
|
||||
|
||||
@doc("Represents the document's predicted class.")
|
||||
predictedClass: string;
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents the evaluation summary for a custom single-label classification
|
||||
project.
|
||||
""")
|
||||
model CustomSingleLabelClassificationEvaluationSummary
|
||||
extends EvaluationSummary {
|
||||
@doc("Contains the data related to single label classification evaluation.")
|
||||
customSingleLabelClassificationEvaluation: SingleLabelClassificationEvaluationSummary;
|
||||
|
||||
@doc("Represents the project type that the evaluation ran on.")
|
||||
projectKind: "CustomSingleLabelClassification";
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents the evaluation summary for a custom single-label classification
|
||||
project.
|
||||
""")
|
||||
model SingleLabelClassificationEvaluationSummary {
|
||||
@doc("""
|
||||
Represents the confusion matrix between two classes (the two classes can be the
|
||||
same). The matrix is between the class that was labelled and the class that was
|
||||
predicted.
|
||||
""")
|
||||
confusionMatrix: Record<Record<ConfusionMatrixCell>>;
|
||||
|
||||
@doc("Represents the classes evaluation")
|
||||
classes: Record<SingleLabelClassEvaluationSummary>;
|
||||
|
||||
@doc("Represents the micro F1")
|
||||
microF1: float32;
|
||||
|
||||
@doc("Represents the micro precision")
|
||||
microPrecision: float32;
|
||||
|
||||
@doc("Represents the micro recall")
|
||||
microRecall: float32;
|
||||
|
||||
@doc("Represents the macro F1")
|
||||
macroF1: float32;
|
||||
|
||||
@doc("Represents the macro precision")
|
||||
macroPrecision: float32;
|
||||
|
||||
@doc("Represents the macro recall")
|
||||
macroRecall: float32;
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents the evaluation summary for a class in a single-label classification
|
||||
project.
|
||||
""")
|
||||
model SingleLabelClassEvaluationSummary {
|
||||
@doc("Represents the model precision")
|
||||
f1: float32;
|
||||
|
||||
@doc("Represents the model recall")
|
||||
precision: float32;
|
||||
|
||||
@doc("Represents the model F1 score")
|
||||
recall: float32;
|
||||
|
||||
@doc("Represents the count of true positive")
|
||||
truePositiveCount: int32;
|
||||
|
||||
@doc("Represents the count of true negative")
|
||||
trueNegativeCount: int32;
|
||||
|
||||
@doc("Represents the count of false positive")
|
||||
falsePositiveCount: int32;
|
||||
|
||||
@doc("Represents the count of false negative")
|
||||
falseNegativeCount: int32;
|
||||
}
|
||||
|
||||
@doc("Represents a class of an exported project.")
|
||||
model ExportedClass {
|
||||
@doc("The class category.")
|
||||
category?: string;
|
||||
}
|
||||
|
||||
@doc("Represents an exported document for a custom entity recognition project.")
|
||||
model ExportedCustomEntityRecognitionDocument {
|
||||
@doc("The list of entity labels belonging to the document.")
|
||||
entities?: ExportedDocumentRegion[];
|
||||
|
||||
@doc("The location of the document in the storage.")
|
||||
location?: string;
|
||||
|
||||
@doc("""
|
||||
Represents the document language. This is BCP-47 representation of a language.
|
||||
For example, use \"en\" for English, \"en-gb\" for English (UK), \"es\" for
|
||||
Spanish etc.
|
||||
""")
|
||||
language?: string;
|
||||
|
||||
@doc("The dataset for this document. Allowed values are 'Train' and 'Test'.")
|
||||
dataset?: string;
|
||||
}
|
||||
|
||||
@doc("Represents a region in a document for entity labeling.")
|
||||
model ExportedDocumentRegion {
|
||||
@doc("Start position for the region.")
|
||||
regionOffset?: int32;
|
||||
|
||||
@doc("Length for the region text.")
|
||||
regionLength?: int32;
|
||||
|
||||
@doc("The list of entity labels belonging to this region.")
|
||||
labels?: ExportedDocumentEntityLabel[];
|
||||
}
|
||||
|
||||
@doc("Represents an entity label for a document.")
|
||||
model ExportedDocumentEntityLabel {
|
||||
@doc("The entity category.")
|
||||
category?: string;
|
||||
|
||||
@doc("Start position for the entity text.")
|
||||
offset?: int32;
|
||||
|
||||
@doc("Length for the entity text.")
|
||||
length?: int32;
|
||||
}
|
||||
|
||||
@doc("Represents the exported assets for a entity recognition project.")
|
||||
model ExportedCustomEntityRecognitionProjectAssets
|
||||
extends ExportedProjectAssets {
|
||||
@doc("The list of entities belonging to the project.")
|
||||
entities?: ExportedEntity[];
|
||||
|
||||
@doc("The list of documents belonging to the project.")
|
||||
documents?: ExportedCustomEntityRecognitionDocument[];
|
||||
|
||||
@doc("The type of the project the assets belong to.")
|
||||
projectKind: "CustomEntityRecognition";
|
||||
}
|
||||
|
||||
@doc("Represents an entity in an exported project.")
|
||||
model ExportedEntity {
|
||||
@doc("The entity category.")
|
||||
category?: string;
|
||||
}
|
||||
|
||||
@doc("Represents an exported document of a custom multi-label classification project.")
|
||||
model ExportedCustomMultiLabelClassificationDocument {
|
||||
@doc("The document classes.")
|
||||
classes?: ExportedDocumentClass[];
|
||||
|
||||
@doc("The location of the document in the storage.")
|
||||
location?: string;
|
||||
|
||||
@doc("""
|
||||
Represents the document language. This is BCP-47 representation of a language.
|
||||
For example, use \"en\" for English, \"en-gb\" for English (UK), \"es\" for
|
||||
Spanish etc.
|
||||
""")
|
||||
language?: string;
|
||||
|
||||
@doc("The dataset for this document. Allowed values are 'Train' and 'Test'.")
|
||||
dataset?: string;
|
||||
}
|
||||
|
||||
@doc("Represents a classification label for a document.")
|
||||
model ExportedDocumentClass {
|
||||
category?: string;
|
||||
}
|
||||
|
||||
@doc("Represents the exported assets for a custom multi-label classification project.")
|
||||
model ExportedCustomMultiLabelClassificationProjectAssets
|
||||
extends ExportedProjectAssets {
|
||||
@doc("The list of classes in the project.")
|
||||
classes?: ExportedClass[];
|
||||
|
||||
@doc("The list of documents in the project.")
|
||||
documents?: ExportedCustomMultiLabelClassificationDocument[];
|
||||
|
||||
@doc("The type of the project the assets belong to.")
|
||||
projectKind: "CustomMultiLabelClassification";
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Represents an exported document for a custom single-label classification
|
||||
project.
|
||||
""")
|
||||
model ExportedCustomSingleLabelClassificationDocument {
|
||||
@doc("The class of the documents.")
|
||||
class?: ExportedDocumentClass;
|
||||
|
||||
@doc("The location of the document in the storage.")
|
||||
location?: string;
|
||||
|
||||
@doc("""
|
||||
Represents the document language. This is BCP-47 representation of a language.
|
||||
For example, use \"en\" for English, \"en-gb\" for English (UK), \"es\" for
|
||||
Spanish etc.
|
||||
""")
|
||||
language?: string;
|
||||
|
||||
@doc("The dataset for this document. Allowed values are 'Train' and 'Test'.")
|
||||
dataset?: string;
|
||||
}
|
||||
|
||||
@doc("Represents the exported assets for a single-label classification project.")
|
||||
model ExportedCustomSingleLabelClassificationProjectAssets
|
||||
extends ExportedProjectAssets {
|
||||
@doc("The list of classes belonging to this project.")
|
||||
classes?: ExportedClass[];
|
||||
|
||||
@doc("The list of documents belonging to this project.")
|
||||
documents?: ExportedCustomSingleLabelClassificationDocument[];
|
||||
|
||||
@doc("The type of the project the assets belong to.")
|
||||
projectKind: "CustomSingleLabelClassification";
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"name": "@cadl-api-spec/microsoft-cognitive-language-service---analyze-text-authoring",
|
||||
"author": "Microsoft Corporation",
|
||||
"description": "The language service API is a suite of natural language processing (NLP) skills built with best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction, language detection and question answering. Further documentation can be found in <a href=\"https://docs.microsoft.com/en-us/azure/cognitive-services/language-service/overview\">https://docs.microsoft.com/en-us/azure/cognitive-services/language-service/overview</a>.",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cadl-lang/compiler": "^0.37.0",
|
||||
"@cadl-lang/rest": "^0.19.0",
|
||||
"@cadl-lang/versioning": "^0.10.0",
|
||||
"@cadl-lang/prettier-plugin-cadl": "^0.5.17",
|
||||
"@azure-tools/cadl-azure-core": "^0.9.0",
|
||||
"@azure-tools/cadl-autorest": "^0.22.0",
|
||||
"@azure-tools/cadl-python": "^0.4.10",
|
||||
"prettier": "^2.7.1"
|
||||
},
|
||||
"private": true
|
||||
}
|
|
@ -0,0 +1,408 @@
|
|||
import "@azure-tools/cadl-azure-core";
|
||||
import "@cadl-lang/rest";
|
||||
import "./models.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
|
||||
namespace Azure.Language.Authoring;
|
||||
|
||||
interface TextAnalysisAuthoringOperations {
|
||||
@doc("Lists the existing projects.")
|
||||
ListProjects is Azure.Core.ResourceList<
|
||||
ProjectMetadata,
|
||||
{
|
||||
parameters: {
|
||||
@doc("The maximum number of resources to return from the collection.")
|
||||
@query
|
||||
top: int32;
|
||||
|
||||
@doc("An offset into the collection of the first resource to be returned.")
|
||||
@query
|
||||
skip: int32;
|
||||
|
||||
@doc("The maximum number of resources to include in a single response.")
|
||||
@query
|
||||
maxpagesize: int32;
|
||||
};
|
||||
}
|
||||
>;
|
||||
|
||||
@doc("Creates a new project or updates an existing one.")
|
||||
CreateProject is Azure.Core.ResourceCreateOrUpdate<ProjectMetadata>;
|
||||
|
||||
@doc("Gets the details of a project.")
|
||||
GetProject is Azure.Core.ResourceRead<ProjectMetadata>;
|
||||
|
||||
@doc("Deletes a project.")
|
||||
DeleteProject is Azure.Core.LongRunningResourceDelete<ProjectMetadata>;
|
||||
|
||||
@doc("Triggers a job to export a project's data.")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/:export")
|
||||
@post
|
||||
Export is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("""
|
||||
Specifies the method used to interpret string offsets. For additional
|
||||
information see https://aka.ms/text-analytics-offsets.
|
||||
""")
|
||||
@query
|
||||
stringIndexType: StringIndexType;
|
||||
|
||||
@doc("Kind of asset to export.")
|
||||
@query
|
||||
assetKind: string;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("""
|
||||
Triggers a job to import a project. If a project with the same name already
|
||||
exists, the data of that project is replaced.
|
||||
""")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/:import")
|
||||
@post
|
||||
Import is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The project data to import.")
|
||||
@body
|
||||
body: ExportedProject;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Triggers a training job for a project.")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/:train")
|
||||
@post
|
||||
Train is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The training input parameters.")
|
||||
@body
|
||||
body: TrainingJobOptions;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Lists the deployments belonging to a project.")
|
||||
ListDeployments is Azure.Core.ResourceList<
|
||||
ProjectDeployment,
|
||||
{
|
||||
parameters: {
|
||||
@doc("The maximum number of resources to return from the collection.")
|
||||
@query
|
||||
top: int32;
|
||||
|
||||
@doc("An offset into the collection of the first resource to be returned.")
|
||||
@query
|
||||
skip: int32;
|
||||
|
||||
@doc("The maximum number of resources to include in a single response.")
|
||||
@query
|
||||
maxpagesize: int32;
|
||||
};
|
||||
}
|
||||
>;
|
||||
|
||||
@doc("Swaps two existing deployments with each other.")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/deployments/:swap")
|
||||
@post
|
||||
SwapDeployments is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The job object to swap two deployments.")
|
||||
@body
|
||||
body: SwapDeploymentsOptions;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Gets the details of a deployment.")
|
||||
GetDeployment is Azure.Core.ResourceRead<ProjectDeployment>;
|
||||
|
||||
@doc("Creates a new deployment or replaces an existing one.")
|
||||
DeployProject is Azure.Core.LongRunningResourceCreateOrReplace<ProjectDeployment>;
|
||||
|
||||
@doc("Deletes a project deployment.")
|
||||
DeleteDeployment is Azure.Core.LongRunningResourceDelete<ProjectDeployment>;
|
||||
|
||||
@doc("Gets the status of an existing deployment job.")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/deployments/{deploymentName}/jobs/{jobId}")
|
||||
@get
|
||||
GetDeploymentStatus is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The name of the specific deployment of the project to use.")
|
||||
@path
|
||||
deploymentName: string;
|
||||
|
||||
@doc("The job ID.")
|
||||
@path
|
||||
jobId: string;
|
||||
},
|
||||
DeploymentJobState
|
||||
>;
|
||||
|
||||
@doc("Gets the status of an existing swap deployment job.")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/deployments/swap/jobs/{jobId}")
|
||||
@get
|
||||
GetSwapDeploymentsStatus is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The job ID.")
|
||||
@path
|
||||
jobId: string;
|
||||
},
|
||||
DeploymentJobState
|
||||
>;
|
||||
|
||||
@doc("""
|
||||
Gets the status of an export job. Once job completes, returns the project
|
||||
metadata, and assets.
|
||||
""")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/export/jobs/{jobId}")
|
||||
@get
|
||||
GetExportStatus is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The job ID.")
|
||||
@path
|
||||
jobId: string;
|
||||
},
|
||||
ExportProjectJobState
|
||||
>;
|
||||
|
||||
@doc("Gets the status for an import.")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/import/jobs/{jobId}")
|
||||
@get
|
||||
GetImportStatus is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The job ID.")
|
||||
@path
|
||||
jobId: string;
|
||||
},
|
||||
ImportProjectJobState
|
||||
>;
|
||||
|
||||
@doc("Lists the trained models belonging to a project.")
|
||||
ListTrainedModels is Azure.Core.ResourceList<
|
||||
ProjectTrainedModel,
|
||||
{
|
||||
parameters: {
|
||||
@doc("The maximum number of resources to return from the collection.")
|
||||
@query
|
||||
top: int32;
|
||||
|
||||
@doc("An offset into the collection of the first resource to be returned.")
|
||||
@query
|
||||
skip: int32;
|
||||
|
||||
@doc("The maximum number of resources to include in a single response.")
|
||||
@query
|
||||
maxpagesize: int32;
|
||||
};
|
||||
}
|
||||
>;
|
||||
|
||||
@doc("Gets the details of a trained model.")
|
||||
GetTrainedModel is Azure.Core.ResourceRead<ProjectTrainedModel>;
|
||||
|
||||
@doc("Deletes an existing trained model.")
|
||||
DeleteTrainedModel is Azure.Core.ResourceDelete<ProjectTrainedModel>;
|
||||
|
||||
@doc("""
|
||||
Gets the detailed results of the evaluation for a trained model. This includes
|
||||
the raw inference results for the data included in the evaluation process.
|
||||
""")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/models/{trainedModelLabel}/evaluation/result")
|
||||
@get
|
||||
GetModelEvaluationResults is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The trained model label.")
|
||||
@path
|
||||
trainedModelLabel: string;
|
||||
|
||||
@doc("""
|
||||
Specifies the method used to interpret string offsets. For additional
|
||||
information see https://aka.ms/text-analytics-offsets.
|
||||
""")
|
||||
@query
|
||||
stringIndexType: StringIndexType;
|
||||
|
||||
@doc("The maximum number of resources to return from the collection.")
|
||||
@query
|
||||
top: int32;
|
||||
|
||||
@doc("An offset into the collection of the first resource to be returned.")
|
||||
@query
|
||||
skip: int32;
|
||||
|
||||
@doc("The maximum number of resources to include in a single response.")
|
||||
@query
|
||||
maxpagesize: int32;
|
||||
},
|
||||
EvaluationResults
|
||||
>;
|
||||
|
||||
@doc("""
|
||||
Gets the evaluation summary of a trained model. The summary includes high level
|
||||
performance measurements of the model e.g., F1, Precision, Recall, etc.
|
||||
""")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/models/{trainedModelLabel}/evaluation/summary-result")
|
||||
@get
|
||||
GetModelEvaluationSummary is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The trained model label.")
|
||||
@path
|
||||
trainedModelLabel: string;
|
||||
},
|
||||
EvaluationSummary
|
||||
>;
|
||||
|
||||
@doc("Lists the non-expired training jobs created for a project.")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/train/jobs")
|
||||
@get
|
||||
ListTrainingJobs is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The maximum number of resources to return from the collection.")
|
||||
@query
|
||||
top: int32;
|
||||
|
||||
@doc("An offset into the collection of the first resource to be returned.")
|
||||
@query
|
||||
skip: int32;
|
||||
|
||||
@doc("The maximum number of resources to include in a single response.")
|
||||
@query
|
||||
maxpagesize: int32;
|
||||
},
|
||||
TrainingJobs
|
||||
>;
|
||||
|
||||
@doc("Gets the status for a training job.")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/train/jobs/{jobId}")
|
||||
@get
|
||||
GetTrainingStatus is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The job ID.")
|
||||
@path
|
||||
jobId: string;
|
||||
},
|
||||
TrainingJobState
|
||||
>;
|
||||
|
||||
@doc("Triggers a cancellation for a running training job.")
|
||||
@route("/authoring/analyze-text/projects/{projectName}/train/jobs/{jobId}/:cancel")
|
||||
@post
|
||||
CancelTrainingJob is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The name of the project to use.")
|
||||
@path
|
||||
projectName: string;
|
||||
|
||||
@doc("The job ID.")
|
||||
@path
|
||||
jobId: string;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Gets the status for a project deletion job.")
|
||||
@route("/authoring/analyze-text/projects/global/deletion-jobs/{jobId}")
|
||||
@get
|
||||
GetProjectDeletionStatus is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The job ID.")
|
||||
@path
|
||||
jobId: string;
|
||||
},
|
||||
ProjectDeletionJobState
|
||||
>;
|
||||
|
||||
@doc("Lists the supported languages.")
|
||||
GetSupportedLanguages is Azure.Core.ResourceList<
|
||||
SupportedLanguage,
|
||||
{
|
||||
parameters: {
|
||||
@doc("The maximum number of resources to return from the collection.")
|
||||
@query
|
||||
top: int32;
|
||||
|
||||
@doc("An offset into the collection of the first resource to be returned.")
|
||||
@query
|
||||
skip: int32;
|
||||
|
||||
@doc("The maximum number of resources to include in a single response.")
|
||||
@query
|
||||
maxpagesize: int32;
|
||||
};
|
||||
}
|
||||
>;
|
||||
|
||||
@doc("Lists the support training config version for a given project type.")
|
||||
@route("/authoring/analyze-text/projects/global/training-config-versions")
|
||||
@get
|
||||
ListTrainingConfigVersions is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The project kind.")
|
||||
@query
|
||||
projectKind: ProjectKind;
|
||||
|
||||
@doc("The maximum number of resources to return from the collection.")
|
||||
@query
|
||||
top: int32;
|
||||
|
||||
@doc("An offset into the collection of the first resource to be returned.")
|
||||
@query
|
||||
skip: int32;
|
||||
|
||||
@doc("The maximum number of resources to include in a single response.")
|
||||
@query
|
||||
maxpagesize: int32;
|
||||
},
|
||||
TrainingConfigVersions
|
||||
>;
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
```yaml
|
||||
input-file:
|
||||
- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/cognitiveservices/data-plane/Language/stable/2022-05-01/analyzetext-authoring.json
|
||||
title: Microsoft Cognitive Language Service - Analyze Text Authoring
|
||||
clear-output-folder: false
|
||||
guessResourceKey: true
|
||||
isAzureSpec: true
|
||||
namespace: "Azure.Language.Authoring"
|
||||
modelerfour:
|
||||
lenient-model-deduplication: true
|
||||
```
|
|
@ -0,0 +1,14 @@
|
|||
emitters:
|
||||
# "@azure-tools/cadl-autorest": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-python" to your package.json to generate Python code
|
||||
# "@azure-tools/cadl-python":
|
||||
# "basic-setup-py": true
|
||||
# "package-version":
|
||||
# "package-name":
|
||||
# "output-path":
|
||||
# Uncomment this line and add "@azure-tools/cadl-java" to your package.json to generate Java code
|
||||
# "@azure-tools/cadl-java": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-csharp" to your package.json to generate C# code
|
||||
# "@azure-tools/cadl-csharp": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-typescript" to your package.json to generate Typescript code
|
||||
# "@azure-tools/cadl-typescript": true
|
|
@ -0,0 +1,44 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "./routes.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
@service({
|
||||
title: "Anomaly Detector Client",
|
||||
})
|
||||
@server(
|
||||
"{Endpoint}/anomalydetector/{ApiVersion}",
|
||||
"The Anomaly Detector API detects anomalies automatically in time series data. It supports two kinds of mode, one is for stateless using, another is for stateful using. In stateless mode, there are three functionalities. Entire Detect is for detecting the whole series with model trained by the time series, Last Detect is detecting last point with model trained by points before. ChangePoint Detect is for detecting trend changes in time series. In stateful mode, user can store time series, the stored time series will be used for detection anomalies. Under this mode, user can still use the above three functionalities by only giving a time range without preparing time series in client side. Besides the above three functionalities, stateful model also provide group based detection and labeling service. By leveraging labeling service user can provide labels for each detection result, these labels will be used for retuning or regenerating detection models. Inconsistency detection is a kind of group based detection, this detection will find inconsistency ones in a set of time series. By using anomaly detector service, business customers can discover incidents and establish a logic flow for root cause analysis.",
|
||||
{
|
||||
@doc("""
|
||||
Supported Cognitive Services endpoints (protocol and hostname, for example:
|
||||
https://westus2.api.cognitive.microsoft.com).
|
||||
""")
|
||||
Endpoint: string,
|
||||
|
||||
@doc("Anomaly Detector API version (for example, v1.0).")
|
||||
ApiVersion: string,
|
||||
|
||||
@doc("server parameter")
|
||||
$host: string,
|
||||
}
|
||||
)
|
||||
@doc("""
|
||||
The Anomaly Detector API detects anomalies automatically in time series data.
|
||||
It supports two kinds of mode, one is for stateless using, another is for
|
||||
stateful using. In stateless mode, there are three functionalities. Entire
|
||||
Detect is for detecting the whole series with model trained by the time series,
|
||||
Last Detect is detecting last point with model trained by points before.
|
||||
ChangePoint Detect is for detecting trend changes in time series. In stateful
|
||||
mode, user can store time series, the stored time series will be used for
|
||||
detection anomalies. Under this mode, user can still use the above three
|
||||
functionalities by only giving a time range without preparing time series in
|
||||
client side. Besides the above three functionalities, stateful model also
|
||||
provide group based detection and labeling service. By leveraging labeling
|
||||
service user can provide labels for each detection result, these labels will be
|
||||
used for retuning or regenerating detection models. Inconsistency detection is
|
||||
a kind of group based detection, this detection will find inconsistency ones in
|
||||
a set of time series. By using anomaly detector service, business customers can
|
||||
discover incidents and establish a logic flow for root cause analysis.
|
||||
""")
|
||||
namespace AnomalyDetectorClient;
|
|
@ -0,0 +1,622 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "@azure-tools/cadl-azure-core";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Azure.Core;
|
||||
|
||||
namespace AnomalyDetectorClient;
|
||||
|
||||
enum ApiVersionKnownValues {
|
||||
V11Preview1: "v1.1-preview.1",
|
||||
}
|
||||
|
||||
@knownValues(ApiVersionKnownValues)
|
||||
model ApiVersion is string;
|
||||
|
||||
enum ImputeModeKnownValues {
|
||||
Auto: "auto",
|
||||
Previous: "previous",
|
||||
Linear: "linear",
|
||||
Fixed: "fixed",
|
||||
Zero: "zero",
|
||||
NotFill: "notFill",
|
||||
}
|
||||
|
||||
@knownValues(ImputeModeKnownValues)
|
||||
model ImputeMode is string;
|
||||
|
||||
enum AnomalyDetectorErrorCodesKnownValues {
|
||||
"InvalidCustomInterval",
|
||||
"BadArgument",
|
||||
"InvalidGranularity",
|
||||
"InvalidPeriod",
|
||||
"InvalidModelArgument",
|
||||
"InvalidSeries",
|
||||
"InvalidJsonFormat",
|
||||
"RequiredGranularity",
|
||||
"RequiredSeries",
|
||||
"InvalidImputeMode",
|
||||
"InvalidImputeFixedValue",
|
||||
}
|
||||
|
||||
@knownValues(AnomalyDetectorErrorCodesKnownValues)
|
||||
model AnomalyDetectorErrorCodes is string;
|
||||
|
||||
enum FillNAMethodKnownValues {
|
||||
"Previous",
|
||||
"Subsequent",
|
||||
"Linear",
|
||||
"Zero",
|
||||
"Fixed",
|
||||
"NotFill",
|
||||
}
|
||||
|
||||
@knownValues(FillNAMethodKnownValues)
|
||||
model FillNAMethod is string;
|
||||
|
||||
enum TimeGranularity {
|
||||
Yearly: "yearly",
|
||||
Monthly: "monthly",
|
||||
Weekly: "weekly",
|
||||
Daily: "daily",
|
||||
Hourly: "hourly",
|
||||
PerMinute: "minutely",
|
||||
PerSecond: "secondly",
|
||||
Microsecond: "microsecond",
|
||||
None: "none",
|
||||
}
|
||||
|
||||
enum DetectionStatus {
|
||||
Created: "CREATED",
|
||||
Running: "RUNNING",
|
||||
Ready: "READY",
|
||||
Failed: "FAILED",
|
||||
}
|
||||
|
||||
enum DataSchema {
|
||||
"OneTable",
|
||||
"MultiTable",
|
||||
}
|
||||
|
||||
enum AlignMode {
|
||||
"Inner",
|
||||
"Outer",
|
||||
}
|
||||
|
||||
enum ModelStatus {
|
||||
Created: "CREATED",
|
||||
Running: "RUNNING",
|
||||
Ready: "READY",
|
||||
Failed: "FAILED",
|
||||
}
|
||||
|
||||
@doc("The request of entire or last anomaly detection.")
|
||||
model DetectRequest {
|
||||
@doc("""
|
||||
Time series data points. Points should be sorted by timestamp in ascending
|
||||
order to match the anomaly detection result. If the data is not sorted
|
||||
correctly or there is duplicated timestamp, the API will not work. In such
|
||||
case, an error message will be returned.
|
||||
""")
|
||||
series: TimeSeriesPoint[];
|
||||
|
||||
@doc("""
|
||||
Optional argument, can be one of yearly, monthly, weekly, daily, hourly,
|
||||
minutely, secondly, microsecond or none. If granularity is not present, it will
|
||||
be none by default. If granularity is none, the timestamp property in time
|
||||
series point can be absent.
|
||||
""")
|
||||
granularity?: TimeGranularity;
|
||||
|
||||
@doc("""
|
||||
Custom Interval is used to set non-standard time interval, for example, if the
|
||||
series is 5 minutes, request can be set as {\"granularity\":\"minutely\",
|
||||
\"customInterval\":5}.
|
||||
""")
|
||||
customInterval?: int32;
|
||||
|
||||
@doc("""
|
||||
Optional argument, periodic value of a time series. If the value is null or
|
||||
does not present, the API will determine the period automatically.
|
||||
""")
|
||||
period?: int32;
|
||||
|
||||
@doc("Optional argument, advanced model parameter, max anomaly ratio in a time series.")
|
||||
maxAnomalyRatio?: float32;
|
||||
|
||||
@doc("""
|
||||
Optional argument, advanced model parameter, between 0-99, the lower the value
|
||||
is, the larger the margin value will be which means less anomalies will be
|
||||
accepted.
|
||||
""")
|
||||
sensitivity?: int32;
|
||||
|
||||
@doc("""
|
||||
Used to specify how to deal with missing values in the input series, it's used
|
||||
when granularity is not \"none\".
|
||||
""")
|
||||
imputeMode?: ImputeMode;
|
||||
|
||||
@doc("""
|
||||
Used to specify the value to fill, it's used when granularity is not \"none\"
|
||||
and imputeMode is \"fixed\".
|
||||
""")
|
||||
imputeFixedValue?: float32;
|
||||
}
|
||||
|
||||
@doc("The definition of input timeseries points.")
|
||||
model TimeSeriesPoint {
|
||||
@doc("Optional argument, timestamp of a data point (ISO8601 format).")
|
||||
timestamp?: zonedDateTime;
|
||||
|
||||
@doc("The measurement of that point, should be float.")
|
||||
value: float32;
|
||||
}
|
||||
|
||||
@doc("The response of entire anomaly detection.")
|
||||
model EntireDetectResponse {
|
||||
@doc("""
|
||||
Frequency extracted from the series, zero means no recurrent pattern has been
|
||||
found.
|
||||
""")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
period: int32;
|
||||
|
||||
@doc("""
|
||||
ExpectedValues contain expected value for each input point. The index of the
|
||||
array is consistent with the input series.
|
||||
""")
|
||||
expectedValues: float32[];
|
||||
|
||||
@doc("""
|
||||
UpperMargins contain upper margin of each input point. UpperMargin is used to
|
||||
calculate upperBoundary, which equals to expectedValue + (100 -
|
||||
marginScale)*upperMargin. Anomalies in response can be filtered by
|
||||
upperBoundary and lowerBoundary. By adjusting marginScale value, less
|
||||
significant anomalies can be filtered in client side. The index of the array is
|
||||
consistent with the input series.
|
||||
""")
|
||||
upperMargins: float32[];
|
||||
|
||||
@doc("""
|
||||
LowerMargins contain lower margin of each input point. LowerMargin is used to
|
||||
calculate lowerBoundary, which equals to expectedValue - (100 -
|
||||
marginScale)*lowerMargin. Points between the boundary can be marked as normal
|
||||
ones in client side. The index of the array is consistent with the input
|
||||
series.
|
||||
""")
|
||||
lowerMargins: float32[];
|
||||
|
||||
@doc("""
|
||||
IsAnomaly contains anomaly properties for each input point. True means an
|
||||
anomaly either negative or positive has been detected. The index of the array
|
||||
is consistent with the input series.
|
||||
""")
|
||||
isAnomaly: boolean[];
|
||||
|
||||
@doc("""
|
||||
IsNegativeAnomaly contains anomaly status in negative direction for each input
|
||||
point. True means a negative anomaly has been detected. A negative anomaly
|
||||
means the point is detected as an anomaly and its real value is smaller than
|
||||
the expected one. The index of the array is consistent with the input series.
|
||||
""")
|
||||
isNegativeAnomaly: boolean[];
|
||||
|
||||
@doc("""
|
||||
IsPositiveAnomaly contain anomaly status in positive direction for each input
|
||||
point. True means a positive anomaly has been detected. A positive anomaly
|
||||
means the point is detected as an anomaly and its real value is larger than the
|
||||
expected one. The index of the array is consistent with the input series.
|
||||
""")
|
||||
isPositiveAnomaly: boolean[];
|
||||
|
||||
@doc("""
|
||||
The severity score for each input point. The larger the value is, the more
|
||||
sever the anomaly is. For normal points, the \"severity\" is always 0.
|
||||
""")
|
||||
severity?: float32[];
|
||||
}
|
||||
|
||||
@doc("Error information returned by the API.")
|
||||
@error
|
||||
model AnomalyDetectorError {
|
||||
@doc("The error code.")
|
||||
code?: AnomalyDetectorErrorCodes;
|
||||
|
||||
@doc("A message explaining the error reported by the service.")
|
||||
message?: string;
|
||||
}
|
||||
|
||||
@doc("The response of last anomaly detection.")
|
||||
model LastDetectResponse {
|
||||
@doc("""
|
||||
Frequency extracted from the series, zero means no recurrent pattern has been
|
||||
found.
|
||||
""")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
period: int32;
|
||||
|
||||
@doc("Suggested input series points needed for detecting the latest point.")
|
||||
suggestedWindow: int32;
|
||||
|
||||
@doc("Expected value of the latest point.")
|
||||
expectedValue: float32;
|
||||
|
||||
@doc("""
|
||||
Upper margin of the latest point. UpperMargin is used to calculate
|
||||
upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin.
|
||||
If the value of latest point is between upperBoundary and lowerBoundary, it
|
||||
should be treated as normal value. By adjusting marginScale value, anomaly
|
||||
status of latest point can be changed.
|
||||
""")
|
||||
upperMargin: float32;
|
||||
|
||||
@doc("""
|
||||
Lower margin of the latest point. LowerMargin is used to calculate
|
||||
lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin.
|
||||
|
||||
""")
|
||||
lowerMargin: float32;
|
||||
|
||||
@doc("""
|
||||
Anomaly status of the latest point, true means the latest point is an anomaly
|
||||
either in negative direction or positive direction.
|
||||
""")
|
||||
isAnomaly: boolean;
|
||||
|
||||
@doc("""
|
||||
Anomaly status in negative direction of the latest point. True means the latest
|
||||
point is an anomaly and its real value is smaller than the expected one.
|
||||
""")
|
||||
isNegativeAnomaly: boolean;
|
||||
|
||||
@doc("""
|
||||
Anomaly status in positive direction of the latest point. True means the latest
|
||||
point is an anomaly and its real value is larger than the expected one.
|
||||
""")
|
||||
isPositiveAnomaly: boolean;
|
||||
|
||||
@doc("""
|
||||
The severity score for the last input point. The larger the value is, the more
|
||||
sever the anomaly is. For normal points, the \"severity\" is always 0.
|
||||
""")
|
||||
severity?: float32;
|
||||
}
|
||||
|
||||
@doc("The request of change point detection.")
|
||||
model ChangePointDetectRequest {
|
||||
@doc("""
|
||||
Time series data points. Points should be sorted by timestamp in ascending
|
||||
order to match the change point detection result.
|
||||
""")
|
||||
series: TimeSeriesPoint[];
|
||||
|
||||
@doc("""
|
||||
Can only be one of yearly, monthly, weekly, daily, hourly, minutely or
|
||||
secondly. Granularity is used for verify whether input series is valid.
|
||||
""")
|
||||
granularity: TimeGranularity;
|
||||
|
||||
@doc("""
|
||||
Custom Interval is used to set non-standard time interval, for example, if the
|
||||
series is 5 minutes, request can be set as {\"granularity\":\"minutely\",
|
||||
\"customInterval\":5}.
|
||||
""")
|
||||
customInterval?: int32;
|
||||
|
||||
@doc("""
|
||||
Optional argument, periodic value of a time series. If the value is null or
|
||||
does not present, the API will determine the period automatically.
|
||||
""")
|
||||
period?: int32;
|
||||
|
||||
@doc("""
|
||||
Optional argument, advanced model parameter, a default stableTrendWindow will
|
||||
be used in detection.
|
||||
""")
|
||||
stableTrendWindow?: int32;
|
||||
|
||||
@doc("""
|
||||
Optional argument, advanced model parameter, between 0.0-1.0, the lower the
|
||||
value is, the larger the trend error will be which means less change point will
|
||||
be accepted.
|
||||
""")
|
||||
threshold?: float32;
|
||||
}
|
||||
|
||||
@doc("The response of change point detection.")
|
||||
model ChangePointDetectResponse {
|
||||
@doc("""
|
||||
Frequency extracted from the series, zero means no recurrent pattern has been
|
||||
found.
|
||||
""")
|
||||
@visibility("read")
|
||||
period?: int32;
|
||||
|
||||
@doc("""
|
||||
isChangePoint contains change point properties for each input point. True means
|
||||
an anomaly either negative or positive has been detected. The index of the
|
||||
array is consistent with the input series.
|
||||
""")
|
||||
isChangePoint?: boolean[];
|
||||
|
||||
@doc("the change point confidence of each point")
|
||||
confidenceScores?: float32[];
|
||||
}
|
||||
|
||||
@doc("Detection results for the given resultId.")
|
||||
@resource("multivariate/entire/detect/{resultId}")
|
||||
model DetectionResult {
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
resultId: string;
|
||||
|
||||
@doc("Multivariate anomaly detection status.")
|
||||
summary: DetectionResultSummary;
|
||||
|
||||
@doc("Detection result for each timestamp.")
|
||||
results: AnomalyState[];
|
||||
}
|
||||
|
||||
@doc("Multivariate anomaly detection status.")
|
||||
model DetectionResultSummary {
|
||||
@doc("Status of detection results. One of CREATED, RUNNING, READY, and FAILED.")
|
||||
status: DetectionStatus;
|
||||
|
||||
@doc("Error message when detection is failed.")
|
||||
errors?: ErrorResponse[];
|
||||
variableStates?: VariableState[];
|
||||
|
||||
@doc("Detection request.")
|
||||
setupInfo: DetectionRequest;
|
||||
}
|
||||
|
||||
@error
|
||||
model ErrorResponse {
|
||||
@doc("The error code.")
|
||||
code: string;
|
||||
|
||||
@doc("The message explaining the error reported by the service.")
|
||||
message: string;
|
||||
}
|
||||
|
||||
model VariableState {
|
||||
@doc("Variable name.")
|
||||
variable?: string;
|
||||
|
||||
@doc("Proportion of NaN values filled of the variable.")
|
||||
filledNARatio?: float32;
|
||||
|
||||
@doc("Number of effective points counted.")
|
||||
effectiveCount?: int32;
|
||||
|
||||
@doc("First timestamp of the variable.")
|
||||
firstTimestamp?: zonedDateTime;
|
||||
|
||||
@doc("Last timestamp of the variable.")
|
||||
lastTimestamp?: zonedDateTime;
|
||||
}
|
||||
|
||||
@doc("Detection request.")
|
||||
model DetectionRequest {
|
||||
@doc("""
|
||||
Source link to the input variables. Each variable should be a csv with two
|
||||
columns, `timestamp` and `value`. The file name of the variable will be used as
|
||||
its name. The variables used in detection should be exactly the same with those
|
||||
used in the training phase.
|
||||
""")
|
||||
dataSource: string;
|
||||
|
||||
@doc("Top contributor count.")
|
||||
topContributorCount: int32;
|
||||
|
||||
@doc("""
|
||||
A required field, indicating the start time of data for detection. Should be
|
||||
date-time.
|
||||
""")
|
||||
startTime: zonedDateTime;
|
||||
|
||||
@doc("""
|
||||
A required field, indicating the end time of data for detection. Should be
|
||||
date-time.
|
||||
""")
|
||||
endTime: zonedDateTime;
|
||||
}
|
||||
|
||||
model AnomalyState {
|
||||
@doc("timestamp")
|
||||
timestamp: zonedDateTime;
|
||||
value?: AnomalyValue;
|
||||
|
||||
@doc("Error message for the current timestamp")
|
||||
errors?: ErrorResponse[];
|
||||
}
|
||||
|
||||
model AnomalyValue {
|
||||
@doc("True if an anomaly is detected at the current timestamp.")
|
||||
isAnomaly: boolean;
|
||||
|
||||
@doc("""
|
||||
Indicates the significance of the anomaly. The higher the severity, the more
|
||||
significant the anomaly.
|
||||
""")
|
||||
severity: float32;
|
||||
|
||||
@doc("Raw score from the model.")
|
||||
score: float32;
|
||||
interpretation?: AnomalyInterpretation[];
|
||||
}
|
||||
|
||||
model AnomalyInterpretation {
|
||||
variable?: string;
|
||||
contributionScore?: float32;
|
||||
correlationChanges?: CorrelationChanges;
|
||||
}
|
||||
|
||||
model CorrelationChanges {
|
||||
@doc("correlated variables")
|
||||
changedVariables?: string[];
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Training result of a model including its status, errors and diagnostics
|
||||
information.
|
||||
""")
|
||||
model ModelInfo {
|
||||
@doc("""
|
||||
Source link to the input variables. Each variable should be a csv file with two
|
||||
columns, `timestamp` and `value`. By default, the file name of the variable
|
||||
will be used as its variable name.
|
||||
""")
|
||||
dataSource: string;
|
||||
dataSchema?: DataSchema;
|
||||
|
||||
@doc("""
|
||||
A required field, indicating the start time of training data. Should be
|
||||
date-time.
|
||||
""")
|
||||
startTime: zonedDateTime;
|
||||
|
||||
@doc("A required field, indicating the end time of training data. Should be date-time.")
|
||||
endTime: zonedDateTime;
|
||||
|
||||
@doc("An optional field. The name of the model whose maximum length is 24.")
|
||||
displayName?: string;
|
||||
|
||||
@doc("""
|
||||
An optional field, indicating how many previous points will be used to compute
|
||||
the anomaly score of the subsequent point.
|
||||
""")
|
||||
slidingWindow?: int32;
|
||||
|
||||
@doc("An optional field, indicating the manner to align multiple variables.")
|
||||
alignPolicy?: AlignPolicy;
|
||||
|
||||
@doc("Model status. One of CREATED, RUNNING, READY, and FAILED.")
|
||||
status?: ModelStatus;
|
||||
|
||||
@doc("Error messages when failed to create a model.")
|
||||
errors?: ErrorResponse[];
|
||||
|
||||
@doc("Diagnostics Information for inspecting model/variable states.")
|
||||
diagnosticsInfo?: DiagnosticsInfo;
|
||||
}
|
||||
|
||||
@doc("An optional field, indicating the manner to align multiple variables.")
|
||||
model AlignPolicy {
|
||||
@doc("""
|
||||
An optional field, indicating how we align different variables to the same
|
||||
time-range. Either Inner or Outer.
|
||||
""")
|
||||
alignMode?: AlignMode;
|
||||
|
||||
@doc("""
|
||||
An optional field, indicating how missing values will be filled. One of
|
||||
Previous, Subsequent, Linear, Zero, Fixed, and NotFill. Cannot be set to
|
||||
NotFill, when the alignMode is Outer.
|
||||
""")
|
||||
fillNAMethod?: FillNAMethod;
|
||||
|
||||
@doc("An optional field. Required when fillNAMethod is Fixed.")
|
||||
paddingValue?: float32;
|
||||
}
|
||||
|
||||
@doc("Diagnostics Information for inspecting model/variable states.")
|
||||
model DiagnosticsInfo {
|
||||
modelState?: ModelState;
|
||||
variableStates?: VariableState[];
|
||||
}
|
||||
|
||||
model ModelState {
|
||||
@doc("Epoch id")
|
||||
epochIds?: int32[];
|
||||
trainLosses?: float32[];
|
||||
validationLosses?: float32[];
|
||||
latenciesInSeconds?: float32[];
|
||||
}
|
||||
|
||||
@doc("Response of listing models.")
|
||||
@pagedResult
|
||||
model ModelList {
|
||||
@doc("List of models")
|
||||
@items
|
||||
models: ModelSnapshot[];
|
||||
|
||||
@doc("Current count of trained multivariate models.")
|
||||
currentCount: int32;
|
||||
|
||||
@doc("Max number of models that can be trained for this subscription.")
|
||||
maxCount: int32;
|
||||
|
||||
@doc("The link to fetch more models.")
|
||||
@nextLink
|
||||
nextLink?: string;
|
||||
}
|
||||
|
||||
@resource("multivariate/models")
|
||||
model ModelSnapshot {
|
||||
@doc("Model identifier.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
modelId: string;
|
||||
|
||||
@doc("Date and time (UTC) when the model was created.")
|
||||
createdTime: zonedDateTime;
|
||||
|
||||
@doc("Date and time (UTC) when the model was last updated.")
|
||||
lastUpdatedTime: zonedDateTime;
|
||||
|
||||
@doc("Model status. One of CREATED, RUNNING, READY, and FAILED.")
|
||||
status: ModelStatus;
|
||||
displayName?: string;
|
||||
|
||||
@doc("Total number of variables.")
|
||||
variablesCount: int32;
|
||||
}
|
||||
|
||||
@doc("Response of getting a model.")
|
||||
@resource("multivariate/models/{modelId}")
|
||||
model Model {
|
||||
@doc("Model identifier.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
modelId: string;
|
||||
|
||||
@doc("Date and time (UTC) when the model was created.")
|
||||
createdTime: zonedDateTime;
|
||||
|
||||
@doc("Date and time (UTC) when the model was last updated.")
|
||||
lastUpdatedTime: zonedDateTime;
|
||||
|
||||
@doc("""
|
||||
Training result of a model including its status, errors and diagnostics
|
||||
information.
|
||||
""")
|
||||
modelInfo?: ModelInfo;
|
||||
}
|
||||
|
||||
model LastDetectionRequest {
|
||||
@doc("variables")
|
||||
variables: VariableValues[];
|
||||
|
||||
@doc("Top contributor count.")
|
||||
topContributorCount: int32;
|
||||
}
|
||||
|
||||
model VariableValues {
|
||||
@doc("variable name")
|
||||
name: string;
|
||||
|
||||
@doc("timestamps")
|
||||
timestamps: string[];
|
||||
|
||||
@doc("values")
|
||||
values: float32[];
|
||||
}
|
||||
|
||||
model LastDetectionResult {
|
||||
variableStates?: VariableState[];
|
||||
results?: AnomalyState[];
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"name": "@cadl-api-spec/anomaly-detector-client",
|
||||
"author": "Microsoft Corporation",
|
||||
"description": "The Anomaly Detector API detects anomalies automatically in time series data. It supports two kinds of mode, one is for stateless using, another is for stateful using. In stateless mode, there are three functionalities. Entire Detect is for detecting the whole series with model trained by the time series, Last Detect is detecting last point with model trained by points before. ChangePoint Detect is for detecting trend changes in time series. In stateful mode, user can store time series, the stored time series will be used for detection anomalies. Under this mode, user can still use the above three functionalities by only giving a time range without preparing time series in client side. Besides the above three functionalities, stateful model also provide group based detection and labeling service. By leveraging labeling service user can provide labels for each detection result, these labels will be used for retuning or regenerating detection models. Inconsistency detection is a kind of group based detection, this detection will find inconsistency ones in a set of time series. By using anomaly detector service, business customers can discover incidents and establish a logic flow for root cause analysis.",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cadl-lang/compiler": "^0.37.0",
|
||||
"@cadl-lang/rest": "^0.19.0",
|
||||
"@cadl-lang/versioning": "^0.10.0",
|
||||
"@cadl-lang/prettier-plugin-cadl": "^0.5.17",
|
||||
"@azure-tools/cadl-azure-core": "^0.9.0",
|
||||
"@azure-tools/cadl-autorest": "^0.22.0",
|
||||
"@azure-tools/cadl-python": "^0.4.10",
|
||||
"prettier": "^2.7.1"
|
||||
},
|
||||
"private": true
|
||||
}
|
|
@ -0,0 +1,173 @@
|
|||
import "@azure-tools/cadl-azure-core";
|
||||
import "@cadl-lang/rest";
|
||||
import "./models.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
|
||||
namespace AnomalyDetectorClient;
|
||||
|
||||
@summary("Detect anomalies for the entire series in batch.")
|
||||
@doc("""
|
||||
This operation generates a model with an entire series, each point is detected
|
||||
with the same model. With this method, points before and after a certain point
|
||||
are used to determine whether it is an anomaly. The entire detection can give
|
||||
user an overall status of the time series.
|
||||
""")
|
||||
@route("/timeseries/entire/detect")
|
||||
@post
|
||||
op DetectEntireSeries is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("""
|
||||
Time series points and period if needed. Advanced model parameters can also be
|
||||
set in the request.
|
||||
""")
|
||||
@body
|
||||
body: DetectRequest;
|
||||
},
|
||||
EntireDetectResponse
|
||||
>;
|
||||
|
||||
@summary("Detect anomaly status of the latest point in time series.")
|
||||
@doc("""
|
||||
This operation generates a model using points before the latest one. With this
|
||||
method, only historical points are used to determine whether the target point
|
||||
is an anomaly. The latest point detecting operation matches the scenario of
|
||||
real-time monitoring of business metrics.
|
||||
""")
|
||||
@route("/timeseries/last/detect")
|
||||
@post
|
||||
op DetectLastPoint is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("""
|
||||
Time series points and period if needed. Advanced model parameters can also be
|
||||
set in the request.
|
||||
""")
|
||||
@body
|
||||
body: DetectRequest;
|
||||
},
|
||||
LastDetectResponse
|
||||
>;
|
||||
|
||||
@summary("Detect change point for the entire series")
|
||||
@doc("Evaluate change point score of every series point")
|
||||
@route("/timeseries/changepoint/detect")
|
||||
@post
|
||||
op DetectChangePoint is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("""
|
||||
Time series points and granularity is needed. Advanced model parameters can
|
||||
also be set in the request if needed.
|
||||
""")
|
||||
@body
|
||||
body: ChangePointDetectRequest;
|
||||
},
|
||||
ChangePointDetectResponse
|
||||
>;
|
||||
|
||||
@summary("Get Multivariate Anomaly Detection Result")
|
||||
@doc("""
|
||||
Get multivariate anomaly detection result based on resultId returned by the
|
||||
DetectAnomalyAsync api
|
||||
""")
|
||||
op GetDetectionResult is Azure.Core.ResourceRead<DetectionResult>;
|
||||
|
||||
@summary("Train a Multivariate Anomaly Detection Model")
|
||||
@doc("""
|
||||
Create and train a multivariate anomaly detection model. The request must
|
||||
include a source parameter to indicate an externally accessible Azure storage
|
||||
Uri (preferably a Shared Access Signature Uri). All time-series used in
|
||||
generate the model must be zipped into one single file. Each time-series will
|
||||
be in a single CSV file in which the first column is timestamp and the second
|
||||
column is value.
|
||||
""")
|
||||
@route("/multivariate/models")
|
||||
@post
|
||||
op TrainMultivariateModel is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Training request")
|
||||
@body
|
||||
body: ModelInfo;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@summary("List Multivariate Models")
|
||||
@doc("List models of a subscription")
|
||||
op ListMultivariateModel is Azure.Core.ResourceList<
|
||||
ModelSnapshot,
|
||||
{
|
||||
parameters: {
|
||||
@doc("$skip indicates how many models will be skipped.")
|
||||
@query
|
||||
$skip: int32;
|
||||
|
||||
@doc("$top indicates how many models will be fetched.")
|
||||
@query
|
||||
$top: int32;
|
||||
};
|
||||
}
|
||||
>;
|
||||
|
||||
@summary("Delete Multivariate Model")
|
||||
@doc("Delete an existing multivariate model according to the modelId")
|
||||
@route("/multivariate/models/{modelId}")
|
||||
@delete
|
||||
op DeleteMultivariateModel is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Model identifier")
|
||||
@path
|
||||
modelId: string;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@summary("Get Multivariate Model")
|
||||
@doc("""
|
||||
Get detailed information of multivariate model, including the training status
|
||||
and variables used in the model.
|
||||
""")
|
||||
op GetMultivariateModel is Azure.Core.ResourceRead<Model>;
|
||||
|
||||
@summary("Detect Multivariate Anomaly")
|
||||
@doc("""
|
||||
Submit detection multivariate anomaly task with the trained model of modelId,
|
||||
the input schema should be the same with the training request. Thus request
|
||||
will be complete asynchronously and will return a resultId for querying the
|
||||
detection result.The request should be a source link to indicate an externally
|
||||
accessible Azure storage Uri (preferably a Shared Access Signature Uri). All
|
||||
time-series used in generate the model must be zipped into one single file.
|
||||
Each time-series will be as follows: the first column is timestamp and the
|
||||
second column is value.
|
||||
""")
|
||||
@route("/multivariate/models/{modelId}/entire/detect")
|
||||
@post
|
||||
op DetectAnomaly is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Model identifier")
|
||||
@path
|
||||
modelId: string;
|
||||
|
||||
@doc("Detect anomaly request")
|
||||
@body
|
||||
body: DetectionRequest;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@summary("Detect anomalies in the last a few points of the request body")
|
||||
@doc("Synchronized API for anomaly detection.")
|
||||
@route("/multivariate/models/{modelId}/last/detect")
|
||||
@post
|
||||
op LastDetectAnomaly is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Model identifier")
|
||||
@path
|
||||
modelId: string;
|
||||
|
||||
@doc("Request for last detection")
|
||||
@body
|
||||
body: LastDetectionRequest;
|
||||
},
|
||||
LastDetectionResult
|
||||
>;
|
|
@ -0,0 +1,5 @@
|
|||
```yaml
|
||||
require: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/7a9bd6a89b7d13bd56e757b926a45d669ee32906/specification/cognitiveservices/data-plane/AnomalyDetector/readme.md
|
||||
clear-output-folder: false
|
||||
isAzureSpec: true
|
||||
```
|
|
@ -0,0 +1,14 @@
|
|||
emitters:
|
||||
# "@azure-tools/cadl-autorest": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-python" to your package.json to generate Python code
|
||||
# "@azure-tools/cadl-python":
|
||||
# "basic-setup-py": true
|
||||
# "package-version":
|
||||
# "package-name":
|
||||
# "output-path":
|
||||
# Uncomment this line and add "@azure-tools/cadl-java" to your package.json to generate Java code
|
||||
# "@azure-tools/cadl-java": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-csharp" to your package.json to generate C# code
|
||||
# "@azure-tools/cadl-csharp": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-typescript" to your package.json to generate Typescript code
|
||||
# "@azure-tools/cadl-typescript": true
|
|
@ -0,0 +1,19 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "./routes.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
@service({
|
||||
title: "Microsoft Azure Compute Management",
|
||||
})
|
||||
@serviceVersion("2022-08-01")
|
||||
@server(
|
||||
"{$host}",
|
||||
"Compute Client",
|
||||
{
|
||||
@doc("server parameter")
|
||||
$host: string,
|
||||
}
|
||||
)
|
||||
@doc("Compute Client")
|
||||
namespace Compute;
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"name": "@cadl-api-spec/microsoft-azure-compute-management",
|
||||
"author": "Microsoft Corporation",
|
||||
"description": "Compute Client",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cadl-lang/compiler": "^0.37.0",
|
||||
"@cadl-lang/rest": "^0.19.0",
|
||||
"@cadl-lang/versioning": "^0.10.0",
|
||||
"@cadl-lang/prettier-plugin-cadl": "^0.5.17",
|
||||
"@azure-tools/cadl-azure-core": "^0.9.0",
|
||||
"@azure-tools/cadl-autorest": "^0.22.0",
|
||||
"@azure-tools/cadl-python": "^0.4.10",
|
||||
"prettier": "^2.7.1"
|
||||
},
|
||||
"private": true
|
||||
}
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,10 @@
|
|||
```yaml
|
||||
require:
|
||||
- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/ddca448bd879175a928b990e0f25ca3a0e6c1c33/specification/compute/resource-manager/readme.md
|
||||
title: Microsoft Azure Compute Management
|
||||
clear-output-folder: false
|
||||
guessResourceKey: false
|
||||
isAzureSpec: true
|
||||
namespace: "Compute"
|
||||
tag: package-2022-08-01-only
|
||||
```
|
|
@ -0,0 +1,9 @@
|
|||
```yaml
|
||||
input-file:
|
||||
- https://github.com/wiboris/azure-rest-api-specs/blob/SwaggerRefactor/specification/batch/data-plane/Microsoft.Batch/stable/2022-12-01/BatchService.json
|
||||
title: Azure Batch Service
|
||||
clear-output-folder: false
|
||||
guessResourceKey: true
|
||||
isAzureSpec: true
|
||||
namespace: "Azure.Batch"
|
||||
```
|
|
@ -0,0 +1,14 @@
|
|||
emitters:
|
||||
# "@azure-tools/cadl-autorest": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-python" to your package.json to generate Python code
|
||||
# "@azure-tools/cadl-python":
|
||||
# "basic-setup-py": true
|
||||
# "package-version":
|
||||
# "package-name":
|
||||
# "output-path":
|
||||
# Uncomment this line and add "@azure-tools/cadl-java" to your package.json to generate Java code
|
||||
# "@azure-tools/cadl-java": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-csharp" to your package.json to generate C# code
|
||||
# "@azure-tools/cadl-csharp": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-typescript" to your package.json to generate Typescript code
|
||||
# "@azure-tools/cadl-typescript": true
|
|
@ -0,0 +1,19 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "./routes.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
@service({
|
||||
title: "Azure Batch Service",
|
||||
})
|
||||
@serviceVersion("2022-01-01.15.0")
|
||||
@server(
|
||||
"{batchUrl}",
|
||||
"A client for issuing REST requests to the Azure Batch service.",
|
||||
{
|
||||
@doc("The base URL for all Azure Batch service requests.")
|
||||
batchUrl: string,
|
||||
}
|
||||
)
|
||||
@doc("A client for issuing REST requests to the Azure Batch service.")
|
||||
namespace Azure.Batch;
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"name": "@cadl-api-spec/azure-batch-service",
|
||||
"author": "Microsoft Corporation",
|
||||
"description": "A client for issuing REST requests to the Azure Batch service.",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cadl-lang/compiler": "^0.37.0",
|
||||
"@cadl-lang/rest": "^0.19.0",
|
||||
"@cadl-lang/versioning": "^0.10.0",
|
||||
"@cadl-lang/prettier-plugin-cadl": "^0.5.17",
|
||||
"@azure-tools/cadl-azure-core": "^0.9.0",
|
||||
"@azure-tools/cadl-autorest": "^0.22.0",
|
||||
"@azure-tools/cadl-python": "^0.4.10",
|
||||
"prettier": "^2.7.1"
|
||||
},
|
||||
"private": true
|
||||
}
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,14 @@
|
|||
emitters:
|
||||
# "@azure-tools/cadl-autorest": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-python" to your package.json to generate Python code
|
||||
# "@azure-tools/cadl-python":
|
||||
# "basic-setup-py": true
|
||||
# "package-version":
|
||||
# "package-name":
|
||||
# "output-path":
|
||||
# Uncomment this line and add "@azure-tools/cadl-java" to your package.json to generate Java code
|
||||
# "@azure-tools/cadl-java": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-csharp" to your package.json to generate C# code
|
||||
# "@azure-tools/cadl-csharp": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-typescript" to your package.json to generate Typescript code
|
||||
# "@azure-tools/cadl-typescript": true
|
|
@ -0,0 +1,19 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "./routes.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
@service({
|
||||
title: "AutoRest Complex Test Service",
|
||||
})
|
||||
@serviceVersion("2016-02-29")
|
||||
@server(
|
||||
"{$host}",
|
||||
"Test Infrastructure for AutoRest",
|
||||
{
|
||||
@doc("server parameter")
|
||||
$host: string,
|
||||
}
|
||||
)
|
||||
@doc("Test Infrastructure for AutoRest")
|
||||
namespace AutoRestComplexTestService;
|
|
@ -0,0 +1,218 @@
|
|||
import "@cadl-lang/rest";
|
||||
|
||||
using Cadl.Rest;
|
||||
|
||||
namespace AutoRestComplexTestService;
|
||||
|
||||
enum CMYKColorsKnownValues {
|
||||
Cyan: "cyan",
|
||||
"Magenta",
|
||||
Yellow: "YELLOW",
|
||||
BlacK: "blacK",
|
||||
}
|
||||
|
||||
@knownValues(CMYKColorsKnownValues)
|
||||
model CMYKColors is string;
|
||||
|
||||
enum MyKindKnownValues {
|
||||
"Kind1",
|
||||
}
|
||||
|
||||
@knownValues(MyKindKnownValues)
|
||||
model MyKind is string;
|
||||
|
||||
enum GoblinSharkColorKnownValues {
|
||||
Pink: "pink",
|
||||
Gray: "gray",
|
||||
Brown: "brown",
|
||||
UpperRed: "RED",
|
||||
LowerRed: "red",
|
||||
}
|
||||
|
||||
@knownValues(GoblinSharkColorKnownValues)
|
||||
model GoblinSharkColor is string;
|
||||
|
||||
model Basic {
|
||||
@doc("Basic Id")
|
||||
id?: int32;
|
||||
|
||||
@doc("""
|
||||
Name property with a very long description that does not fit on a single line
|
||||
and a line break.
|
||||
""")
|
||||
name?: string;
|
||||
color?: CMYKColors;
|
||||
}
|
||||
|
||||
@error
|
||||
model Error {
|
||||
status?: int32;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
model IntWrapper {
|
||||
field1?: int32;
|
||||
field2?: int32;
|
||||
}
|
||||
|
||||
model LongWrapper {
|
||||
field1?: int32;
|
||||
field2?: int32;
|
||||
}
|
||||
|
||||
model FloatWrapper {
|
||||
field1?: float32;
|
||||
field2?: float32;
|
||||
}
|
||||
|
||||
model DoubleWrapper {
|
||||
field1?: float32;
|
||||
field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose?: float32;
|
||||
}
|
||||
|
||||
model BooleanWrapper {
|
||||
field_true?: boolean;
|
||||
field_false?: boolean;
|
||||
}
|
||||
|
||||
model StringWrapper {
|
||||
field?: string;
|
||||
empty?: string;
|
||||
null?: string;
|
||||
}
|
||||
|
||||
model DateWrapper {
|
||||
field?: plainDate;
|
||||
leap?: plainDate;
|
||||
}
|
||||
|
||||
model DatetimeWrapper {
|
||||
field?: zonedDateTime;
|
||||
now?: zonedDateTime;
|
||||
}
|
||||
|
||||
model Datetimerfc1123Wrapper {
|
||||
field?: zonedDateTime;
|
||||
now?: zonedDateTime;
|
||||
}
|
||||
|
||||
model DurationWrapper {
|
||||
field?: duration;
|
||||
}
|
||||
|
||||
model ByteWrapper {
|
||||
field?: bytes;
|
||||
}
|
||||
|
||||
model ArrayWrapper {
|
||||
array?: string[];
|
||||
}
|
||||
|
||||
model DictionaryWrapper {
|
||||
@doc("Dictionary of <string>")
|
||||
defaultProgram?: Record<string>;
|
||||
}
|
||||
|
||||
model Siamese {
|
||||
...Cat;
|
||||
breed?: string;
|
||||
}
|
||||
|
||||
model Cat {
|
||||
...Pet;
|
||||
color?: string;
|
||||
hates?: Dog[];
|
||||
}
|
||||
|
||||
model Dog {
|
||||
...Pet;
|
||||
food?: string;
|
||||
}
|
||||
|
||||
model Pet {
|
||||
id?: int32;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
@discriminator("fishtype")
|
||||
model Fish {
|
||||
species?: string;
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
|
||||
@key
|
||||
length: float32;
|
||||
siblings?: Fish[];
|
||||
}
|
||||
|
||||
@discriminator("fish.type")
|
||||
model DotFish {
|
||||
species?: string;
|
||||
}
|
||||
|
||||
model DotFishMarket {
|
||||
sampleSalmon?: DotSalmon;
|
||||
salmons?: DotSalmon[];
|
||||
sampleFish?: DotFish;
|
||||
fishes?: DotFish[];
|
||||
}
|
||||
|
||||
model DotSalmon extends DotFish {
|
||||
location?: string;
|
||||
iswild?: boolean;
|
||||
"fish.type": "DotSalmon";
|
||||
}
|
||||
|
||||
@discriminator("fishtype")
|
||||
model Salmon extends Fish {
|
||||
location?: string;
|
||||
iswild?: boolean;
|
||||
}
|
||||
|
||||
model ReadonlyObj {
|
||||
@visibility("read")
|
||||
id?: string;
|
||||
size?: int32;
|
||||
}
|
||||
|
||||
@discriminator("kind")
|
||||
model MyBaseType {
|
||||
propB1?: string;
|
||||
helper?: MyBaseHelperType;
|
||||
}
|
||||
|
||||
model MyBaseHelperType {
|
||||
propBH1?: string;
|
||||
}
|
||||
|
||||
model SmartSalmon extends Salmon {
|
||||
college_degree?: string;
|
||||
fishtype: "smart_salmon";
|
||||
}
|
||||
|
||||
@discriminator("fishtype")
|
||||
model Shark extends Fish {
|
||||
age?: int32;
|
||||
birthday: zonedDateTime;
|
||||
}
|
||||
|
||||
model Sawshark extends Shark {
|
||||
picture?: bytes;
|
||||
fishtype: "sawshark";
|
||||
}
|
||||
|
||||
model Goblinshark extends Shark {
|
||||
jawsize?: int32;
|
||||
|
||||
@doc("Colors possible")
|
||||
color?: GoblinSharkColor;
|
||||
fishtype: "goblin";
|
||||
}
|
||||
|
||||
model Cookiecuttershark extends Shark {
|
||||
fishtype: "cookiecuttershark";
|
||||
}
|
||||
|
||||
model MyDerivedType extends MyBaseType {
|
||||
propD1?: string;
|
||||
kind: "Kind1";
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"name": "@cadl-api-spec/autorest-complex-test-service",
|
||||
"author": "Microsoft Corporation",
|
||||
"description": "Test Infrastructure for AutoRest",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cadl-lang/compiler": "^0.37.0",
|
||||
"@cadl-lang/rest": "^0.19.0",
|
||||
"@cadl-lang/versioning": "^0.10.0",
|
||||
"@cadl-lang/prettier-plugin-cadl": "^0.5.17",
|
||||
"@azure-tools/cadl-azure-core": "^0.9.0",
|
||||
"@azure-tools/cadl-autorest": "^0.22.0",
|
||||
"@azure-tools/cadl-python": "^0.4.10",
|
||||
"prettier": "^2.7.1"
|
||||
},
|
||||
"private": true
|
||||
}
|
|
@ -0,0 +1,655 @@
|
|||
import "@azure-tools/cadl-azure-core";
|
||||
import "@cadl-lang/rest";
|
||||
import "./models.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
|
||||
namespace AutoRestComplexTestService;
|
||||
|
||||
interface BasicOperations {
|
||||
@doc("Get complex type {id: 2, name: 'abc', color: 'YELLOW'}")
|
||||
@route("/complex/basic/valid")
|
||||
@get
|
||||
GetValid is Azure.Core.Foundations.Operation<{}, Basic>;
|
||||
|
||||
@doc("Please put {id: 2, name: 'abc', color: 'Magenta'}")
|
||||
@route("/complex/basic/valid")
|
||||
@put
|
||||
PutValid is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put {id: 2, name: 'abc', color: 'Magenta'}")
|
||||
@body
|
||||
complexBody: Basic;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get a basic complex type that is invalid for the local strong type")
|
||||
@route("/complex/basic/invalid")
|
||||
@get
|
||||
GetInvalid is Azure.Core.Foundations.Operation<{}, Basic>;
|
||||
|
||||
@doc("Get a basic complex type that is empty")
|
||||
@route("/complex/basic/empty")
|
||||
@get
|
||||
GetEmpty is Azure.Core.Foundations.Operation<{}, Basic>;
|
||||
|
||||
@doc("Get a basic complex type whose properties are null")
|
||||
@route("/complex/basic/null")
|
||||
@get
|
||||
GetNull is Azure.Core.Foundations.Operation<{}, Basic>;
|
||||
|
||||
@doc("Get a basic complex type while the server doesn't provide a response payload")
|
||||
@route("/complex/basic/notprovided")
|
||||
@get
|
||||
GetNotProvided is Azure.Core.Foundations.Operation<{}, Basic>;
|
||||
}
|
||||
|
||||
interface PrimitiveOperations {
|
||||
@doc("Get complex types with integer properties")
|
||||
@route("/complex/primitive/integer")
|
||||
@get
|
||||
GetInt is Azure.Core.Foundations.Operation<{}, IntWrapper>;
|
||||
|
||||
@doc("Put complex types with integer properties")
|
||||
@route("/complex/primitive/integer")
|
||||
@put
|
||||
PutInt is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put -1 and 2")
|
||||
@body
|
||||
complexBody: IntWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with long properties")
|
||||
@route("/complex/primitive/long")
|
||||
@get
|
||||
GetLong is Azure.Core.Foundations.Operation<{}, LongWrapper>;
|
||||
|
||||
@doc("Put complex types with long properties")
|
||||
@route("/complex/primitive/long")
|
||||
@put
|
||||
PutLong is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put 1099511627775 and -999511627788")
|
||||
@body
|
||||
complexBody: LongWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with float properties")
|
||||
@route("/complex/primitive/float")
|
||||
@get
|
||||
GetFloat is Azure.Core.Foundations.Operation<{}, FloatWrapper>;
|
||||
|
||||
@doc("Put complex types with float properties")
|
||||
@route("/complex/primitive/float")
|
||||
@put
|
||||
PutFloat is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put 1.05 and -0.003")
|
||||
@body
|
||||
complexBody: FloatWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with double properties")
|
||||
@route("/complex/primitive/double")
|
||||
@get
|
||||
GetDouble is Azure.Core.Foundations.Operation<{}, DoubleWrapper>;
|
||||
|
||||
@doc("Put complex types with double properties")
|
||||
@route("/complex/primitive/double")
|
||||
@put
|
||||
PutDouble is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("""
|
||||
Please put 3e-100 and
|
||||
-0.000000000000000000000000000000000000000000000000000000005
|
||||
""")
|
||||
@body
|
||||
complexBody: DoubleWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with bool properties")
|
||||
@route("/complex/primitive/bool")
|
||||
@get
|
||||
GetBool is Azure.Core.Foundations.Operation<{}, BooleanWrapper>;
|
||||
|
||||
@doc("Put complex types with bool properties")
|
||||
@route("/complex/primitive/bool")
|
||||
@put
|
||||
PutBool is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put true and false")
|
||||
@body
|
||||
complexBody: BooleanWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with string properties")
|
||||
@route("/complex/primitive/string")
|
||||
@get
|
||||
GetString is Azure.Core.Foundations.Operation<{}, StringWrapper>;
|
||||
|
||||
@doc("Put complex types with string properties")
|
||||
@route("/complex/primitive/string")
|
||||
@put
|
||||
PutString is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put 'goodrequest', '', and null")
|
||||
@body
|
||||
complexBody: StringWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with date properties")
|
||||
@route("/complex/primitive/date")
|
||||
@get
|
||||
GetDate is Azure.Core.Foundations.Operation<{}, DateWrapper>;
|
||||
|
||||
@doc("Put complex types with date properties")
|
||||
@route("/complex/primitive/date")
|
||||
@put
|
||||
PutDate is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put '0001-01-01' and '2016-02-29'")
|
||||
@body
|
||||
complexBody: DateWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with datetime properties")
|
||||
@route("/complex/primitive/datetime")
|
||||
@get
|
||||
GetDateTime is Azure.Core.Foundations.Operation<{}, DatetimeWrapper>;
|
||||
|
||||
@doc("Put complex types with datetime properties")
|
||||
@route("/complex/primitive/datetime")
|
||||
@put
|
||||
PutDateTime is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00'")
|
||||
@body
|
||||
complexBody: DatetimeWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with datetimeRfc1123 properties")
|
||||
@route("/complex/primitive/datetimerfc1123")
|
||||
@get
|
||||
GetDateTimeRfc1123 is Azure.Core.Foundations.Operation<
|
||||
{},
|
||||
Datetimerfc1123Wrapper
|
||||
>;
|
||||
|
||||
@doc("Put complex types with datetimeRfc1123 properties")
|
||||
@route("/complex/primitive/datetimerfc1123")
|
||||
@put
|
||||
PutDateTimeRfc1123 is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00 GMT'")
|
||||
@body
|
||||
complexBody: Datetimerfc1123Wrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with duration properties")
|
||||
@route("/complex/primitive/duration")
|
||||
@get
|
||||
GetDuration is Azure.Core.Foundations.Operation<{}, DurationWrapper>;
|
||||
|
||||
@doc("Put complex types with duration properties")
|
||||
@route("/complex/primitive/duration")
|
||||
@put
|
||||
PutDuration is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put 'P123DT22H14M12.011S'")
|
||||
@body
|
||||
complexBody: DurationWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with byte properties")
|
||||
@route("/complex/primitive/byte")
|
||||
@get
|
||||
GetByte is Azure.Core.Foundations.Operation<{}, ByteWrapper>;
|
||||
|
||||
@doc("Put complex types with byte properties")
|
||||
@route("/complex/primitive/byte")
|
||||
@put
|
||||
PutByte is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6)")
|
||||
@body
|
||||
complexBody: ByteWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
}
|
||||
|
||||
interface ArrayOperations {
|
||||
@doc("Get complex types with array property")
|
||||
@route("/complex/array/valid")
|
||||
@get
|
||||
GetValid is Azure.Core.Foundations.Operation<{}, ArrayWrapper>;
|
||||
|
||||
@doc("Put complex types with array property")
|
||||
@route("/complex/array/valid")
|
||||
@put
|
||||
PutValid is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("""
|
||||
Please put an array with 4 items: \"1, 2, 3, 4\", \"\", null, \"&S#$(*Y\",
|
||||
\"The quick brown fox jumps over the lazy dog\"
|
||||
""")
|
||||
@body
|
||||
complexBody: ArrayWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with array property which is empty")
|
||||
@route("/complex/array/empty")
|
||||
@get
|
||||
GetEmpty is Azure.Core.Foundations.Operation<{}, ArrayWrapper>;
|
||||
|
||||
@doc("Put complex types with array property which is empty")
|
||||
@route("/complex/array/empty")
|
||||
@put
|
||||
PutEmpty is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put an empty array")
|
||||
@body
|
||||
complexBody: ArrayWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("""
|
||||
Get complex types with array property while server doesn't provide a response
|
||||
payload
|
||||
""")
|
||||
@route("/complex/array/notprovided")
|
||||
@get
|
||||
GetNotProvided is Azure.Core.Foundations.Operation<{}, ArrayWrapper>;
|
||||
}
|
||||
|
||||
interface DictionaryOperations {
|
||||
@doc("Get complex types with dictionary property")
|
||||
@route("/complex/dictionary/typed/valid")
|
||||
@get
|
||||
GetValid is Azure.Core.Foundations.Operation<{}, DictionaryWrapper>;
|
||||
|
||||
@doc("Put complex types with dictionary property")
|
||||
@route("/complex/dictionary/typed/valid")
|
||||
@put
|
||||
PutValid is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("""
|
||||
Please put a dictionary with 5 key-value pairs: \"txt\":\"notepad\",
|
||||
\"bmp\":\"mspaint\", \"xls\":\"excel\", \"exe\":\"\", \"\":null
|
||||
""")
|
||||
@body
|
||||
complexBody: DictionaryWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with dictionary property which is empty")
|
||||
@route("/complex/dictionary/typed/empty")
|
||||
@get
|
||||
GetEmpty is Azure.Core.Foundations.Operation<{}, DictionaryWrapper>;
|
||||
|
||||
@doc("Put complex types with dictionary property which is empty")
|
||||
@route("/complex/dictionary/typed/empty")
|
||||
@put
|
||||
PutEmpty is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Please put an empty dictionary")
|
||||
@body
|
||||
complexBody: DictionaryWrapper;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types with dictionary property which is null")
|
||||
@route("/complex/dictionary/typed/null")
|
||||
@get
|
||||
GetNull is Azure.Core.Foundations.Operation<{}, DictionaryWrapper>;
|
||||
|
||||
@doc("""
|
||||
Get complex types with dictionary property while server doesn't provide a
|
||||
response payload
|
||||
""")
|
||||
@route("/complex/dictionary/typed/notprovided")
|
||||
@get
|
||||
GetNotProvided is Azure.Core.Foundations.Operation<{}, DictionaryWrapper>;
|
||||
}
|
||||
|
||||
interface InheritanceOperations {
|
||||
@doc("Get complex types that extend others")
|
||||
@route("/complex/inheritance/valid")
|
||||
@get
|
||||
GetValid is Azure.Core.Foundations.Operation<{}, Siamese>;
|
||||
|
||||
@doc("Put complex types that extend others")
|
||||
@route("/complex/inheritance/valid")
|
||||
@put
|
||||
PutValid is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("""
|
||||
Please put a siamese with id=2, name=\"Siameee\", color=green, breed=persion,
|
||||
which hates 2 dogs, the 1st one named \"Potato\" with id=1 and food=\"tomato\",
|
||||
and the 2nd one named \"Tomato\" with id=-1 and food=\"french fries\".
|
||||
""")
|
||||
@body
|
||||
complexBody: Siamese;
|
||||
},
|
||||
void
|
||||
>;
|
||||
}
|
||||
|
||||
interface PolymorphismOperations {
|
||||
@doc("Get complex types that are polymorphic")
|
||||
@route("/complex/polymorphism/valid")
|
||||
@get
|
||||
GetValid is Azure.Core.Foundations.Operation<{}, Fish>;
|
||||
|
||||
@doc("Put complex types that are polymorphic")
|
||||
@route("/complex/polymorphism/valid")
|
||||
@put
|
||||
PutValid is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("""
|
||||
Please put a salmon that looks like this:
|
||||
{
|
||||
'fishtype':'Salmon',
|
||||
|
||||
'location':'alaska',
|
||||
'iswild':true,
|
||||
'species':'king',
|
||||
|
||||
'length':1.0,
|
||||
'siblings':[
|
||||
{
|
||||
'fishtype':'Shark',
|
||||
|
||||
'age':6,
|
||||
'birthday': '2012-01-05T01:00:00Z',
|
||||
|
||||
'length':20.0,
|
||||
'species':'predator',
|
||||
},
|
||||
{
|
||||
|
||||
'fishtype':'Sawshark',
|
||||
'age':105,
|
||||
'birthday':
|
||||
'1900-01-05T01:00:00Z',
|
||||
'length':10.0,
|
||||
'picture': new
|
||||
Buffer([255, 255, 255, 255, 254]).toString('base64'),
|
||||
|
||||
'species':'dangerous',
|
||||
},
|
||||
{
|
||||
'fishtype':
|
||||
'goblin',
|
||||
'age': 1,
|
||||
'birthday':
|
||||
'2015-08-08T00:00:00Z',
|
||||
'length': 30.0,
|
||||
'species':
|
||||
'scary',
|
||||
'jawsize': 5
|
||||
}
|
||||
]
|
||||
};
|
||||
""")
|
||||
@body
|
||||
complexBody: Fish;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get complex types that are polymorphic, JSON key contains a dot")
|
||||
@route("/complex/polymorphism/dotsyntax")
|
||||
@get
|
||||
GetDotSyntax is Azure.Core.Foundations.Operation<{}, DotFish>;
|
||||
|
||||
@doc("""
|
||||
Get complex object composing a polymorphic scalar property and array property
|
||||
with polymorphic element type, with discriminator specified. Deserialization
|
||||
must NOT fail and use the discriminator type specified on the wire.
|
||||
""")
|
||||
@route("/complex/polymorphism/composedWithDiscriminator")
|
||||
@get
|
||||
GetComposedWithDiscriminator is Azure.Core.Foundations.Operation<
|
||||
{},
|
||||
DotFishMarket
|
||||
>;
|
||||
|
||||
@doc("""
|
||||
Get complex object composing a polymorphic scalar property and array property
|
||||
with polymorphic element type, without discriminator specified on wire.
|
||||
Deserialization must NOT fail and use the explicit type of the property.
|
||||
""")
|
||||
@route("/complex/polymorphism/composedWithoutDiscriminator")
|
||||
@get
|
||||
GetComposedWithoutDiscriminator is Azure.Core.Foundations.Operation<
|
||||
{},
|
||||
DotFishMarket
|
||||
>;
|
||||
|
||||
@doc("""
|
||||
Get complex types that are polymorphic, but not at the root of the hierarchy;
|
||||
also have additional properties
|
||||
""")
|
||||
@route("/complex/polymorphism/complicated")
|
||||
@get
|
||||
GetComplicated is Azure.Core.Foundations.Operation<{}, Salmon>;
|
||||
|
||||
@doc("""
|
||||
Put complex types that are polymorphic, but not at the root of the hierarchy;
|
||||
also have additional properties
|
||||
""")
|
||||
@route("/complex/polymorphism/complicated")
|
||||
@put
|
||||
PutComplicated is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@body complexBody: Salmon;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Put complex types that are polymorphic, omitting the discriminator")
|
||||
@route("/complex/polymorphism/missingdiscriminator")
|
||||
@put
|
||||
PutMissingDiscriminator is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@body complexBody: Salmon;
|
||||
},
|
||||
Salmon
|
||||
>;
|
||||
|
||||
@doc("""
|
||||
Put complex types that are polymorphic, attempting to omit required 'birthday'
|
||||
field - the request should not be allowed from the client
|
||||
""")
|
||||
@route("/complex/polymorphism/missingrequired/invalid")
|
||||
@put
|
||||
PutValidMissingRequired is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("""
|
||||
Please attempt put a sawshark that looks like this, the client should not allow
|
||||
this data to be sent:
|
||||
{
|
||||
\"fishtype\": \"sawshark\",
|
||||
\"species\":
|
||||
\"snaggle toothed\",
|
||||
\"length\": 18.5,
|
||||
\"age\": 2,
|
||||
\"birthday\":
|
||||
\"2013-06-01T01:00:00Z\",
|
||||
\"location\": \"alaska\",
|
||||
\"picture\":
|
||||
base64(FF FF FF FF FE),
|
||||
\"siblings\": [
|
||||
{
|
||||
\"fishtype\":
|
||||
\"shark\",
|
||||
\"species\": \"predator\",
|
||||
\"birthday\":
|
||||
\"2012-01-05T01:00:00Z\",
|
||||
\"length\": 20,
|
||||
\"age\": 6
|
||||
|
||||
},
|
||||
{
|
||||
\"fishtype\": \"sawshark\",
|
||||
|
||||
\"species\": \"dangerous\",
|
||||
\"picture\": base64(FF FF FF FF FE),
|
||||
|
||||
\"length\": 10,
|
||||
\"age\": 105
|
||||
}
|
||||
]
|
||||
}
|
||||
""")
|
||||
@body
|
||||
complexBody: Fish;
|
||||
},
|
||||
void
|
||||
>;
|
||||
}
|
||||
|
||||
interface PolymorphicrecursiveOperations {
|
||||
@doc("Get complex types that are polymorphic and have recursive references")
|
||||
@route("/complex/polymorphicrecursive/valid")
|
||||
@get
|
||||
GetValid is Azure.Core.Foundations.Operation<{}, Fish>;
|
||||
|
||||
@doc("Put complex types that are polymorphic and have recursive references")
|
||||
@route("/complex/polymorphicrecursive/valid")
|
||||
@put
|
||||
PutValid is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("""
|
||||
Please put a salmon that looks like this:
|
||||
{
|
||||
\"fishtype\": \"salmon\",
|
||||
|
||||
\"species\": \"king\",
|
||||
\"length\": 1,
|
||||
\"age\": 1,
|
||||
\"location\":
|
||||
\"alaska\",
|
||||
\"iswild\": true,
|
||||
\"siblings\": [
|
||||
{
|
||||
|
||||
\"fishtype\": \"shark\",
|
||||
\"species\": \"predator\",
|
||||
|
||||
\"length\": 20,
|
||||
\"age\": 6,
|
||||
\"siblings\": [
|
||||
|
||||
{
|
||||
\"fishtype\": \"salmon\",
|
||||
|
||||
\"species\": \"coho\",
|
||||
\"length\": 2,
|
||||
|
||||
\"age\": 2,
|
||||
\"location\": \"atlantic\",
|
||||
|
||||
\"iswild\": true,
|
||||
\"siblings\": [
|
||||
|
||||
{
|
||||
\"fishtype\": \"shark\",
|
||||
|
||||
\"species\": \"predator\",
|
||||
\"length\": 20,
|
||||
|
||||
\"age\": 6
|
||||
},
|
||||
|
||||
{
|
||||
\"fishtype\": \"sawshark\",
|
||||
|
||||
\"species\": \"dangerous\",
|
||||
\"length\":
|
||||
10,
|
||||
\"age\": 105
|
||||
}
|
||||
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
\"fishtype\": \"sawshark\",
|
||||
\"species\": \"dangerous\",
|
||||
|
||||
\"length\": 10,
|
||||
\"age\": 105
|
||||
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
\"fishtype\": \"sawshark\",
|
||||
|
||||
\"species\": \"dangerous\",
|
||||
\"length\": 10,
|
||||
|
||||
\"age\": 105
|
||||
}
|
||||
]
|
||||
}
|
||||
""")
|
||||
@body
|
||||
complexBody: Fish;
|
||||
},
|
||||
void
|
||||
>;
|
||||
}
|
||||
|
||||
interface ReadonlypropertyOperations {
|
||||
@doc("Get complex types that have readonly properties")
|
||||
@route("/complex/readonlyproperty/valid")
|
||||
@get
|
||||
GetValid is Azure.Core.Foundations.Operation<{}, ReadonlyObj>;
|
||||
|
||||
@doc("Put complex types that have readonly properties")
|
||||
@route("/complex/readonlyproperty/valid")
|
||||
@put
|
||||
PutValid is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@body complexBody: ReadonlyObj;
|
||||
},
|
||||
void
|
||||
>;
|
||||
}
|
||||
|
||||
interface FlattencomplexOperations {
|
||||
@route("/complex/flatten/valid")
|
||||
@get
|
||||
GetValid is Azure.Core.Foundations.Operation<{}, MyBaseType>;
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
emitters:
|
||||
# "@azure-tools/cadl-autorest": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-python" to your package.json to generate Python code
|
||||
# "@azure-tools/cadl-python":
|
||||
# "basic-setup-py": true
|
||||
# "package-version":
|
||||
# "package-name":
|
||||
# "output-path":
|
||||
# Uncomment this line and add "@azure-tools/cadl-java" to your package.json to generate Java code
|
||||
# "@azure-tools/cadl-java": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-csharp" to your package.json to generate C# code
|
||||
# "@azure-tools/cadl-csharp": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-typescript" to your package.json to generate Typescript code
|
||||
# "@azure-tools/cadl-typescript": true
|
|
@ -0,0 +1,19 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "./routes.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
@service({
|
||||
title: "Complex Model Client",
|
||||
})
|
||||
@serviceVersion("2014-04-01-preview")
|
||||
@server(
|
||||
"{$host}",
|
||||
"Some cool documentation.",
|
||||
{
|
||||
@doc("server parameter")
|
||||
$host: string,
|
||||
}
|
||||
)
|
||||
@doc("Some cool documentation.")
|
||||
namespace ComplexModelClient;
|
|
@ -0,0 +1,53 @@
|
|||
import "@cadl-lang/rest";
|
||||
|
||||
using Cadl.Rest;
|
||||
|
||||
namespace ComplexModelClient;
|
||||
|
||||
model CatalogArray {
|
||||
@doc("Array of products")
|
||||
productArray?: Product[];
|
||||
}
|
||||
|
||||
@doc("The product documentation.")
|
||||
model Product {
|
||||
@doc("""
|
||||
Unique identifier representing a specific product for a given latitude &
|
||||
longitude. For example, uberX in San Francisco will have a different product_id
|
||||
than uberX in Los Angeles.
|
||||
""")
|
||||
product_id?: string;
|
||||
|
||||
@doc("Description of product.")
|
||||
description?: string;
|
||||
|
||||
@doc("Display name of product.")
|
||||
display_name?: string;
|
||||
|
||||
@doc("Capacity of product. For example, 4 people.")
|
||||
capacity?: string;
|
||||
|
||||
@doc("Image URL representing the product.")
|
||||
image?: string;
|
||||
}
|
||||
|
||||
@error
|
||||
model Error {
|
||||
status?: int32;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
model CatalogDictionaryOfArray {
|
||||
@doc("Dictionary of Array of product")
|
||||
productDictionaryOfArray?: Record<Product[]>;
|
||||
}
|
||||
|
||||
model CatalogDictionary {
|
||||
@doc("Dictionary of products")
|
||||
productDictionary?: Record<Product>;
|
||||
}
|
||||
|
||||
model CatalogArrayOfDictionary {
|
||||
@doc("Array of dictionary of products")
|
||||
productArrayOfDictionary?: Record<Product>[];
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"name": "@cadl-api-spec/complex-model-client",
|
||||
"author": "Microsoft Corporation",
|
||||
"description": "Some cool documentation.",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cadl-lang/compiler": "^0.37.0",
|
||||
"@cadl-lang/rest": "^0.19.0",
|
||||
"@cadl-lang/versioning": "^0.10.0",
|
||||
"@cadl-lang/prettier-plugin-cadl": "^0.5.17",
|
||||
"@azure-tools/cadl-azure-core": "^0.9.0",
|
||||
"@azure-tools/cadl-autorest": "^0.22.0",
|
||||
"@azure-tools/cadl-python": "^0.4.10",
|
||||
"prettier": "^2.7.1"
|
||||
},
|
||||
"private": true
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
import "@azure-tools/cadl-azure-core";
|
||||
import "@cadl-lang/rest";
|
||||
import "./models.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
|
||||
namespace ComplexModelClient;
|
||||
|
||||
@summary("Product Types")
|
||||
@doc("""
|
||||
The Products endpoint returns information about the Uber products offered at a
|
||||
given location. The response includes the display name and other details about
|
||||
each product, and lists the products in the proper display order.
|
||||
""")
|
||||
@route("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis")
|
||||
@get
|
||||
op List is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Subscription ID.")
|
||||
@path
|
||||
subscriptionId: "123456";
|
||||
|
||||
@doc("Resource Group ID.")
|
||||
@path
|
||||
resourceGroupName: string;
|
||||
},
|
||||
CatalogArray
|
||||
>;
|
||||
|
||||
@summary("Create products")
|
||||
@doc("Resets products.")
|
||||
@route("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis")
|
||||
@post
|
||||
op Create is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Subscription ID.")
|
||||
@path
|
||||
subscriptionId: string;
|
||||
|
||||
@doc("Resource Group ID.")
|
||||
@path
|
||||
resourceGroupName: string;
|
||||
|
||||
@doc("body Parameter")
|
||||
@body
|
||||
bodyParameter: CatalogDictionaryOfArray;
|
||||
},
|
||||
CatalogDictionary
|
||||
>;
|
||||
|
||||
@summary("Update products")
|
||||
@doc("Resets products.")
|
||||
@route("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis")
|
||||
@put
|
||||
op Update is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Subscription ID.")
|
||||
@path
|
||||
subscriptionId: string;
|
||||
|
||||
@doc("Resource Group ID.")
|
||||
@path
|
||||
resourceGroupName: string;
|
||||
|
||||
@doc("body Parameter")
|
||||
@body
|
||||
bodyParameter: CatalogArrayOfDictionary;
|
||||
},
|
||||
CatalogArray
|
||||
>;
|
|
@ -0,0 +1,267 @@
|
|||
{
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"title": "Complex Model Client",
|
||||
"description": "Some cool documentation.",
|
||||
"version": "2014-04-01-preview"
|
||||
},
|
||||
"host": "localhost:3000",
|
||||
"schemes": ["http"],
|
||||
"produces": ["application/json"],
|
||||
"consumes": ["application/json"],
|
||||
"paths": {
|
||||
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis": {
|
||||
"get": {
|
||||
"operationId": "list",
|
||||
"summary": "Product Types",
|
||||
"description": "The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order.",
|
||||
"parameters": [
|
||||
{
|
||||
"$ref": "#/parameters/SubscriptionIdParamterer"
|
||||
},
|
||||
{
|
||||
"name": "resourceGroupName",
|
||||
"in": "path",
|
||||
"description": "Resource Group ID.",
|
||||
"required": true,
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"$ref": "#/parameters/ApiVersionParameter"
|
||||
}
|
||||
],
|
||||
"tags": ["Redis"],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "A list of caches",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/CatalogArray"
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"description": "Unexpected error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"operationId": "create",
|
||||
"summary": "Create products",
|
||||
"description": "Resets products.",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "subscriptionId",
|
||||
"in": "path",
|
||||
"description": "Subscription ID.",
|
||||
"required": true,
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"name": "resourceGroupName",
|
||||
"in": "path",
|
||||
"description": "Resource Group ID.",
|
||||
"required": true,
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"name": "bodyParameter",
|
||||
"in": "body",
|
||||
"description": "body Parameter",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/CatalogDictionaryOfArray"
|
||||
}
|
||||
},
|
||||
{
|
||||
"$ref": "#/parameters/ApiVersionParameter"
|
||||
}
|
||||
],
|
||||
"tags": ["Redis"],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "A list of caches",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/CatalogDictionary"
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"description": "Unexpected error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"put": {
|
||||
"operationId": "update",
|
||||
"summary": "Update products",
|
||||
"description": "Resets products.",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "subscriptionId",
|
||||
"in": "path",
|
||||
"description": "Subscription ID.",
|
||||
"required": true,
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"name": "resourceGroupName",
|
||||
"in": "path",
|
||||
"description": "Resource Group ID.",
|
||||
"required": true,
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"name": "bodyParameter",
|
||||
"in": "body",
|
||||
"description": "body Parameter",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/CatalogArrayOfDictionary"
|
||||
}
|
||||
},
|
||||
{
|
||||
"$ref": "#/parameters/ApiVersionParameter"
|
||||
}
|
||||
],
|
||||
"tags": ["Redis"],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "A list of caches",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/CatalogArray"
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"description": "Unexpected error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Product": {
|
||||
"type": "object",
|
||||
"description": "The product documentation.",
|
||||
"properties": {
|
||||
"product_id": {
|
||||
"type": "string",
|
||||
"description": "Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles."
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "Description of product."
|
||||
},
|
||||
"display_name": {
|
||||
"type": "string",
|
||||
"description": "Display name of product."
|
||||
},
|
||||
"capacity": {
|
||||
"type": "string",
|
||||
"description": "Capacity of product. For example, 4 people.",
|
||||
"default": "100"
|
||||
},
|
||||
"image": {
|
||||
"type": "string",
|
||||
"description": "Image URL representing the product."
|
||||
}
|
||||
},
|
||||
"example": {
|
||||
"name": "Puma",
|
||||
"id": 1
|
||||
}
|
||||
},
|
||||
"CatalogDictionary": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"productDictionary": {
|
||||
"type": "object",
|
||||
"description": "Dictionary of products",
|
||||
"additionalProperties": {
|
||||
"$ref": "#/definitions/Product"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"CatalogArray": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"productArray": {
|
||||
"description": "Array of products",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Product"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"CatalogArrayOfDictionary": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"productArrayOfDictionary": {
|
||||
"description": "Array of dictionary of products",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"$ref": "#/definitions/Product"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"CatalogDictionaryOfArray": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"productDictionaryOfArray": {
|
||||
"type": "object",
|
||||
"description": "Dictionary of Array of product",
|
||||
"additionalProperties": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Product"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Error": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "integer",
|
||||
"format": "int32"
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"parameters": {
|
||||
"SubscriptionIdParamterer": {
|
||||
"name": "subscriptionId",
|
||||
"in": "path",
|
||||
"description": "Subscription ID.",
|
||||
"required": true,
|
||||
"type": "string",
|
||||
"enum": ["123456"],
|
||||
"x-ms-enum": {
|
||||
"modelAsString": false
|
||||
}
|
||||
},
|
||||
"ApiVersionParameter": {
|
||||
"name": "api-version",
|
||||
"in": "query",
|
||||
"description": "API ID.",
|
||||
"required": true,
|
||||
"type": "string",
|
||||
"enum": ["2014-04-01-preview"]
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
emitters:
|
||||
# "@azure-tools/cadl-autorest": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-python" to your package.json to generate Python code
|
||||
# "@azure-tools/cadl-python":
|
||||
# "basic-setup-py": true
|
||||
# "package-version":
|
||||
# "package-name":
|
||||
# "output-path":
|
||||
# Uncomment this line and add "@azure-tools/cadl-java" to your package.json to generate Java code
|
||||
# "@azure-tools/cadl-java": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-csharp" to your package.json to generate C# code
|
||||
# "@azure-tools/cadl-csharp": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-typescript" to your package.json to generate Typescript code
|
||||
# "@azure-tools/cadl-typescript": true
|
|
@ -0,0 +1,25 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "./routes.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
@service({
|
||||
title: "Microsoft Cognitive Language Service - Analyze Text Authoring",
|
||||
})
|
||||
@serviceVersion("2022-05-13")
|
||||
@server(
|
||||
"{ledgerEndpoint}",
|
||||
"The ConfidentialLedgerClient writes and retrieves ledger entries against the Confidential Ledger service.",
|
||||
{
|
||||
@doc("""
|
||||
The Confidential Ledger URL, for example
|
||||
https://contoso.confidentialledger.azure.com
|
||||
""")
|
||||
ledgerEndpoint: string,
|
||||
}
|
||||
)
|
||||
@doc("""
|
||||
The ConfidentialLedgerClient writes and retrieves ledger entries against the
|
||||
Confidential Ledger service.
|
||||
""")
|
||||
namespace Azure.Language.Authoring;
|
|
@ -0,0 +1,276 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "@azure-tools/cadl-azure-core";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Azure.Core;
|
||||
|
||||
namespace Azure.Language.Authoring;
|
||||
|
||||
enum ConfidentialLedgerQueryStateKnownValues {
|
||||
"Loading",
|
||||
"Ready",
|
||||
}
|
||||
|
||||
@knownValues(ConfidentialLedgerQueryStateKnownValues)
|
||||
model ConfidentialLedgerQueryState is string;
|
||||
|
||||
enum TransactionStateKnownValues {
|
||||
"Committed",
|
||||
"Pending",
|
||||
}
|
||||
|
||||
@knownValues(TransactionStateKnownValues)
|
||||
model TransactionState is string;
|
||||
|
||||
enum ConfidentialLedgerUserRoleNameKnownValues {
|
||||
"Administrator",
|
||||
"Contributor",
|
||||
"Reader",
|
||||
}
|
||||
|
||||
@knownValues(ConfidentialLedgerUserRoleNameKnownValues)
|
||||
model ConfidentialLedgerUserRoleName is string;
|
||||
|
||||
@doc("The governance script for the application.")
|
||||
model Constitution {
|
||||
@doc("SHA256 digest of the constitution script.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
digest: string;
|
||||
|
||||
@doc("Contents of the constitution.")
|
||||
script: string;
|
||||
}
|
||||
|
||||
@doc("An error response from Confidential Ledger.")
|
||||
@error
|
||||
model ConfidentialLedgerError {
|
||||
@doc("An error response from Confidential Ledger.")
|
||||
@visibility("read")
|
||||
error?: ConfidentialLedgerErrorBody;
|
||||
}
|
||||
|
||||
@doc("An error response from Confidential Ledger.")
|
||||
model ConfidentialLedgerErrorBody {
|
||||
@doc("The error code.")
|
||||
@visibility("read")
|
||||
code?: string;
|
||||
|
||||
@doc("The error message.")
|
||||
@visibility("read")
|
||||
message?: string;
|
||||
}
|
||||
|
||||
@doc("List of members in the consortium.")
|
||||
@pagedResult
|
||||
model Consortium {
|
||||
@items
|
||||
members: ConsortiumMember[];
|
||||
|
||||
@doc("Path from which to retrieve the next page of results.")
|
||||
@nextLink
|
||||
nextLink?: string;
|
||||
}
|
||||
|
||||
@doc("Describes a member of the consortium.")
|
||||
@resource("app/governance/members")
|
||||
model ConsortiumMember {
|
||||
@doc("PEM-encoded certificate associated with the member.")
|
||||
certificate: string;
|
||||
|
||||
@doc("Identifier assigned to the member.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
id: string;
|
||||
}
|
||||
|
||||
@doc("Information about the enclaves running the Confidential Ledger.")
|
||||
@resource("app/enclaveQuotes")
|
||||
model ConfidentialLedgerEnclaves {
|
||||
@doc("Id of the Confidential Ledger node responding to the request.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
currentNodeId: string;
|
||||
|
||||
@doc("Dictionary of enclave quotes, indexed by node id.")
|
||||
enclaveQuotes: Record<EnclaveQuote>;
|
||||
}
|
||||
|
||||
@doc("Contains the enclave quote.")
|
||||
model EnclaveQuote {
|
||||
@doc("ID assigned to this node.")
|
||||
nodeId: string;
|
||||
|
||||
@doc("MRENCLAVE value of the code running in the enclave.")
|
||||
mrenclave?: string;
|
||||
|
||||
@doc("Version of the quote presented.")
|
||||
quoteVersion: string;
|
||||
|
||||
@doc("Raw SGX quote, parsable by tools like Open Enclave's oeverify.")
|
||||
raw: string;
|
||||
}
|
||||
|
||||
@doc("Paginated collections returned in response to a query.")
|
||||
@pagedResult
|
||||
model PagedCollections {
|
||||
@items
|
||||
collections: Collection[];
|
||||
|
||||
@doc("Path from which to retrieve the next page of results.")
|
||||
@nextLink
|
||||
nextLink?: string;
|
||||
}
|
||||
|
||||
@doc("Identifier for collections.")
|
||||
@resource("app/collections")
|
||||
model Collection {
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
collectionId: string;
|
||||
}
|
||||
|
||||
@doc("Paginated ledger entries returned in response to a query.")
|
||||
@pagedResult
|
||||
model PagedLedgerEntries {
|
||||
@doc("State of a ledger query.")
|
||||
state: ConfidentialLedgerQueryState;
|
||||
|
||||
@doc("Path from which to retrieve the next page of results.")
|
||||
@nextLink
|
||||
nextLink?: string;
|
||||
|
||||
@doc("Array of ledger entries.")
|
||||
@items
|
||||
entries: LedgerEntry[];
|
||||
}
|
||||
|
||||
@doc("An entry in the ledger.")
|
||||
model LedgerEntry {
|
||||
@doc("Contents of the ledger entry.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
contents: string;
|
||||
|
||||
@visibility("read")
|
||||
collectionId?: string;
|
||||
|
||||
@doc("""
|
||||
A unique identifier for the state of the ledger. If returned as part of a
|
||||
LedgerEntry, it indicates the state from which the entry was read.
|
||||
""")
|
||||
@visibility("read")
|
||||
transactionId?: string;
|
||||
}
|
||||
|
||||
@doc("""
|
||||
Returned as a result of a write to the Confidential Ledger, the transaction id
|
||||
in the response indicates when the write will become durable.
|
||||
""")
|
||||
@resource("app/transactions")
|
||||
model LedgerWriteResult {
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
collectionId: string;
|
||||
}
|
||||
|
||||
@doc("""
|
||||
The result of querying for a ledger entry from an older transaction id. The
|
||||
ledger entry is available in the response only if the returned state is Ready.
|
||||
""")
|
||||
model LedgerQueryResult {
|
||||
@doc("State of a ledger query.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
state: ConfidentialLedgerQueryState;
|
||||
|
||||
@doc("""
|
||||
The ledger entry found as a result of the query. This is only available if the
|
||||
query is in Ready state.
|
||||
""")
|
||||
entry?: LedgerEntry;
|
||||
}
|
||||
|
||||
@doc("A receipt certifying the transaction at the specified id.")
|
||||
@resource("app/transactions/{transactionId}/receipt")
|
||||
model TransactionReceipt {
|
||||
receipt?: ReceiptContents;
|
||||
|
||||
@doc("State of a ledger query.")
|
||||
state: ConfidentialLedgerQueryState;
|
||||
|
||||
@doc("""
|
||||
A unique identifier for the state of the ledger. If returned as part of a
|
||||
LedgerEntry, it indicates the state from which the entry was read.
|
||||
""")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
transactionId: string;
|
||||
}
|
||||
|
||||
model ReceiptContents {
|
||||
cert?: string;
|
||||
leaf?: string;
|
||||
leafComponents?: ReceiptLeafComponents;
|
||||
nodeId: string;
|
||||
proof: ReceiptElement[];
|
||||
root?: string;
|
||||
serviceEndorsements?: string[];
|
||||
signature: string;
|
||||
}
|
||||
|
||||
model ReceiptLeafComponents {
|
||||
claimsDigest?: string;
|
||||
commitEvidence?: string;
|
||||
writeSetDigest?: string;
|
||||
}
|
||||
|
||||
model ReceiptElement {
|
||||
left?: string;
|
||||
right?: string;
|
||||
}
|
||||
|
||||
@doc("Response returned to a query for the transaction status")
|
||||
@resource("app/transactions/{transactionId}/status")
|
||||
model TransactionStatus {
|
||||
@doc("Represents the state of the transaction.")
|
||||
state: TransactionState;
|
||||
|
||||
@doc("""
|
||||
A unique identifier for the state of the ledger. If returned as part of a
|
||||
LedgerEntry, it indicates the state from which the entry was read.
|
||||
""")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
transactionId: string;
|
||||
}
|
||||
|
||||
@doc("Details about a Confidential Ledger user.")
|
||||
model LedgerUser {
|
||||
@doc("Represents an assignable role.")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
assignedRole: ConfidentialLedgerUserRoleName;
|
||||
|
||||
@doc("""
|
||||
Identifier for the user. This must either be an AAD object id or a certificate
|
||||
fingerprint.
|
||||
""")
|
||||
@visibility("read")
|
||||
userId?: string;
|
||||
}
|
||||
|
||||
@doc("An item in the Merkle proof.")
|
||||
model MerkleProofElement {
|
||||
left?: string;
|
||||
right?: string;
|
||||
}
|
||||
|
||||
@doc("Object for assigning a role to a user.")
|
||||
model RoleAssignment {
|
||||
@doc("Represents an assignable role.")
|
||||
roleName: ConfidentialLedgerUserRoleName;
|
||||
|
||||
@doc("Description of the role.")
|
||||
description?: string;
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"name": "@cadl-api-spec/microsoft-cognitive-language-service---analyze-text-authoring",
|
||||
"author": "Microsoft Corporation",
|
||||
"description": "The ConfidentialLedgerClient writes and retrieves ledger entries against the Confidential Ledger service.",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cadl-lang/compiler": "^0.37.0",
|
||||
"@cadl-lang/rest": "^0.19.0",
|
||||
"@cadl-lang/versioning": "^0.10.0",
|
||||
"@cadl-lang/prettier-plugin-cadl": "^0.5.17",
|
||||
"@azure-tools/cadl-azure-core": "^0.9.0",
|
||||
"@azure-tools/cadl-autorest": "^0.22.0",
|
||||
"@azure-tools/cadl-python": "^0.4.10",
|
||||
"prettier": "^2.7.1"
|
||||
},
|
||||
"private": true
|
||||
}
|
|
@ -0,0 +1,159 @@
|
|||
import "@azure-tools/cadl-azure-core";
|
||||
import "@cadl-lang/rest";
|
||||
import "./models.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
|
||||
namespace Azure.Language.Authoring;
|
||||
|
||||
@summary("Gets the constitution used for governance.")
|
||||
@doc("""
|
||||
The constitution is a script that assesses and applies proposals from
|
||||
consortium members.
|
||||
""")
|
||||
@route("/app/governance/constitution")
|
||||
@get
|
||||
op GetConstitution is Azure.Core.Foundations.Operation<{}, Constitution>;
|
||||
|
||||
@summary("Lists the consortium members.")
|
||||
@doc("Consortium members can manage the Confidential Ledger.")
|
||||
op ListConsortiumMembers is Azure.Core.ResourceList<ConsortiumMember>;
|
||||
|
||||
@summary("Gets quotes for all nodes of the Confidential Ledger.")
|
||||
@doc("""
|
||||
A quote is an SGX enclave measurement that can be used to verify the validity
|
||||
of a node and its enclave.
|
||||
""")
|
||||
op GetEnclaveQuotes is Azure.Core.ResourceRead<ConfidentialLedgerEnclaves>;
|
||||
|
||||
@summary("Retrieves a list of collection ids present in the Confidential Ledger")
|
||||
@doc("Collection ids are user-created collections of ledger entries")
|
||||
op ListCollections is Azure.Core.ResourceList<Collection>;
|
||||
|
||||
@summary("Gets ledger entries from a collection corresponding to a range.")
|
||||
@doc("""
|
||||
A collection id may optionally be specified. Only entries in the specified (or
|
||||
default) collection will be returned.
|
||||
""")
|
||||
@route("/app/transactions")
|
||||
@get
|
||||
op ListLedgerEntries is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The collection id.")
|
||||
@query
|
||||
collectionId: string;
|
||||
|
||||
@doc("Specify the first transaction ID in a range.")
|
||||
@query
|
||||
fromTransactionId: string;
|
||||
|
||||
@doc("Specify the last transaction ID in a range.")
|
||||
@query
|
||||
toTransactionId: string;
|
||||
},
|
||||
PagedLedgerEntries
|
||||
>;
|
||||
|
||||
@summary("Writes a ledger entry.")
|
||||
@doc("A collection id may optionally be specified.")
|
||||
op CreateLedgerEntry is Azure.Core.ResourceCreateWithServiceProvidedName<
|
||||
LedgerWriteResult,
|
||||
{
|
||||
parameters: {
|
||||
@doc("The collection id.")
|
||||
@query
|
||||
collectionId: string;
|
||||
};
|
||||
}
|
||||
>;
|
||||
|
||||
@summary("""
|
||||
Gets the ledger entry at the specified transaction id. A collection id may
|
||||
optionally be specified to indicate the collection from which to fetch the
|
||||
value.
|
||||
""")
|
||||
@doc("""
|
||||
To return older ledger entries, the relevant sections of the ledger must be
|
||||
read from disk and validated. To prevent blocking within the enclave, the
|
||||
response will indicate whether the entry is ready and part of the response, or
|
||||
if the loading is still ongoing.
|
||||
""")
|
||||
@route("/app/transactions/{transactionId}")
|
||||
@get
|
||||
op GetLedgerEntry is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The collection id.")
|
||||
@query
|
||||
collectionId: string;
|
||||
|
||||
@doc("Identifies a write transaction.")
|
||||
@path
|
||||
transactionId: string;
|
||||
},
|
||||
LedgerQueryResult
|
||||
>;
|
||||
|
||||
@summary("Gets a receipt certifying ledger contents at a particular transaction id.")
|
||||
@doc("Gets a receipt certifying ledger contents at a particular transaction id.")
|
||||
op GetReceipt is Azure.Core.ResourceRead<TransactionReceipt>;
|
||||
|
||||
@summary("Gets the status of an entry identified by a transaction id.")
|
||||
@doc("Gets the status of an entry identified by a transaction id.")
|
||||
op GetTransactionStatus is Azure.Core.ResourceRead<TransactionStatus>;
|
||||
|
||||
@summary("Gets the current value available in the ledger.")
|
||||
@doc("A collection id may optionally be specified.")
|
||||
@route("/app/transactions/current")
|
||||
@get
|
||||
op GetCurrentLedgerEntry is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The collection id.")
|
||||
@query
|
||||
collectionId: string;
|
||||
},
|
||||
LedgerEntry
|
||||
>;
|
||||
|
||||
@summary("Deletes a user from the Confidential Ledger.")
|
||||
@doc("Deletes a user from the Confidential Ledger.")
|
||||
@route("/app/users/{userId}")
|
||||
@delete
|
||||
op DeleteUser is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The user id, either an AAD object ID or certificate fingerprint.")
|
||||
@path
|
||||
userId: string;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@summary("Gets a user.")
|
||||
@doc("Gets a user.")
|
||||
@route("/app/users/{userId}")
|
||||
@get
|
||||
op GetUser is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The user id, either an AAD object ID or certificate fingerprint.")
|
||||
@path
|
||||
userId: string;
|
||||
},
|
||||
LedgerUser
|
||||
>;
|
||||
|
||||
@summary("Adds a user or updates a user's fields.")
|
||||
@doc("A JSON merge patch is applied for existing users")
|
||||
@route("/app/users/{userId}")
|
||||
@patch
|
||||
op CreateOrUpdateUser is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("The user id, either an AAD object ID or certificate fingerprint.")
|
||||
@path
|
||||
userId: string;
|
||||
|
||||
@doc("Details about a Confidential Ledger user.")
|
||||
@body
|
||||
userDetails: LedgerUser;
|
||||
},
|
||||
LedgerUser
|
||||
>;
|
|
@ -0,0 +1,10 @@
|
|||
```yaml
|
||||
require:
|
||||
- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/confidentialledger/data-plane/readme.md
|
||||
title: Microsoft Cognitive Language Service - Analyze Text Authoring
|
||||
clear-output-folder: false
|
||||
guessResourceKey: true
|
||||
isAzureSpec: true
|
||||
namespace: "Azure.Language.Authoring"
|
||||
tag: package-2022-05-13-ledger
|
||||
```
|
|
@ -0,0 +1,14 @@
|
|||
emitters:
|
||||
# "@azure-tools/cadl-autorest": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-python" to your package.json to generate Python code
|
||||
# "@azure-tools/cadl-python":
|
||||
# "basic-setup-py": true
|
||||
# "package-version":
|
||||
# "package-name":
|
||||
# "output-path":
|
||||
# Uncomment this line and add "@azure-tools/cadl-java" to your package.json to generate Java code
|
||||
# "@azure-tools/cadl-java": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-csharp" to your package.json to generate C# code
|
||||
# "@azure-tools/cadl-csharp": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-typescript" to your package.json to generate Typescript code
|
||||
# "@azure-tools/cadl-typescript": true
|
|
@ -0,0 +1,22 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "./routes.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
@service({
|
||||
title: "NotificationHubsClient",
|
||||
})
|
||||
@serviceVersion("2020-06-01")
|
||||
@server(
|
||||
"{namespaceBaseUrl}",
|
||||
"The Notification Hubs client performs operations to register and query devices, and send notifications",
|
||||
{
|
||||
@doc("The namespace name, for example https://mynamespace.servicebus.windows.net.")
|
||||
namespaceBaseUrl: string,
|
||||
}
|
||||
)
|
||||
@doc("""
|
||||
The Notification Hubs client performs operations to register and query devices,
|
||||
and send notifications
|
||||
""")
|
||||
namespace NotificationHubsClient;
|
|
@ -0,0 +1,358 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "@azure-tools/cadl-azure-core";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Azure.Core;
|
||||
|
||||
namespace NotificationHubsClient;
|
||||
|
||||
enum MSApiVersionTypeKnownValues {
|
||||
TwoThousandFifteen01: "2015-01",
|
||||
TwoThousandFifteen04: "2015-04",
|
||||
TwoThousandFifteen08: "2015-08",
|
||||
TwoThousandSixteen07: "2016-07",
|
||||
}
|
||||
|
||||
@knownValues(MSApiVersionTypeKnownValues)
|
||||
model MSApiVersionType is string;
|
||||
|
||||
enum NotificationHubContentModelTypeKnownValues {
|
||||
ApplicationXml: "application/xml",
|
||||
}
|
||||
|
||||
@knownValues(NotificationHubContentModelTypeKnownValues)
|
||||
model NotificationHubContentModelType is string;
|
||||
|
||||
enum NotificationHubDescriptionModelXmlnsIKnownValues {
|
||||
HttpWwwW3Org2001XMLSchemaInstance: "http://www.w3.org/2001/XMLSchema-instance",
|
||||
}
|
||||
|
||||
@knownValues(NotificationHubDescriptionModelXmlnsIKnownValues)
|
||||
model NotificationHubDescriptionModelXmlnsI is string;
|
||||
|
||||
enum NotificationHubDescriptionModelAuthorizationRulesItemITypeKnownValues {
|
||||
HttpWwwW3Org2001XMLSchemaInstance: "http://www.w3.org/2001/XMLSchema-instance",
|
||||
}
|
||||
|
||||
@knownValues(
|
||||
NotificationHubDescriptionModelAuthorizationRulesItemITypeKnownValues
|
||||
)
|
||||
model NotificationHubDescriptionModelAuthorizationRulesItemIType is string;
|
||||
|
||||
enum NotificationHubDescriptionModelAuthorizationRulesItemClaimTypeKnownValues {
|
||||
"SharedAccessAuthorizationRule",
|
||||
}
|
||||
|
||||
@knownValues(
|
||||
NotificationHubDescriptionModelAuthorizationRulesItemClaimTypeKnownValues
|
||||
)
|
||||
model NotificationHubDescriptionModelAuthorizationRulesItemClaimType is string;
|
||||
|
||||
enum RegistrationEntryModelXmlnsMKnownValues {
|
||||
HttpSchemasMicrosoftComAdo200708DataservicesMetadata: "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
|
||||
}
|
||||
|
||||
@knownValues(RegistrationEntryModelXmlnsMKnownValues)
|
||||
model RegistrationEntryModelXmlnsM is string;
|
||||
|
||||
enum PlatformTypeKnownValues {
|
||||
Apns: "apns",
|
||||
Wns: "wns",
|
||||
Gcm: "gcm",
|
||||
Baidu: "baidu",
|
||||
Adm: "adm",
|
||||
}
|
||||
|
||||
@knownValues(PlatformTypeKnownValues)
|
||||
model PlatformType is string;
|
||||
|
||||
enum InstallationPatchTypeKnownValues {
|
||||
Add: "add",
|
||||
Remove: "remove",
|
||||
Replace: "replace",
|
||||
}
|
||||
|
||||
@knownValues(InstallationPatchTypeKnownValues)
|
||||
model InstallationPatchType is string;
|
||||
|
||||
enum FormatParameterTypeKnownValues {
|
||||
Apple: "apple",
|
||||
Baidu: "baidu",
|
||||
Gcm: "gcm",
|
||||
Windows: "windows",
|
||||
}
|
||||
|
||||
@knownValues(FormatParameterTypeKnownValues)
|
||||
model FormatParameterType is string;
|
||||
|
||||
enum RegistrationContentModelTypeKnownValues {
|
||||
ApplicationXml: "application/xml",
|
||||
}
|
||||
|
||||
@knownValues(RegistrationContentModelTypeKnownValues)
|
||||
model RegistrationContentModelType is string;
|
||||
|
||||
enum AppleRegistrationContentModelXmlnsIKnownValues {
|
||||
HttpWwwW3Org2001XMLSchemaInstance: "http://www.w3.org/2001/XMLSchema-instance",
|
||||
}
|
||||
|
||||
@knownValues(AppleRegistrationContentModelXmlnsIKnownValues)
|
||||
model AppleRegistrationContentModelXmlnsI is string;
|
||||
|
||||
enum AppleTemplateRegistrationContentModelXmlnsIKnownValues {
|
||||
HttpWwwW3Org2001XMLSchemaInstance: "http://www.w3.org/2001/XMLSchema-instance",
|
||||
}
|
||||
|
||||
@knownValues(AppleTemplateRegistrationContentModelXmlnsIKnownValues)
|
||||
model AppleTemplateRegistrationContentModelXmlnsI is string;
|
||||
|
||||
enum BaiduRegistrationContentModelXmlnsIKnownValues {
|
||||
HttpWwwW3Org2001XMLSchemaInstance: "http://www.w3.org/2001/XMLSchema-instance",
|
||||
}
|
||||
|
||||
@knownValues(BaiduRegistrationContentModelXmlnsIKnownValues)
|
||||
model BaiduRegistrationContentModelXmlnsI is string;
|
||||
|
||||
enum BaiduTemplateRegistrationContentModelXmlnsIKnownValues {
|
||||
HttpWwwW3Org2001XMLSchemaInstance: "http://www.w3.org/2001/XMLSchema-instance",
|
||||
}
|
||||
|
||||
@knownValues(BaiduTemplateRegistrationContentModelXmlnsIKnownValues)
|
||||
model BaiduTemplateRegistrationContentModelXmlnsI is string;
|
||||
|
||||
enum GcmRegistrationContentModelXmlnsIKnownValues {
|
||||
HttpWwwW3Org2001XMLSchemaInstance: "http://www.w3.org/2001/XMLSchema-instance",
|
||||
}
|
||||
|
||||
@knownValues(GcmRegistrationContentModelXmlnsIKnownValues)
|
||||
model GcmRegistrationContentModelXmlnsI is string;
|
||||
|
||||
enum GcmTemplateRegistrationContentModelXmlnsIKnownValues {
|
||||
HttpWwwW3Org2001XMLSchemaInstance: "http://www.w3.org/2001/XMLSchema-instance",
|
||||
}
|
||||
|
||||
@knownValues(GcmTemplateRegistrationContentModelXmlnsIKnownValues)
|
||||
model GcmTemplateRegistrationContentModelXmlnsI is string;
|
||||
|
||||
enum WindowsRegistrationContentModelXmlnsIKnownValues {
|
||||
HttpWwwW3Org2001XMLSchemaInstance: "http://www.w3.org/2001/XMLSchema-instance",
|
||||
}
|
||||
|
||||
@knownValues(WindowsRegistrationContentModelXmlnsIKnownValues)
|
||||
model WindowsRegistrationContentModelXmlnsI is string;
|
||||
|
||||
enum WindowsTemplateRegistrationContentModelXmlnsIKnownValues {
|
||||
HttpWwwW3Org2001XMLSchemaInstance: "http://www.w3.org/2001/XMLSchema-instance",
|
||||
}
|
||||
|
||||
@knownValues(WindowsTemplateRegistrationContentModelXmlnsIKnownValues)
|
||||
model WindowsTemplateRegistrationContentModelXmlnsI is string;
|
||||
|
||||
enum ApiVersionTypeKnownValues {
|
||||
TwoThousandFifteen01: "2015-01",
|
||||
TwoThousandFifteen04: "2015-04",
|
||||
TwoThousandFifteen08: "2015-08",
|
||||
TwoThousandSixteen07: "2016-07",
|
||||
TwoThousandTwenty06: "2020-06",
|
||||
}
|
||||
|
||||
@knownValues(ApiVersionTypeKnownValues)
|
||||
model ApiVersionType is string;
|
||||
|
||||
enum ContentType {
|
||||
ApplicationJsonCharsetUtf8: "application/json;charset=utf-8",
|
||||
ApplicationXmlCharsetUtf8: "application/xml;charset=utf-8",
|
||||
}
|
||||
|
||||
model NotificationHubEntryModel {
|
||||
content?: NotificationHubContentModel;
|
||||
}
|
||||
|
||||
model NotificationHubContentModel {
|
||||
type?: NotificationHubContentModelType;
|
||||
NotificationHubDescription?: NotificationHubDescriptionModel;
|
||||
}
|
||||
|
||||
model NotificationHubDescriptionModel {
|
||||
"xmlns:i"?: NotificationHubDescriptionModelXmlnsI;
|
||||
RegistrationTtl?: string;
|
||||
Location?: string;
|
||||
ApnsCredential?: PropertyBagModelItem[];
|
||||
GcmCredential?: PropertyBagModelItem[];
|
||||
WnsCredential?: PropertyBagModelItem[];
|
||||
AuthorizationRules?: NotificationHubDescriptionModelAuthorizationRulesItem[];
|
||||
}
|
||||
|
||||
model PropertyBagModelItem {
|
||||
Name?: string;
|
||||
Value?: string;
|
||||
}
|
||||
|
||||
model NotificationHubDescriptionModelAuthorizationRulesItem {
|
||||
"i:type"?: NotificationHubDescriptionModelAuthorizationRulesItemIType;
|
||||
ClaimType?: NotificationHubDescriptionModelAuthorizationRulesItemClaimType;
|
||||
ClaimValue?: string;
|
||||
Rights?: string[];
|
||||
CreatedTime?: string;
|
||||
ModifiedTime?: string;
|
||||
KeyName?: string;
|
||||
PrimaryKey?: string;
|
||||
SecondaryKey?: string;
|
||||
}
|
||||
|
||||
model RegistrationEntryModel {
|
||||
content?: NotificationHubContentModel;
|
||||
"xmlns:m"?: RegistrationEntryModelXmlnsM;
|
||||
"m:etag"?: string;
|
||||
}
|
||||
|
||||
@resource("{hubName}/installations/{installationId}")
|
||||
model InstallationModel {
|
||||
@doc("Installation Unique Identifier")
|
||||
// FIXME: (resource-key-guessing) - Verify that this property is the resource key, if not please update the model with the right one
|
||||
@key
|
||||
installationId: string;
|
||||
|
||||
@doc("The user ID for the installation")
|
||||
userId?: string;
|
||||
|
||||
@doc("The date when the installation was made inactivate by the PNS.")
|
||||
@visibility("read")
|
||||
lastActiveOn?: string;
|
||||
|
||||
@doc("Date in W3C format of last update to this installation.")
|
||||
@visibility("read")
|
||||
lastUpdate?: string;
|
||||
|
||||
@doc("PNS Platform for the installation")
|
||||
platform: PlatformType;
|
||||
|
||||
@doc("The unique device handle for the PNS.")
|
||||
pushChannel: string;
|
||||
|
||||
@doc("This is true if the PNS expired the channel.")
|
||||
@visibility("read")
|
||||
expiredPushChannel?: boolean;
|
||||
|
||||
@doc("The tags for the installation for targeting")
|
||||
tags?: string[];
|
||||
|
||||
@doc("Set of named templates associated with the installation.")
|
||||
templates?: Record<InstallationTemplateModel>;
|
||||
|
||||
@doc("""
|
||||
Set of secondary tiles associated with the installation. Applies only to the
|
||||
'wns' platform.
|
||||
""")
|
||||
secondaryTiles?: Record<InstallationSecondaryTileModel>;
|
||||
}
|
||||
|
||||
model InstallationTemplateModel {
|
||||
@doc("Template for the body of the notification.")
|
||||
body: string;
|
||||
|
||||
@doc("""
|
||||
Set of named headers associated with the template. Header values can contain
|
||||
template parameters.
|
||||
""")
|
||||
headers?: Record<string>;
|
||||
|
||||
@doc("Template expression evaluating in W3D date format.")
|
||||
expiry?: string;
|
||||
|
||||
@doc("The tags for the installation for targeting")
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
model InstallationSecondaryTileModel {
|
||||
@doc("ChannelUri for the secondary tile. Applies only to the 'wns' platform.")
|
||||
pushChannel: string;
|
||||
|
||||
@doc("The tags for the installation for targeting")
|
||||
tags?: string[];
|
||||
|
||||
@doc("""
|
||||
Set of named templates associated with the secondary tile. Applies only to the
|
||||
'wns' platform.
|
||||
""")
|
||||
templates?: Record<InstallationTemplateModel>;
|
||||
}
|
||||
|
||||
model InstallationPatchModelItem {
|
||||
"op": InstallationPatchType;
|
||||
path: string;
|
||||
value?: string;
|
||||
}
|
||||
|
||||
model RegistrationContentModel {
|
||||
type?: RegistrationContentModelType;
|
||||
AppleRegistrationDescription?: AppleRegistrationContentModel;
|
||||
AppleTemplateRegistrationDescription?: AppleTemplateRegistrationContentModel;
|
||||
BaiduRegistrationDescription?: BaiduRegistrationContentModel;
|
||||
BaiduTemplateRegistrationDescription?: BaiduTemplateRegistrationContentModel;
|
||||
GcmRegistrationDescription?: GcmRegistrationContentModel;
|
||||
GcmTemplateRegistrationDescription?: GcmTemplateRegistrationContentModel;
|
||||
WindowsRegistrationDescription?: WindowsRegistrationContentModel;
|
||||
WindowsTemplateRegistrationDescription?: WindowsTemplateRegistrationContentModel;
|
||||
}
|
||||
|
||||
model AppleRegistrationContentModel {
|
||||
"xmlns:i"?: AppleRegistrationContentModelXmlnsI;
|
||||
Tags?: string;
|
||||
DeviceToken: string;
|
||||
}
|
||||
|
||||
model AppleTemplateRegistrationContentModel {
|
||||
"xmlns:i"?: AppleTemplateRegistrationContentModelXmlnsI;
|
||||
Tags?: string;
|
||||
DeviceToken: string;
|
||||
BodyTemplate: string;
|
||||
Expiry?: string;
|
||||
}
|
||||
|
||||
model BaiduRegistrationContentModel {
|
||||
"xmlns:i"?: BaiduRegistrationContentModelXmlnsI;
|
||||
Tags?: string;
|
||||
BaiduUserId: string;
|
||||
BaiduChannelId: string;
|
||||
}
|
||||
|
||||
model BaiduTemplateRegistrationContentModel {
|
||||
"xmlns:i"?: BaiduTemplateRegistrationContentModelXmlnsI;
|
||||
Tags?: string;
|
||||
BaiduUserId: string;
|
||||
BaiduChannelId: string;
|
||||
BodyTemplate: string;
|
||||
}
|
||||
|
||||
model GcmRegistrationContentModel {
|
||||
"xmlns:i"?: GcmRegistrationContentModelXmlnsI;
|
||||
Tags?: string;
|
||||
GcmRegistrationId?: string;
|
||||
}
|
||||
|
||||
model GcmTemplateRegistrationContentModel {
|
||||
"xmlns:i"?: GcmTemplateRegistrationContentModelXmlnsI;
|
||||
Tags?: string;
|
||||
GcmRegistrationId: string;
|
||||
BodyTemplate: string;
|
||||
}
|
||||
|
||||
model WindowsRegistrationContentModel {
|
||||
"xmlns:i"?: WindowsRegistrationContentModelXmlnsI;
|
||||
Tags?: string;
|
||||
ChannelUri: string;
|
||||
}
|
||||
|
||||
model WindowsTemplateRegistrationContentModel {
|
||||
"xmlns:i"?: WindowsTemplateRegistrationContentModelXmlnsI;
|
||||
Tags?: string;
|
||||
ChannelUri: string;
|
||||
BodyTemplate: string;
|
||||
WnsHeaders?: WindowsTemplateRegistrationContentModelWnsHeadersItem[];
|
||||
}
|
||||
|
||||
model WindowsTemplateRegistrationContentModelWnsHeadersItem {
|
||||
Header?: string;
|
||||
Value?: string;
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"name": "@cadl-api-spec/notificationhubsclient",
|
||||
"author": "Microsoft Corporation",
|
||||
"description": "The Notification Hubs client performs operations to register and query devices, and send notifications",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cadl-lang/compiler": "^0.37.0",
|
||||
"@cadl-lang/rest": "^0.19.0",
|
||||
"@cadl-lang/versioning": "^0.10.0",
|
||||
"@cadl-lang/prettier-plugin-cadl": "^0.5.17",
|
||||
"@azure-tools/cadl-azure-core": "^0.9.0",
|
||||
"@azure-tools/cadl-autorest": "^0.22.0",
|
||||
"@azure-tools/cadl-python": "^0.4.10",
|
||||
"prettier": "^2.7.1"
|
||||
},
|
||||
"private": true
|
||||
}
|
|
@ -0,0 +1,524 @@
|
|||
import "@azure-tools/cadl-azure-core";
|
||||
import "@cadl-lang/rest";
|
||||
import "./models.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
|
||||
namespace NotificationHubsClient;
|
||||
|
||||
@doc("Deletes a notification hub.")
|
||||
@route("/{hubName}")
|
||||
@delete
|
||||
op DeleteNotificationHub is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Retrieves information about a notification hub.")
|
||||
@route("/{hubName}")
|
||||
@get
|
||||
op GetNotificationHub is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
|
||||
@doc("Accept header")
|
||||
@header
|
||||
Accept: "application/atom+xml;type=entry;charset=utf-8";
|
||||
},
|
||||
NotificationHubEntryModel | void
|
||||
>;
|
||||
|
||||
@doc("Create or update a notification hub.")
|
||||
@route("/{hubName}")
|
||||
@put
|
||||
op CreateOrUpdateNotificationHub is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
|
||||
@doc("ETag as returned by creation, update, and retrieval, or * (overwrite).")
|
||||
@header
|
||||
"If-Match": string;
|
||||
@body body: NotificationHubEntryModel;
|
||||
|
||||
@doc("Accept header")
|
||||
@header
|
||||
Accept: "application/atom+xml;type=entry;charset=utf-8";
|
||||
},
|
||||
NotificationHubEntryModel | void
|
||||
>;
|
||||
|
||||
@doc("Retrieves all registrations with a specific tag.")
|
||||
@route("/{hubName}/tags/{tag}/registrations")
|
||||
@get
|
||||
op GetRegistrationsByTag is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
|
||||
@doc("The path for the tag to query")
|
||||
@path
|
||||
tag: string;
|
||||
|
||||
@doc("""
|
||||
Contains the token to continue the enumeration of registrations, in case there
|
||||
are more.
|
||||
""")
|
||||
@query
|
||||
ContinuationToken: string;
|
||||
|
||||
@doc("OData top parameter")
|
||||
@query
|
||||
$top: string;
|
||||
|
||||
@doc("Accept header")
|
||||
@header
|
||||
Accept: "application/atom+xml;type=entry;charset=utf-8";
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Create a registration ID")
|
||||
@route("/{hubName}/registrationIDs")
|
||||
@post
|
||||
op CreateRegistrationId is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get registrations by the specified criteria")
|
||||
@route("/{hubName}/registrations")
|
||||
@get
|
||||
op GetRegistrations is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
|
||||
@doc("""
|
||||
Contains the token to continue the enumeration of registrations, in case there
|
||||
are more.
|
||||
""")
|
||||
@query
|
||||
ContinuationToken: string;
|
||||
|
||||
@doc("OData filter parameter")
|
||||
@query
|
||||
$filter: string;
|
||||
|
||||
@doc("OData top parameter")
|
||||
@query
|
||||
$top: string;
|
||||
|
||||
@doc("Accept header")
|
||||
@header
|
||||
Accept: "application/atom+xml;type=entry;charset=utf-8";
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Creates a registration")
|
||||
@route("/{hubName}/registrations")
|
||||
@post
|
||||
op CreateRegistration is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
|
||||
@doc("Accept header")
|
||||
@header
|
||||
Accept: "application/atom+xml;type=entry;charset=utf-8";
|
||||
},
|
||||
RegistrationEntryModel | void
|
||||
>;
|
||||
|
||||
@doc("Deletes a registration")
|
||||
@route("/{hubName}/registrations/{registrationId}")
|
||||
@delete
|
||||
op DeleteRegistration is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Registration ID parameter")
|
||||
@path
|
||||
registrationId: string;
|
||||
|
||||
@doc("ETag as returned by creation, update, and retrieval, or * (overwrite).")
|
||||
@header
|
||||
"If-Match": string;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get a registration by registration ID")
|
||||
@route("/{hubName}/registrations/{registrationId}")
|
||||
@get
|
||||
op GetRegistration is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Registration ID parameter")
|
||||
@path
|
||||
registrationId: string;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
|
||||
@doc("Accept header")
|
||||
@header
|
||||
Accept: "application/atom+xml;type=entry;charset=utf-8";
|
||||
},
|
||||
RegistrationEntryModel | void
|
||||
>;
|
||||
|
||||
@doc("Create or update a registration")
|
||||
@route("/{hubName}/registrations/{registrationId}")
|
||||
@put
|
||||
op CreateOrUpdateRegistration is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Registration ID parameter")
|
||||
@path
|
||||
registrationId: string;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
@body body: RegistrationEntryModel;
|
||||
|
||||
@doc("Accept header")
|
||||
@header
|
||||
Accept: "application/atom+xml;type=entry;charset=utf-8";
|
||||
},
|
||||
RegistrationEntryModel | void
|
||||
>;
|
||||
|
||||
@summary("Delete Installation")
|
||||
@doc("Delete an installation by ID")
|
||||
@route("/{hubName}/installations/{installationId}")
|
||||
@delete
|
||||
op DeleteInstallation is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Installation ID parameter")
|
||||
@path
|
||||
installationId: string;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Get an Installation by Installation ID")
|
||||
op GetInstallation is Azure.Core.ResourceRead<
|
||||
InstallationModel,
|
||||
{
|
||||
parameters: {
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
};
|
||||
}
|
||||
>;
|
||||
|
||||
@doc("""
|
||||
Azure Notification Hubs supports partial updates to an installation using the
|
||||
JSON-Patch standard in [RFC6902](https://tools.ietf.org/html/rfc6902).
|
||||
""")
|
||||
op PatchInstallation is Azure.Core.ResourceCreateOrUpdate<
|
||||
InstallationModel,
|
||||
{
|
||||
parameters: {
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
};
|
||||
}
|
||||
>;
|
||||
|
||||
@doc("Creates or overwrites an installation.")
|
||||
op CreateOrUpdateInstallation is Azure.Core.ResourceCreateOrReplace<
|
||||
InstallationModel,
|
||||
{
|
||||
parameters: {
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
};
|
||||
}
|
||||
>;
|
||||
|
||||
@doc("Sends a notification to the specified targets.")
|
||||
@route("/{hubName}/messages")
|
||||
@post
|
||||
op SendMessage is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
|
||||
@doc("Device handle for the PNS")
|
||||
@header
|
||||
"ServiceBusNotification-DeviceHandle": string;
|
||||
|
||||
@doc("Platform type for the notification")
|
||||
@header
|
||||
"ServiceBusNotification-Format": FormatParameterType;
|
||||
|
||||
@doc("Notification message tags for targeting")
|
||||
@header
|
||||
"ServiceBusNotification-Tags": string;
|
||||
|
||||
@doc("Direct Send")
|
||||
@query
|
||||
direct: boolean;
|
||||
|
||||
@doc("The apns-topic header")
|
||||
@header
|
||||
"apns-topic": string;
|
||||
|
||||
@doc("The apns-priority header")
|
||||
@header
|
||||
"apns-priority": string;
|
||||
|
||||
@doc("The apns-push-type header")
|
||||
@header
|
||||
"apns-push-type": string;
|
||||
|
||||
@doc(" X-WNS-Cache-Policy header parameter")
|
||||
@header
|
||||
"X-WNS-Cache-Policy": string;
|
||||
|
||||
@doc("X-WNS-PRIORITY header parameter")
|
||||
@header
|
||||
"X-WNS-PRIORITY": string;
|
||||
|
||||
@doc("X-WNS-RequestForStatus header parameter")
|
||||
@header
|
||||
"X-WNS-RequestForStatus": string;
|
||||
|
||||
@doc("X-WNS-Tag header parameter")
|
||||
@header
|
||||
"X-WNS-Tag": string;
|
||||
|
||||
@doc("X-WNS-TTL header parameter")
|
||||
@header
|
||||
"X-WNS-TTL": string;
|
||||
|
||||
@doc("X-WNS-Type header parameter")
|
||||
@header
|
||||
"X-WNS-Type": string;
|
||||
|
||||
@doc("Upload file type")
|
||||
@header
|
||||
"Content-Type": ContentType;
|
||||
|
||||
@doc("The notification message body")
|
||||
@body
|
||||
body: string;
|
||||
},
|
||||
void
|
||||
>;
|
||||
|
||||
@doc("Sends a notification to the specified targets.")
|
||||
@route("/{hubName}/messages")
|
||||
@post
|
||||
op SendMessage is Azure.Core.Foundations.Operation<
|
||||
{
|
||||
@doc("Notification Hub Name")
|
||||
@path
|
||||
hubName: string;
|
||||
|
||||
@doc("API Version")
|
||||
@header
|
||||
"x-ms-version": MSApiVersionType;
|
||||
|
||||
@doc("Authorization Header value")
|
||||
@header
|
||||
Authorization: string;
|
||||
|
||||
@doc("Device handle for the PNS")
|
||||
@header
|
||||
"ServiceBusNotification-DeviceHandle": string;
|
||||
|
||||
@doc("Platform type for the notification")
|
||||
@header
|
||||
"ServiceBusNotification-Format": FormatParameterType;
|
||||
|
||||
@doc("Notification message tags for targeting")
|
||||
@header
|
||||
"ServiceBusNotification-Tags": string;
|
||||
|
||||
@doc("Direct Send")
|
||||
@query
|
||||
direct: boolean;
|
||||
|
||||
@doc("The apns-topic header")
|
||||
@header
|
||||
"apns-topic": string;
|
||||
|
||||
@doc("The apns-priority header")
|
||||
@header
|
||||
"apns-priority": string;
|
||||
|
||||
@doc("The apns-push-type header")
|
||||
@header
|
||||
"apns-push-type": string;
|
||||
|
||||
@doc(" X-WNS-Cache-Policy header parameter")
|
||||
@header
|
||||
"X-WNS-Cache-Policy": string;
|
||||
|
||||
@doc("X-WNS-PRIORITY header parameter")
|
||||
@header
|
||||
"X-WNS-PRIORITY": string;
|
||||
|
||||
@doc("X-WNS-RequestForStatus header parameter")
|
||||
@header
|
||||
"X-WNS-RequestForStatus": string;
|
||||
|
||||
@doc("X-WNS-Tag header parameter")
|
||||
@header
|
||||
"X-WNS-Tag": string;
|
||||
|
||||
@doc("X-WNS-TTL header parameter")
|
||||
@header
|
||||
"X-WNS-TTL": string;
|
||||
|
||||
@doc("X-WNS-Type header parameter")
|
||||
@header
|
||||
"X-WNS-Type": string;
|
||||
|
||||
@doc("Upload file type")
|
||||
@header
|
||||
"Content-Type": ContentType;
|
||||
|
||||
@doc("The notification message body")
|
||||
@body
|
||||
body: string;
|
||||
},
|
||||
void
|
||||
>;
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,14 @@
|
|||
emitters:
|
||||
# "@azure-tools/cadl-autorest": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-python" to your package.json to generate Python code
|
||||
# "@azure-tools/cadl-python":
|
||||
# "basic-setup-py": true
|
||||
# "package-version":
|
||||
# "package-name":
|
||||
# "output-path":
|
||||
# Uncomment this line and add "@azure-tools/cadl-java" to your package.json to generate Java code
|
||||
# "@azure-tools/cadl-java": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-csharp" to your package.json to generate C# code
|
||||
# "@azure-tools/cadl-csharp": true
|
||||
# Uncomment this line and add "@azure-tools/cadl-typescript" to your package.json to generate Typescript code
|
||||
# "@azure-tools/cadl-typescript": true
|
|
@ -0,0 +1,15 @@
|
|||
import "@cadl-lang/rest";
|
||||
import "./routes.cadl";
|
||||
|
||||
using Cadl.Rest;
|
||||
using Cadl.Http;
|
||||
@service({
|
||||
title: "OpenAI",
|
||||
})
|
||||
@serviceVersion("2022-03-01-preview")
|
||||
@server(
|
||||
"https://{endpoint}/openai",
|
||||
"Azure OpenAI APIs for completions and search"
|
||||
)
|
||||
@doc("Azure OpenAI APIs for completions and search")
|
||||
namespace Azure.AI.OpenAI;
|
|
@ -0,0 +1,189 @@
|
|||
import "@cadl-lang/rest";
|
||||
|
||||
using Cadl.Rest;
|
||||
|
||||
namespace Azure.AI.OpenAI;
|
||||
|
||||
model Paths1Vtxb06DeploymentsDeploymentIdCompletionsPostRequestbodyContentApplicationJsonSchema {
|
||||
@doc("""
|
||||
An optional prompt to complete from, encoded as a string, a list of strings, or
|
||||
a list of token lists. Defaults to <|endoftext|>. The prompt to complete from.
|
||||
If you would like to provide multiple prompts, use the POST variant of this
|
||||
method. Note that <|endoftext|> is the document separator that the model sees
|
||||
during training, so if a prompt is not specified the model will generate as if
|
||||
from the beginning of a new document. Maximum allowed size of string list is
|
||||
2048.
|
||||
""")
|
||||
prompt?: PostContentSchemaPrompt;
|
||||
|
||||
@doc("The maximum number of tokens to generate. Has minimum of 0.")
|
||||
max_tokens?: int32;
|
||||
|
||||
@doc("""
|
||||
What sampling temperature to use. Higher values means the model will take more
|
||||
risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones
|
||||
with a well-defined answer.
|
||||
We generally recommend using this or `top_p` but
|
||||
not both.
|
||||
Minimum of 0 and maximum of 2 allowed.
|
||||
|
||||
""")
|
||||
temperature?: float32;
|
||||
|
||||
@doc("""
|
||||
An alternative to sampling with temperature, called nucleus sampling, where the
|
||||
model considers the results of the tokens with top_p probability mass. So 0.1
|
||||
means only the tokens comprising the top 10% probability mass are
|
||||
considered.
|
||||
We generally recommend using this or `temperature` but not
|
||||
both.
|
||||
Minimum of 0 and maximum of 1 allowed.
|
||||
|
||||
""")
|
||||
top_p?: float32;
|
||||
|
||||
@doc("""
|
||||
Defaults to null. Modify the likelihood of specified tokens appearing in the
|
||||
completion. Accepts a json object that maps tokens (specified by their token ID
|
||||
in the GPT tokenizer) to an associated bias value from -100 to 100. You can use
|
||||
this tokenizer tool (which works for both GPT-2 and GPT-3) to convert text to
|
||||
token IDs. Mathematically, the bias is added to the logits generated by the
|
||||
model prior to sampling. The exact effect will vary per model, but values
|
||||
between -1 and 1 should decrease or increase likelihood of selection; values
|
||||
like -100 or 100 should result in a ban or exclusive selection of the relevant
|
||||
token. As an example, you can pass {\"50256\" : -100} to prevent the
|
||||
<|endoftext|> token from being generated.
|
||||
""")
|
||||
logit_bias?: object;
|
||||
|
||||
@doc("The ID of the end-user, for use in tracking and rate-limiting.")
|
||||
user?: string;
|
||||
|
||||
@doc("""
|
||||
How many snippets to generate for each prompt. Minimum of 1 and maximum of 128
|
||||
allowed.
|
||||
""")
|
||||
n?: int32;
|
||||
|
||||
@doc("""
|
||||
Whether to enable streaming for this endpoint. If set, tokens will be sent as
|
||||
server-sent events as they become available.
|
||||
""")
|
||||
stream?: boolean;
|
||||
|
||||
@doc("""
|
||||
Include the log probabilities on the `logprobs` most likely tokens, as well the
|
||||
chosen tokens. So for example, if `logprobs` is 10, the API will return a list
|
||||
of the 10 most likely tokens. If `logprobs` is 0, only the chosen tokens will
|
||||
have logprobs returned. Minimum of 0 and maximum of 100 allowed.
|
||||
""")
|
||||
logprobs?: int32;
|
||||
|
||||
@doc("The name of the model to use")
|
||||
"model"?: string;
|
||||
|
||||
@doc("Echo back the prompt in addition to the completion")
|
||||
echo?: boolean;
|
||||
|
||||
@doc("A sequence which indicates the end of the current document.")
|
||||
stop?: PostContentSchemaStop;
|
||||
completion_config?: string;
|
||||
|
||||
@doc("""
|
||||
can be used to disable any server-side caching, 0=no cache, 1=prompt prefix
|
||||
enabled, 2=full cache
|
||||
""")
|
||||
cache_level?: int32;
|
||||
|
||||
@doc("""
|
||||
How much to penalize new tokens based on their existing frequency in the text
|
||||
so far. Decreases the model's likelihood to repeat the same line verbatim. Has
|
||||
minimum of -2 and maximum of 2.
|
||||
""")
|
||||
presence_penalty?: float32;
|
||||
|
||||
@doc("""
|
||||
How much to penalize new tokens based on whether they appear in the text so
|
||||
far. Increases the model's likelihood to talk about new topics.
|
||||
""")
|
||||
frequency_penalty?: float32;
|
||||
|
||||
@doc("""
|
||||
How many generations to create server side, and display only the best. Will not
|
||||
stream intermediate progress if best_of > 1. Has maximum value of 128.
|
||||
""")
|
||||
best_of?: int32;
|
||||
}
|
||||
|
||||
@doc("""
|
||||
An optional prompt to complete from, encoded as a string, a list of strings, or
|
||||
a list of token lists. Defaults to <|endoftext|>. The prompt to complete from.
|
||||
If you would like to provide multiple prompts, use the POST variant of this
|
||||
method. Note that <|endoftext|> is the document separator that the model sees
|
||||
during training, so if a prompt is not specified the model will generate as if
|
||||
from the beginning of a new document. Maximum allowed size of string list is
|
||||
2048.
|
||||
""")
|
||||
model PostContentSchemaPrompt {}
|
||||
|
||||
@doc("A sequence which indicates the end of the current document.")
|
||||
model PostContentSchemaStop {}
|
||||
|
||||
model PathsMaorw9DeploymentsDeploymentIdCompletionsPostResponses200ContentApplicationJsonSchema {
|
||||
id?: string;
|
||||
object?: string;
|
||||
created?: int32;
|
||||
"model"?: string;
|
||||
choices?: Post200ApplicationJsonPropertiesItemsItem[];
|
||||
}
|
||||
|
||||
model Post200ApplicationJsonPropertiesItemsItem {
|
||||
text?: string;
|
||||
index?: int32;
|
||||
logprobs?: PostResponses200ContentApplicationJsonSchemaChoicesItemLogprobs;
|
||||
finish_reason?: string;
|
||||
}
|
||||
|
||||
model PostResponses200ContentApplicationJsonSchemaChoicesItemLogprobs {
|
||||
tokens?: string[];
|
||||
token_logprobs?: float32[];
|
||||
top_logprobs?: Record<float32>[];
|
||||
text_offset?: int32[];
|
||||
}
|
||||
|
||||
@error
|
||||
model ErrorResponse {
|
||||
error?: ErrorResponseError;
|
||||
}
|
||||
|
||||
model ErrorResponseError {
|
||||
code?: string;
|
||||
message?: string;
|
||||
param?: string;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
model Paths13PiqocDeploymentsDeploymentIdEmbeddingsPostRequestbodyContentApplicationJsonSchema {
|
||||
...DictionaryOfany;
|
||||
|
||||
@doc("""
|
||||
An input to embed, encoded as a string, a list of strings, or a list of token
|
||||
lists
|
||||
""")
|
||||
input: PostContentSchemaInput;
|
||||
|
||||
@doc("The ID of the end-user, for use in tracking and rate-limiting.")
|
||||
user?: string;
|
||||
|
||||
@doc("input type of embedding search to use")
|
||||
input_type?: string;
|
||||
|
||||
@doc("ID of the model to use")
|
||||
"model"?: string;
|
||||
}
|
||||
|
||||
@doc("""
|
||||
An input to embed, encoded as a string, a list of strings, or a list of token
|
||||
lists
|
||||
""")
|
||||
model PostContentSchemaInput {}
|
Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше
Загрузка…
Ссылка в новой задаче