@azure-tools/typespec-ts 0.36.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/src/contextManager.d.ts +1 -2
  3. package/dist/src/contextManager.d.ts.map +1 -1
  4. package/dist/src/contextManager.js.map +1 -1
  5. package/dist/src/framework/load-static-helpers.d.ts +2 -1
  6. package/dist/src/framework/load-static-helpers.d.ts.map +1 -1
  7. package/dist/src/framework/load-static-helpers.js +17 -0
  8. package/dist/src/framework/load-static-helpers.js.map +1 -1
  9. package/dist/src/index.d.ts.map +1 -1
  10. package/dist/src/index.js +31 -29
  11. package/dist/src/index.js.map +1 -1
  12. package/dist/src/metaTree.d.ts +0 -5
  13. package/dist/src/metaTree.d.ts.map +1 -1
  14. package/dist/src/modular/buildClassicalClient.d.ts +3 -2
  15. package/dist/src/modular/buildClassicalClient.d.ts.map +1 -1
  16. package/dist/src/modular/buildClassicalClient.js +64 -62
  17. package/dist/src/modular/buildClassicalClient.js.map +1 -1
  18. package/dist/src/modular/buildClassicalOperationGroups.d.ts +3 -2
  19. package/dist/src/modular/buildClassicalOperationGroups.d.ts.map +1 -1
  20. package/dist/src/modular/buildClassicalOperationGroups.js +35 -27
  21. package/dist/src/modular/buildClassicalOperationGroups.js.map +1 -1
  22. package/dist/src/modular/buildClientContext.d.ts +4 -3
  23. package/dist/src/modular/buildClientContext.d.ts.map +1 -1
  24. package/dist/src/modular/buildClientContext.js +84 -35
  25. package/dist/src/modular/buildClientContext.js.map +1 -1
  26. package/dist/src/modular/buildModularOptions.d.ts +7 -0
  27. package/dist/src/modular/buildModularOptions.d.ts.map +1 -0
  28. package/dist/src/modular/buildModularOptions.js +16 -0
  29. package/dist/src/modular/buildModularOptions.js.map +1 -0
  30. package/dist/src/modular/buildOperations.d.ts +6 -4
  31. package/dist/src/modular/buildOperations.d.ts.map +1 -1
  32. package/dist/src/modular/buildOperations.js +56 -55
  33. package/dist/src/modular/buildOperations.js.map +1 -1
  34. package/dist/src/modular/buildProjectFiles.d.ts +3 -2
  35. package/dist/src/modular/buildProjectFiles.d.ts.map +1 -1
  36. package/dist/src/modular/buildProjectFiles.js +18 -16
  37. package/dist/src/modular/buildProjectFiles.js.map +1 -1
  38. package/dist/src/modular/buildRestorePoller.d.ts +4 -2
  39. package/dist/src/modular/buildRestorePoller.d.ts.map +1 -1
  40. package/dist/src/modular/buildRestorePoller.js +22 -18
  41. package/dist/src/modular/buildRestorePoller.js.map +1 -1
  42. package/dist/src/modular/buildRootIndex.d.ts +4 -3
  43. package/dist/src/modular/buildRootIndex.d.ts.map +1 -1
  44. package/dist/src/modular/buildRootIndex.js +40 -31
  45. package/dist/src/modular/buildRootIndex.js.map +1 -1
  46. package/dist/src/modular/buildSubpathIndex.d.ts +4 -2
  47. package/dist/src/modular/buildSubpathIndex.d.ts.map +1 -1
  48. package/dist/src/modular/buildSubpathIndex.js +8 -5
  49. package/dist/src/modular/buildSubpathIndex.js.map +1 -1
  50. package/dist/src/modular/emitLoggerFile.d.ts +2 -3
  51. package/dist/src/modular/emitLoggerFile.d.ts.map +1 -1
  52. package/dist/src/modular/emitLoggerFile.js +4 -4
  53. package/dist/src/modular/emitLoggerFile.js.map +1 -1
  54. package/dist/src/modular/emitModels.d.ts +1 -2
  55. package/dist/src/modular/emitModels.d.ts.map +1 -1
  56. package/dist/src/modular/emitModels.js +10 -3
  57. package/dist/src/modular/emitModels.js.map +1 -1
  58. package/dist/src/modular/emitModelsOptions.d.ts +3 -24
  59. package/dist/src/modular/emitModelsOptions.d.ts.map +1 -1
  60. package/dist/src/modular/emitModelsOptions.js +10 -86
  61. package/dist/src/modular/emitModelsOptions.js.map +1 -1
  62. package/dist/src/modular/emitSamples.js +2 -1
  63. package/dist/src/modular/emitSamples.js.map +1 -1
  64. package/dist/src/modular/helpers/classicalOperationHelpers.d.ts +3 -3
  65. package/dist/src/modular/helpers/classicalOperationHelpers.d.ts.map +1 -1
  66. package/dist/src/modular/helpers/classicalOperationHelpers.js +40 -50
  67. package/dist/src/modular/helpers/classicalOperationHelpers.js.map +1 -1
  68. package/dist/src/modular/helpers/clientHelpers.d.ts +11 -8
  69. package/dist/src/modular/helpers/clientHelpers.d.ts.map +1 -1
  70. package/dist/src/modular/helpers/clientHelpers.js +87 -60
  71. package/dist/src/modular/helpers/clientHelpers.js.map +1 -1
  72. package/dist/src/modular/helpers/namingHelpers.d.ts +4 -7
  73. package/dist/src/modular/helpers/namingHelpers.d.ts.map +1 -1
  74. package/dist/src/modular/helpers/namingHelpers.js +3 -26
  75. package/dist/src/modular/helpers/namingHelpers.js.map +1 -1
  76. package/dist/src/modular/helpers/operationHelpers.d.ts +21 -20
  77. package/dist/src/modular/helpers/operationHelpers.d.ts.map +1 -1
  78. package/dist/src/modular/helpers/operationHelpers.js +336 -291
  79. package/dist/src/modular/helpers/operationHelpers.js.map +1 -1
  80. package/dist/src/modular/helpers/typeHelpers.d.ts +4 -25
  81. package/dist/src/modular/helpers/typeHelpers.d.ts.map +1 -1
  82. package/dist/src/modular/helpers/typeHelpers.js +6 -218
  83. package/dist/src/modular/helpers/typeHelpers.js.map +1 -1
  84. package/dist/src/modular/interfaces.d.ts +15 -8
  85. package/dist/src/modular/interfaces.d.ts.map +1 -1
  86. package/dist/src/modular/serialization/buildDeserializerFunction.d.ts.map +1 -1
  87. package/dist/src/modular/serialization/buildDeserializerFunction.js +1 -2
  88. package/dist/src/modular/serialization/buildDeserializerFunction.js.map +1 -1
  89. package/dist/src/modular/serialization/buildSerializerFunction.d.ts.map +1 -1
  90. package/dist/src/modular/serialization/buildSerializerFunction.js +1 -2
  91. package/dist/src/modular/serialization/buildSerializerFunction.js.map +1 -1
  92. package/dist/src/modular/serialization/serializeUtils.d.ts +8 -5
  93. package/dist/src/modular/serialization/serializeUtils.d.ts.map +1 -1
  94. package/dist/src/modular/serialization/serializeUtils.js +22 -22
  95. package/dist/src/modular/serialization/serializeUtils.js.map +1 -1
  96. package/dist/src/utils/clientUtils.d.ts +3 -1
  97. package/dist/src/utils/clientUtils.d.ts.map +1 -1
  98. package/dist/src/utils/clientUtils.js +10 -0
  99. package/dist/src/utils/clientUtils.js.map +1 -1
  100. package/dist/src/utils/operationUtil.d.ts +6 -2
  101. package/dist/src/utils/operationUtil.d.ts.map +1 -1
  102. package/dist/src/utils/operationUtil.js +66 -7
  103. package/dist/src/utils/operationUtil.js.map +1 -1
  104. package/dist/tsconfig.tsbuildinfo +1 -1
  105. package/package.json +3 -3
  106. package/src/contextManager.ts +1 -2
  107. package/src/framework/load-static-helpers.ts +24 -1
  108. package/src/index.ts +65 -37
  109. package/src/metaTree.ts +0 -6
  110. package/src/modular/buildClassicalClient.ts +97 -99
  111. package/src/modular/buildClassicalOperationGroups.ts +53 -47
  112. package/src/modular/buildClientContext.ts +101 -44
  113. package/src/modular/buildModularOptions.ts +27 -0
  114. package/src/modular/buildOperations.ts +91 -78
  115. package/src/modular/buildProjectFiles.ts +24 -21
  116. package/src/modular/buildRestorePoller.ts +39 -23
  117. package/src/modular/buildRootIndex.ts +51 -42
  118. package/src/modular/buildSubpathIndex.ts +16 -7
  119. package/src/modular/emitLoggerFile.ts +12 -10
  120. package/src/modular/emitModels.ts +15 -7
  121. package/src/modular/emitModelsOptions.ts +18 -125
  122. package/src/modular/emitSamples.ts +2 -3
  123. package/src/modular/helpers/classicalOperationHelpers.ts +50 -75
  124. package/src/modular/helpers/clientHelpers.ts +107 -73
  125. package/src/modular/helpers/namingHelpers.ts +6 -65
  126. package/src/modular/helpers/operationHelpers.ts +506 -384
  127. package/src/modular/helpers/typeHelpers.ts +11 -267
  128. package/src/modular/interfaces.ts +16 -8
  129. package/src/modular/serialization/buildDeserializerFunction.ts +1 -6
  130. package/src/modular/serialization/buildSerializerFunction.ts +1 -2
  131. package/src/modular/serialization/serializeUtils.ts +31 -30
  132. package/src/utils/clientUtils.ts +23 -1
  133. package/src/utils/operationUtil.ts +106 -14
  134. package/dist/src/modular/buildCodeModel.d.ts +0 -34
  135. package/dist/src/modular/buildCodeModel.d.ts.map +0 -1
  136. package/dist/src/modular/buildCodeModel.js +0 -1489
  137. package/dist/src/modular/buildCodeModel.js.map +0 -1
  138. package/dist/src/modular/modularCodeModel.d.ts +0 -166
  139. package/dist/src/modular/modularCodeModel.d.ts.map +0 -1
  140. package/dist/src/modular/modularCodeModel.js +0 -2
  141. package/dist/src/modular/modularCodeModel.js.map +0 -1
  142. package/src/modular/buildCodeModel.ts +0 -1965
  143. package/src/modular/modularCodeModel.ts +0 -211
@@ -1,1489 +0,0 @@
1
- import { NoTarget, UsageFlags, getDiscriminator, getDoc, getEncode, getFriendlyName, getMaxItems, getMaxLength, getMaxValue, getMinItems, getMinLength, getMinValue, getPattern, getPropertyType, getSummary, getVisibility, isErrorModel, isNeverType, isNullType, isNumericType, isStringType, isTemplateDeclarationOrInstance, isType, isVoidType, listServices } from "@typespec/compiler";
2
- import { getAuthentication, getServers, isSharedRoute } from "@typespec/http";
3
- import { NameType, buildRuntimeImports, isAzurePackage, normalizeName } from "@azure-tools/rlc-common";
4
- import { getAllModels, getClientNamespaceString, getClientType, getDefaultApiVersion, getHttpOperationWithCache, getLibraryName, getSdkUnion, getWireName, isApiVersion, listClients, listOperationGroups, listOperationsInOperationGroup } from "@azure-tools/typespec-client-generator-core";
5
- import { buildCoreTypeInfo, getBodyType, getDefaultApiVersionString, getEffectiveSchemaType, isAzureCoreErrorType, isBodyRequired, isSchemaProperty } from "../utils/modelUtils.js";
6
- import { camelToSnakeCase, toCamelCase } from "../utils/casingUtils.js";
7
- import { extractPagedMetadataNested, getOperationGroupName, getOperationName, isBinaryPayload, isIgnoredHeaderParam, isLongRunningOperation, parseItemName, parseNextLinkName } from "../utils/operationUtil.js";
8
- import { getLroMetadata, getPagedResult } from "@azure-tools/typespec-azure-core";
9
- import { getAddedOnVersions } from "@typespec/versioning";
10
- import { getModelNamespaceName } from "../utils/namespaceUtils.js";
11
- import { getSupportedHttpAuth } from "../utils/credentialUtils.js";
12
- import { getType as getTypeName } from "./helpers/typeHelpers.js";
13
- import { reportDiagnostic } from "../lib.js";
14
- import { useContext } from "../contextManager.js";
15
- import { normalizeModelName } from "./emitModels.js";
16
- let CASING = "snake";
17
- function applyCasing(name, options = { casing: "snake" }) {
18
- if (options.casing === "camel") {
19
- return toCamelCase(name);
20
- }
21
- return camelToSnakeCase(name);
22
- }
23
- const typesMap = new Map();
24
- const simpleTypesMap = new Map();
25
- const endpointPathParameters = [];
26
- let methodApiVersionParam = undefined;
27
- let serverApiVersionParam = undefined;
28
- function isSimpleType(program, type) {
29
- // these decorators can only work for simple type(int/string/float, etc)
30
- if (type && (type.kind === "Scalar" || type.kind === "ModelProperty")) {
31
- const funcs = [
32
- getMinValue,
33
- getMaxValue,
34
- getMinLength,
35
- getMaxLength,
36
- getPattern,
37
- getEncode
38
- ];
39
- for (const func of funcs) {
40
- if (func(program, type)) {
41
- return true;
42
- }
43
- }
44
- }
45
- return false;
46
- }
47
- function getDocStr(program, target) {
48
- var _a;
49
- return (_a = getDoc(program, target)) !== null && _a !== void 0 ? _a : "";
50
- }
51
- function isDiscriminator(context, type, propertyName) {
52
- const discriminator = getDiscriminator(context.program, type);
53
- if (discriminator && discriminator.propertyName === propertyName) {
54
- return true;
55
- }
56
- return false;
57
- }
58
- function handleDiscriminator(context, type, usage) {
59
- const discriminator = getDiscriminator(context.program, type);
60
- if (discriminator) {
61
- const discriminatorValues = [];
62
- const aliases = [];
63
- const discriminatedSubtypes = [];
64
- let discriminatorTcgcType = undefined;
65
- for (const childModel of type.derivedModels) {
66
- const modelType = getType(context, childModel, { usage });
67
- aliases.push(modelType.name);
68
- for (const property of modelType.properties) {
69
- if (property.restApiName === discriminator.propertyName) {
70
- modelType.discriminatorValue = property.type.value;
71
- discriminatorValues.push(modelType.discriminatorValue);
72
- discriminatorTcgcType = getClientType(context, property.type);
73
- }
74
- }
75
- discriminatedSubtypes.push(modelType);
76
- }
77
- const discriminatorInfo = {
78
- description: discriminatorValues.length > 0
79
- ? `the discriminator possible values: ${discriminatorValues.join(", ")}`
80
- : "discriminator property",
81
- type: { type: "string", tcgcType: discriminatorTcgcType },
82
- restApiName: discriminator.propertyName,
83
- clientName: discriminator.propertyName,
84
- name: discriminator.propertyName,
85
- isPolymorphic: true,
86
- isDiscriminator: true,
87
- aliases,
88
- discriminatedSubtypes
89
- };
90
- return discriminatorInfo;
91
- }
92
- return undefined;
93
- }
94
- function processModelProperties(context, newValue, model, usage) {
95
- // need to do properties after insertion to avoid infinite recursion
96
- const discriminatorInfo = handleDiscriminator(context, model, usage);
97
- let hasDiscriminator = false;
98
- for (const property of model.properties.values()) {
99
- if (!isSchemaProperty(context.program, property)) {
100
- continue;
101
- }
102
- if (isNeverType(property.type)) {
103
- continue;
104
- }
105
- if (newValue.properties === undefined || newValue.properties === null) {
106
- newValue.properties = [];
107
- }
108
- let newProperty = emitProperty(context, property, usage);
109
- if (isDiscriminator(context, model, property.name)) {
110
- hasDiscriminator = true;
111
- newProperty = {
112
- ...newProperty,
113
- ...discriminatorInfo,
114
- type: newProperty["type"],
115
- tcgcType: getClientType(context, property)
116
- };
117
- }
118
- newValue.properties.push(newProperty);
119
- }
120
- if (discriminatorInfo) {
121
- if (!hasDiscriminator) {
122
- newValue.properties.push({ ...discriminatorInfo });
123
- }
124
- // we don't need to add the discriminator info if it's an anonymous model
125
- // because it's impossible to have a anonymous model as the polymorphic base in typespec
126
- // the only possibility is the anonymous model is an alias for an union type which has already been taken care of in the combined types.
127
- if (newValue.name) {
128
- newValue.name = normalizeName(newValue.name, NameType.Interface);
129
- discriminatorInfo === null || discriminatorInfo === void 0 ? void 0 : discriminatorInfo.aliases.push(`${newValue.name}`);
130
- newValue.alias = `${newValue.name.replace(/Union$/g, "")}`;
131
- newValue.name = `${newValue.name}`;
132
- newValue.aliasType = discriminatorInfo === null || discriminatorInfo === void 0 ? void 0 : discriminatorInfo.aliases.join(" | ");
133
- newValue.types = discriminatorInfo === null || discriminatorInfo === void 0 ? void 0 : discriminatorInfo.discriminatedSubtypes;
134
- newValue.isPolymorphicBaseModel = true;
135
- newValue.discriminator = discriminatorInfo.restApiName;
136
- }
137
- }
138
- }
139
- function isEmptyAnonymousModel(type) {
140
- // object, {}, all will be treated as empty model
141
- return (type.kind === "Model" &&
142
- type.name === "" &&
143
- type.properties.size === 0 &&
144
- !type.baseModel &&
145
- type.derivedModels.length === 0 &&
146
- !type.indexer);
147
- }
148
- export function getType(context, type, options = {}) {
149
- var _a, _b;
150
- const modularMetatree = useContext("modularMetaTree");
151
- // don't cache simple type(string, int, etc) since decorators may change the result
152
- const enableCache = !isSimpleType(context.program, type);
153
- const effectiveModel = !options.disableEffectiveModel &&
154
- (type.kind === "Model" || type.kind === "Union")
155
- ? getEffectiveSchemaType(context.program, type)
156
- : type;
157
- if (enableCache) {
158
- const cached = typesMap.get(effectiveModel);
159
- if (cached) {
160
- return cached;
161
- }
162
- }
163
- let newValue = { __raw: type };
164
- if (isEmptyAnonymousModel(type)) {
165
- // do not generate model for empty model, treat it as any
166
- newValue = { type: "any" };
167
- }
168
- else {
169
- newValue = emitType(context, type, options);
170
- }
171
- if (type.kind === "ModelProperty" || type.kind === "Scalar") {
172
- newValue = applyEncoding(context.program, type, newValue);
173
- }
174
- if (isTypespecType(type)) {
175
- newValue.tcgcType = getClientType(context, effectiveModel);
176
- newValue.name = !newValue.tcgcType.isGeneratedName
177
- ? normalizeModelName(context, newValue.tcgcType)
178
- : newValue.name;
179
- newValue.__raw = type;
180
- modularMetatree.set(type, newValue);
181
- }
182
- if (enableCache) {
183
- if (!options.disableEffectiveModel) {
184
- if (newValue.__raw === undefined) {
185
- newValue.__raw = type;
186
- }
187
- typesMap.set(effectiveModel, newValue);
188
- }
189
- if (type.kind === "Union") {
190
- for (const t of type.variants.values()) {
191
- if (t.type.kind === "Model") {
192
- processModelProperties(context, newValue, t.type, options.usage);
193
- }
194
- }
195
- }
196
- if (type.kind === "Model") {
197
- // need to do properties after insertion to avoid infinite recursion
198
- processModelProperties(context, newValue, type, options.usage);
199
- if (newValue.type === "dict") {
200
- newValue = { ...emitModel(context, type, options), ...newValue };
201
- typesMap.set(effectiveModel, newValue);
202
- }
203
- }
204
- }
205
- else {
206
- const { __raw, tcgcType, ...keyableValue } = newValue;
207
- const key = JSON.stringify(keyableValue);
208
- const value = simpleTypesMap.get(key);
209
- if (value) {
210
- newValue = value;
211
- }
212
- else {
213
- simpleTypesMap.set(key, newValue);
214
- }
215
- }
216
- if (type.kind === "Model" &&
217
- newValue.tcgcType.additionalProperties &&
218
- !((_a = context.rlcOptions) === null || _a === void 0 ? void 0 : _a.compatibilityMode)) {
219
- reportDiagnostic(context.program, {
220
- code: "compatible-additional-properties",
221
- format: {
222
- modelName: (_b = type === null || type === void 0 ? void 0 : type.name) !== null && _b !== void 0 ? _b : ""
223
- },
224
- target: type
225
- });
226
- }
227
- typesMap.set(effectiveModel, newValue);
228
- return newValue;
229
- }
230
- function isTypespecType(type) {
231
- return type.kind !== "Credential" && type.kind !== "CredentialTypeUnion";
232
- }
233
- // To pass the yaml dump
234
- function getAddedOnVersion(p, t) {
235
- var _a, _b;
236
- return (_b = (_a = getAddedOnVersions(p, t)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.value;
237
- }
238
- function emitParamBase(context, parameter) {
239
- let optional;
240
- let name;
241
- let restApiName;
242
- let description = "";
243
- let addedOn;
244
- let format;
245
- const program = context.program;
246
- if (parameter.kind === "ModelProperty") {
247
- optional = parameter.optional;
248
- name = normalizeName(getLibraryName(context, parameter), NameType.Parameter, true);
249
- restApiName = getWireName(context, parameter);
250
- description = getDocStr(program, parameter);
251
- addedOn = getAddedOnVersion(program, parameter);
252
- const newParameter = applyEncoding(program, parameter, parameter);
253
- format = newParameter.format;
254
- }
255
- else {
256
- optional = false;
257
- name = "body";
258
- restApiName = "body";
259
- }
260
- return {
261
- optional,
262
- description,
263
- addedOn,
264
- clientName: applyCasing(name, { casing: CASING }),
265
- restApiName,
266
- inOverload: false,
267
- format,
268
- tcgcType: getClientType(context, parameter)
269
- };
270
- }
271
- function emitBodyParameter(context, httpOperation) {
272
- var _a;
273
- const params = httpOperation.parameters;
274
- const body = params.body;
275
- if (body.bodyKind === "single") {
276
- const base = emitParamBase(context, (_a = body.parameter) !== null && _a !== void 0 ? _a : body.type);
277
- let contentTypes = body.contentTypes;
278
- if (contentTypes.length === 0) {
279
- contentTypes = ["application/json"];
280
- }
281
- const type = getType(context, getBodyType(httpOperation), {
282
- disableEffectiveModel: true,
283
- usage: UsageFlags.Input
284
- });
285
- return {
286
- contentTypes,
287
- type,
288
- location: "body",
289
- ...base,
290
- isBinaryPayload: isBinaryPayload(context, body.type, contentTypes),
291
- optional: !isBodyRequired(httpOperation.parameters)
292
- };
293
- }
294
- return undefined;
295
- }
296
- function emitParameter(context, parameter, implementation) {
297
- var _a, _b;
298
- if (parameter.type === "cookie") {
299
- // TODO: support cookie parameters, https://github.com/Azure/autorest.typescript/issues/2898
300
- reportDiagnostic(context.program, {
301
- code: "parameter-type-not-supported",
302
- format: {
303
- paramType: parameter.type,
304
- paramName: parameter.name
305
- },
306
- target: NoTarget
307
- });
308
- return undefined;
309
- }
310
- const base = emitParamBase(context, parameter.param);
311
- let type = getType(context, parameter.param.type, {
312
- usage: UsageFlags.Input
313
- });
314
- let clientDefaultValue = undefined;
315
- if (parameter.name.toLowerCase() === "content-type" &&
316
- type["type"] === "constant") {
317
- /// We don't want constant types for content types, so we make sure if it's
318
- /// a constant, we make it not constant
319
- clientDefaultValue = type["value"];
320
- type = {
321
- ...type["valueType"],
322
- tcgcType: base.tcgcType.kind === "constant"
323
- ? base.tcgcType.valueType
324
- : base.tcgcType
325
- };
326
- }
327
- const paramMap = {
328
- restApiName: parameter.name,
329
- location: parameter.type,
330
- type: base.format ? { ...type, format: base.format } : type,
331
- implementation: implementation,
332
- skipUrlEncoding: parameter.type === "endpointPath" ||
333
- (parameter.type === "path" && parameter.allowReserved),
334
- format: (_a = parameter.format) !== null && _a !== void 0 ? _a : base.format,
335
- tcgcType: base.tcgcType
336
- };
337
- if (paramMap.type.type === "constant") {
338
- clientDefaultValue = paramMap.type.value;
339
- }
340
- if (isApiVersion(context, parameter) &&
341
- (paramMap.location === "query" || paramMap.location === "endpointPath")) {
342
- const defaultApiVersion = getDefaultApiVersion(context, getServiceNamespace(context.program));
343
- paramMap.implementation = implementation;
344
- paramMap.in_docstring = false;
345
- if (defaultApiVersion) {
346
- clientDefaultValue = defaultApiVersion.value;
347
- }
348
- if (!clientDefaultValue) {
349
- clientDefaultValue = getDefaultApiVersionString(context);
350
- }
351
- if (clientDefaultValue !== undefined) {
352
- paramMap.optional = true;
353
- }
354
- }
355
- if (clientDefaultValue === undefined &&
356
- paramMap.location === "endpointPath" &&
357
- ((_b = parameter.param.defaultValue) === null || _b === void 0 ? void 0 : _b.valueKind) === "StringValue") {
358
- // For endpoint path params, treat the default value as a client default.
359
- clientDefaultValue = parameter.param.defaultValue.value;
360
- }
361
- return { clientDefaultValue, ...base, ...paramMap };
362
- }
363
- function emitFlattenedParameter(bodyParameter, property) {
364
- return {
365
- checkClientInput: false,
366
- clientDefaultValue: null,
367
- clientName: property.clientName,
368
- delimiter: null,
369
- description: property.description,
370
- implementation: "Method",
371
- inDocstring: true,
372
- inFlattenedBody: true,
373
- inOverload: false,
374
- inOverriden: false,
375
- isApiVersion: bodyParameter["isApiVersion"],
376
- location: "other",
377
- optional: property["optional"],
378
- restApiName: null,
379
- skipUrlEncoding: false,
380
- type: property["type"],
381
- defaultToUnsetSentinel: true
382
- };
383
- }
384
- function emitResponseHeaders(context, headers) {
385
- const retval = [];
386
- if (!headers) {
387
- return retval;
388
- }
389
- for (const [key, value] of Object.entries(headers)) {
390
- retval.push({
391
- type: getType(context, value.type, { usage: UsageFlags.Output }),
392
- restApiName: key
393
- });
394
- }
395
- return retval;
396
- }
397
- function emitResponse(context, operation, response, innerResponse) {
398
- var _a, _b, _c, _d, _e, _f;
399
- let type = undefined;
400
- if (((_a = innerResponse.body) === null || _a === void 0 ? void 0 : _a.type) &&
401
- !isAzureCoreErrorType(context.program, (_b = innerResponse.body) === null || _b === void 0 ? void 0 : _b.type)) {
402
- // temporary logic. It can be removed after compiler optimize the response
403
- const candidate = [
404
- "ResourceOkResponse",
405
- "ResourceCreatedResponse",
406
- "AcceptedResponse"
407
- ];
408
- const originType = innerResponse.body.type;
409
- if (innerResponse.body.type.kind === "Model" &&
410
- candidate.find((e) => e === originType.name)) {
411
- const modelType = getEffectiveSchemaType(context.program, originType);
412
- type = getType(context, modelType, { usage: UsageFlags.Output });
413
- }
414
- else if (isLroResponse()) {
415
- const metadata = getLroMetadata(context.program, operation);
416
- type =
417
- (metadata === null || metadata === void 0 ? void 0 : metadata.finalResult) === "void" || (metadata === null || metadata === void 0 ? void 0 : metadata.finalResult) === undefined
418
- ? undefined
419
- : getType(context, metadata.finalResult);
420
- }
421
- else {
422
- type = isVoidType(innerResponse.body.type)
423
- ? undefined
424
- : getType(context, innerResponse.body.type, {
425
- usage: UsageFlags.Output
426
- });
427
- }
428
- }
429
- const statusCodes = [];
430
- if (response.statusCode === "*") {
431
- statusCodes.push("default");
432
- }
433
- else {
434
- statusCodes.push(parseInt(response.statusCode));
435
- }
436
- return {
437
- headers: emitResponseHeaders(context, innerResponse.headers),
438
- statusCodes: statusCodes !== null && statusCodes !== void 0 ? statusCodes : [],
439
- addedOn: getAddedOnVersion(context.program, response.type),
440
- discriminator: "basic",
441
- type: type,
442
- isBinaryPayload: ((_c = innerResponse.body) === null || _c === void 0 ? void 0 : _c.type)
443
- ? isBinaryPayload(context, (_d = innerResponse.body) === null || _d === void 0 ? void 0 : _d.type, (_f = (_e = innerResponse.body) === null || _e === void 0 ? void 0 : _e.contentTypes[0]) !== null && _f !== void 0 ? _f : "application/json")
444
- : false
445
- };
446
- function isLroResponse() {
447
- var _a;
448
- return (typeof response.statusCodes === "number" &&
449
- ((_a = ["200", "201", "202"]) === null || _a === void 0 ? void 0 : _a.includes(`${response.statusCodes}`)) &&
450
- !!getLroMetadata(context.program, operation));
451
- }
452
- }
453
- function emitOperation(context, operation, operationGroupName, rlcModels, hierarchies) {
454
- const isAzureFlavor = isAzurePackage(rlcModels);
455
- const emittedOperation = emitBasicOperation(context, operation, operationGroupName, rlcModels, hierarchies);
456
- // Skip to extract paging and lro information for non-branded clients.
457
- if (!isAzureFlavor) {
458
- return emittedOperation;
459
- }
460
- const lro = isLongRunningOperation(context.program, getHttpOperationWithCache(context, operation));
461
- const pagingMetadata = getPagedResult(context.program, operation);
462
- // Disable the paging feature if no itemsSegments is found.
463
- const paging = pagingMetadata &&
464
- pagingMetadata.itemsSegments &&
465
- pagingMetadata.itemsSegments.length > 0;
466
- if (pagingMetadata &&
467
- (!pagingMetadata.itemsSegments || pagingMetadata.itemsSegments.length === 0)) {
468
- reportDiagnostic(context.program, {
469
- code: "no-paging-items-defined",
470
- format: {
471
- operationName: operation.name
472
- },
473
- target: operation
474
- });
475
- }
476
- emitExtraInfoForOperation(emittedOperation);
477
- return emittedOperation;
478
- function emitExtraInfoForOperation(emittedOperation) {
479
- if (lro) {
480
- addLroInformation(context, operation, emittedOperation);
481
- }
482
- if (paging) {
483
- addPagingInformation(context, operation, emittedOperation);
484
- }
485
- if (lro && paging) {
486
- emittedOperation["discriminator"] = "lropaging";
487
- }
488
- }
489
- }
490
- function addLroInformation(context, operation, emittedOperation) {
491
- emittedOperation["discriminator"] = "lro";
492
- const metadata = getLroMetadata(context.program, operation);
493
- emittedOperation["lroMetadata"] = {
494
- finalResult: (metadata === null || metadata === void 0 ? void 0 : metadata.finalResult) === "void" || (metadata === null || metadata === void 0 ? void 0 : metadata.finalResult) === undefined
495
- ? undefined
496
- : getType(context, metadata.finalResult),
497
- finalStateVia: getFinalStateVia(context, operation, metadata),
498
- finalResultPath: metadata === null || metadata === void 0 ? void 0 : metadata.finalResultPath
499
- };
500
- }
501
- function getFinalStateVia(context, operation, metadata) {
502
- if (!metadata) {
503
- return undefined;
504
- }
505
- switch (metadata.finalStateVia) {
506
- case "azure-async-operation":
507
- case "location":
508
- case "operation-location":
509
- case "original-uri":
510
- return metadata.finalStateVia;
511
- default:
512
- reportDiagnostic(context.program, {
513
- code: "un-supported-finalStateVia",
514
- format: {
515
- finalStateVia: metadata.finalStateVia
516
- },
517
- target: operation
518
- });
519
- return undefined;
520
- }
521
- }
522
- function addPagingInformation(context, operation, emittedOperation) {
523
- emittedOperation["discriminator"] = "paging";
524
- const pagedResult = getPagedResult(context.program, operation);
525
- if (pagedResult === undefined) {
526
- throw Error("Trying to add paging information, but not paging metadata for this operation");
527
- }
528
- emittedOperation["itemName"] = parseItemName(pagedResult);
529
- emittedOperation["continuationTokenName"] = parseNextLinkName(pagedResult);
530
- }
531
- function emitBasicOperation(context, operation, operationGroupName, rlcModels, hierarchies) {
532
- var _a, _b, _c, _d, _e;
533
- // Set up parameters for operation
534
- const parameters = [];
535
- if (endpointPathParameters) {
536
- for (const param of endpointPathParameters) {
537
- parameters.push(param);
538
- }
539
- }
540
- const httpOperation = getHttpOperationWithCache(context, operation);
541
- const sourceOperation = operation.sourceOperation &&
542
- !isTemplateDeclarationOrInstance(operation.sourceOperation)
543
- ? operation.sourceOperation
544
- : operation;
545
- const sourceOperationGroupName = getOperationGroupName(context, sourceOperation);
546
- const sourceOperationName = getOperationName(context, sourceOperation);
547
- const sourceRoutePath = getHttpOperationWithCache(context, operation).path;
548
- const rlcResponses = (_a = rlcModels.responses) === null || _a === void 0 ? void 0 : _a.filter((op) => {
549
- return ((sourceOperationGroupName === "" ||
550
- op.operationGroup === sourceOperationGroupName) &&
551
- op.operationName === sourceOperationName &&
552
- op.path === sourceRoutePath);
553
- });
554
- const namespaceHierarchies = ((_b = context.rlcOptions) === null || _b === void 0 ? void 0 : _b.hierarchyClient) === true ? hierarchies : [];
555
- if (namespaceHierarchies.length === 0 &&
556
- ((_c = context.rlcOptions) === null || _c === void 0 ? void 0 : _c.hierarchyClient) === false &&
557
- operationGroupName !== "") {
558
- namespaceHierarchies.push(operationGroupName);
559
- }
560
- for (const param of httpOperation.parameters.parameters) {
561
- if (isIgnoredHeaderParam(param)) {
562
- continue;
563
- }
564
- const emittedParam = emitParameter(context, param, "Method");
565
- if (emittedParam === undefined) {
566
- continue;
567
- }
568
- if (isApiVersion(context, param)) {
569
- emittedParam.isApiVersion = true;
570
- methodApiVersionParam = emittedParam;
571
- }
572
- parameters.push(emittedParam);
573
- }
574
- // Set up responses for operation
575
- const responses = [];
576
- const exceptions = [];
577
- const isOverload = isSharedRoute(context.program, operation);
578
- for (const response of httpOperation.responses) {
579
- for (const innerResponse of response.responses) {
580
- const emittedResponse = emitResponse(context, operation, response, innerResponse);
581
- if (isErrorModel(context.program, response.type)) {
582
- // * is valid status code in typespec but invalid for autorest.python
583
- if (response.statusCode === "*") {
584
- exceptions.push(emittedResponse);
585
- }
586
- }
587
- else {
588
- responses.push(emittedResponse);
589
- }
590
- }
591
- }
592
- let bodyParameter;
593
- if (httpOperation.parameters.body === undefined ||
594
- isVoidType(httpOperation.parameters.body.type)) {
595
- bodyParameter = undefined;
596
- }
597
- else {
598
- bodyParameter = emitBodyParameter(context, httpOperation);
599
- // Flatten the body parameter if it is an anonymous model
600
- const originalBodyType = httpOperation.parameters.body.type;
601
- if (bodyParameter.type.type === "model" &&
602
- originalBodyType.kind === "Model" &&
603
- originalBodyType.name === "" &&
604
- [...originalBodyType.properties.keys()].every((k) => {
605
- var _a;
606
- return operation.parameters.properties.has(k) &&
607
- (operation.parameters.properties.get(k) ===
608
- originalBodyType.properties.get(k) ||
609
- operation.parameters.properties.get(k) ===
610
- ((_a = originalBodyType.properties.get(k)) === null || _a === void 0 ? void 0 : _a.sourceProperty));
611
- })) {
612
- for (const param of bodyParameter.type.properties) {
613
- param.implementation = "Method";
614
- param.location = (_d = param.location) !== null && _d !== void 0 ? _d : "body";
615
- parameters.push(param);
616
- }
617
- bodyParameter = undefined;
618
- }
619
- else if (bodyParameter.type.type === "model" &&
620
- bodyParameter.type.base === "json") {
621
- bodyParameter["propertyToParameterName"] = {};
622
- if (!isOverload) {
623
- bodyParameter.defaultToUnsetSentinel = true;
624
- }
625
- for (const property of bodyParameter.type.properties) {
626
- bodyParameter["propertyToParameterName"][property["restApiName"]] =
627
- property["clientName"];
628
- parameters.push(emitFlattenedParameter(bodyParameter, property));
629
- }
630
- }
631
- }
632
- const name = applyCasing(getLibraryName(context, operation), {
633
- casing: CASING
634
- });
635
- /** handle name collision between operation name and parameter signature */
636
- if (bodyParameter) {
637
- bodyParameter.clientName =
638
- bodyParameter.clientName === name
639
- ? bodyParameter.clientName + "Parameter"
640
- : bodyParameter.clientName;
641
- }
642
- parameters
643
- .filter((param) => {
644
- return param.clientName === name && !param.isReadOnly && param.required;
645
- })
646
- .forEach((param) => {
647
- param.clientName = param.clientName + "Parameter";
648
- });
649
- return {
650
- name,
651
- description: getDocStr(context.program, operation),
652
- summary: (_e = getSummary(context.program, operation)) !== null && _e !== void 0 ? _e : "",
653
- url: httpOperation.path,
654
- method: httpOperation.verb.toUpperCase(),
655
- parameters: parameters,
656
- bodyParameter: bodyParameter,
657
- responses: responses !== null && responses !== void 0 ? responses : [],
658
- exceptions: exceptions !== null && exceptions !== void 0 ? exceptions : [],
659
- groupName: operationGroupName,
660
- addedOn: getAddedOnVersion(context.program, operation),
661
- discriminator: "basic",
662
- isOverload,
663
- overloads: [],
664
- apiVersions: [getAddedOnVersion(context.program, operation)],
665
- rlcResponse: rlcResponses === null || rlcResponses === void 0 ? void 0 : rlcResponses[0],
666
- namespaceHierarchies
667
- };
668
- }
669
- function isReadOnly(program, type) {
670
- // https://microsoft.github.io/typespec/standard-library/http/operations#automatic-visibility
671
- // Only "read" should be readOnly
672
- const visibility = getVisibility(program, type);
673
- if (visibility) {
674
- return visibility.includes("read") && visibility.length === 1;
675
- }
676
- else {
677
- return false;
678
- }
679
- }
680
- function emitProperty(context, property, usage) {
681
- var _a, _b, _c;
682
- const newProperty = applyEncoding(context.program, property, property);
683
- let clientDefaultValue = undefined;
684
- const propertyDefaultKind = (_a = property.default) === null || _a === void 0 ? void 0 : _a.kind;
685
- if (property.default &&
686
- (propertyDefaultKind === "Number" ||
687
- propertyDefaultKind === "String" ||
688
- propertyDefaultKind === "Boolean")) {
689
- clientDefaultValue = property.default.value;
690
- }
691
- if (propertyDefaultKind === "EnumMember") {
692
- clientDefaultValue = (_b = property.default.value) !== null && _b !== void 0 ? _b : property.default.name;
693
- }
694
- // const [clientName, jsonName] = getPropertyNames(context, property);
695
- const clientName = getLibraryName(context, property);
696
- const jsonName = getWireName(context, property);
697
- if (property.model) {
698
- getType(context, property.model, { usage });
699
- }
700
- const type = getType(context, property.type, { usage });
701
- return {
702
- clientName: ((_c = context.rlcOptions) === null || _c === void 0 ? void 0 : _c.ignorePropertyNameNormalize)
703
- ? clientName
704
- : normalizeName(clientName, NameType.Property),
705
- restApiName: jsonName,
706
- type: newProperty.format ? { ...type, format: newProperty.format } : type,
707
- optional: property.optional,
708
- description: getDocStr(context.program, property),
709
- addedOn: getAddedOnVersion(context.program, property),
710
- readonly: isReadOnly(context.program, property),
711
- clientDefaultValue: clientDefaultValue,
712
- format: newProperty.format
713
- };
714
- }
715
- function getName(program, type) {
716
- const friendlyName = getFriendlyName(program, type);
717
- if (friendlyName) {
718
- return friendlyName;
719
- }
720
- else {
721
- if (type.templateMapper &&
722
- type.templateMapper.args &&
723
- type.name !== "" &&
724
- type.templateMapper.args.length > 0) {
725
- return (type.name +
726
- type.templateMapper.args.filter((it) => isType(it))
727
- .map((it) => (it.kind === "Model" ? it.name : ""))
728
- .join(""));
729
- }
730
- else {
731
- return type.name;
732
- }
733
- }
734
- }
735
- export function emitModel(context, type, options = {}) {
736
- var _a, _b;
737
- // Now we know it's a defined model
738
- const properties = [];
739
- let baseModel = undefined;
740
- if (type.baseModel) {
741
- baseModel = getType(context, type.baseModel, options);
742
- }
743
- const effectiveName = !options.disableEffectiveModel
744
- ? getEffectiveSchemaType(context.program, type).name
745
- : undefined;
746
- const overridedModelName = normalizeName((_a = getLibraryName(context, type)) !== null && _a !== void 0 ? _a : getFriendlyName(context.program, type), NameType.Interface, true);
747
- const fullNamespaceName = getModelNamespaceName(context, type.namespace)
748
- .map((nsName) => {
749
- return normalizeName(nsName, NameType.Interface);
750
- })
751
- .join("") +
752
- (effectiveName ? effectiveName : getName(context.program, type));
753
- let modelName = overridedModelName !== type.name
754
- ? overridedModelName
755
- : ((_b = context.rlcOptions) === null || _b === void 0 ? void 0 : _b.enableModelNamespace)
756
- ? fullNamespaceName
757
- : effectiveName
758
- ? effectiveName
759
- : getName(context.program, type);
760
- if (!overridedModelName &&
761
- type.templateMapper &&
762
- type.templateMapper.args &&
763
- type.templateMapper.args.length > 0 &&
764
- getPagedResult(context.program, type)) {
765
- modelName =
766
- type.templateMapper.args.filter((it) => isType(it))
767
- .map((it) => {
768
- switch (it.kind) {
769
- case "Model":
770
- return it.name;
771
- case "String":
772
- return it.value;
773
- default:
774
- return "";
775
- }
776
- })
777
- .join("") + "List";
778
- }
779
- const page = extractPagedMetadataNested(context.program, type);
780
- const isPaging = page && page.itemsSegments && page.itemsSegments.length > 0;
781
- return {
782
- type: "model",
783
- name: `${isPaging ? "_" : ""}${modelName}`,
784
- description: getDocStr(context.program, type),
785
- parents: baseModel ? [baseModel] : [],
786
- discriminatedSubtypes: [],
787
- properties: properties,
788
- addedOn: getAddedOnVersion(context.program, type),
789
- snakeCaseName: modelName
790
- ? applyCasing(modelName, { casing: CASING })
791
- : modelName,
792
- base: modelName === "" ? "json" : "dpg",
793
- coreTypeInfo: buildCoreTypeInfo(context.program, type),
794
- usage: options.usage
795
- };
796
- }
797
- function intOrFloat(value) {
798
- return value.toString().indexOf(".") === -1 ? "integer" : "float";
799
- }
800
- function enumName(name) {
801
- return name;
802
- }
803
- function emitEnum(context, type) {
804
- var _a;
805
- const program = context.program;
806
- const enumValues = [];
807
- for (const m of type.members.values()) {
808
- enumValues.push({
809
- name: enumName(m.name),
810
- value: (_a = m.value) !== null && _a !== void 0 ? _a : m.name,
811
- description: getDocStr(program, m)
812
- });
813
- }
814
- if (enumValues.length === 0) {
815
- throw new Error(`Expecting enum values but got none`);
816
- }
817
- const name = normalizeName(getLibraryName(context, type) ? getLibraryName(context, type) : type.name, NameType.Interface);
818
- return {
819
- type: "enum",
820
- name,
821
- description: getDocStr(program, type) === ""
822
- ? `Type of ${name}`
823
- : getDocStr(program, type),
824
- valueType: { type: enumMemberType(type.members.values().next().value) },
825
- values: enumValues,
826
- isFixed: true,
827
- coreTypeInfo: buildCoreTypeInfo(program, type)
828
- };
829
- }
830
- function enumMemberType(member) {
831
- if (typeof member.value === "number") {
832
- return "number";
833
- }
834
- return "string";
835
- }
836
- function constantType(value, valueType) {
837
- return { type: "constant", value: value, valueType: { type: valueType } };
838
- }
839
- function emitCredential(auth) {
840
- let credential_type = {};
841
- if (auth.type === "oauth2") {
842
- credential_type = {
843
- type: "OAuth2",
844
- policy: {
845
- type: "BearerTokenCredentialPolicy",
846
- credentialScopes: []
847
- }
848
- };
849
- for (const flow of auth.flows) {
850
- for (const scope of flow.scopes) {
851
- credential_type.policy.credentialScopes.push(scope.value);
852
- }
853
- credential_type.policy.credentialScopes.push();
854
- }
855
- }
856
- else if (auth.type === "apiKey") {
857
- credential_type = {
858
- type: "Key",
859
- policy: {
860
- type: "AzureKeyCredentialPolicy",
861
- key: auth.name
862
- }
863
- };
864
- }
865
- else if (auth.type === "http") {
866
- credential_type = {
867
- type: "Key",
868
- policy: {
869
- type: "AzureKeyCredentialPolicy",
870
- key: "Authorization"
871
- }
872
- };
873
- }
874
- return credential_type;
875
- }
876
- function emitCredentialUnion(cred_types) {
877
- const result = {};
878
- // Export as CombinedType, which is already a Union Type in autorest codegen
879
- result.type = "combined";
880
- result.types = [];
881
- for (const cred_type of cred_types.types) {
882
- result.types.push(emitCredential(cred_type.scheme));
883
- }
884
- return result;
885
- }
886
- function emitStdScalar(program, scalar) {
887
- var _a, _b, _c;
888
- const newScalar = applyEncoding(program, scalar, scalar);
889
- switch (scalar.name) {
890
- case "bytes":
891
- return { type: "byte-array", format: newScalar.format };
892
- case "int8":
893
- case "int16":
894
- case "int32":
895
- case "int64":
896
- case "safeint":
897
- case "uint8":
898
- case "uint16":
899
- case "uint32":
900
- case "uint64":
901
- case "integer":
902
- return { type: "integer" };
903
- case "float32":
904
- case "float64":
905
- case "float":
906
- return { type: "float" };
907
- case "url":
908
- case "string":
909
- return { type: "string" };
910
- case "boolean":
911
- return { type: "boolean" };
912
- case "plainDate":
913
- return { type: "string", format: (_a = newScalar.format) !== null && _a !== void 0 ? _a : "date" };
914
- case "utcDateTime":
915
- return { type: "datetime", format: newScalar.format };
916
- case "plainTime":
917
- return { type: "string", format: (_b = newScalar.format) !== null && _b !== void 0 ? _b : "time" };
918
- case "offsetDateTime":
919
- return { type: "string" };
920
- case "duration":
921
- return { type: "duration", format: newScalar.format };
922
- case "numeric":
923
- return {}; // Waiting on design for more precise type https://github.com/microsoft/cadl/issues/1260
924
- case "decimal":
925
- case "decimal128":
926
- reportDiagnostic(program, {
927
- code: "decimal-to-number",
928
- format: {
929
- propertyName: (_c = newScalar === null || newScalar === void 0 ? void 0 : newScalar.name) !== null && _c !== void 0 ? _c : ""
930
- },
931
- target: NoTarget
932
- });
933
- return { type: "integer", format: newScalar.format };
934
- default:
935
- return {};
936
- }
937
- }
938
- function applyEncoding(program, typespecType, target = {}) {
939
- const encodeData = getEncode(program, typespecType);
940
- if (encodeData) {
941
- const newTarget = { ...target };
942
- const newType = emitScalar(program, encodeData.type);
943
- // newTarget["type"] = newType["type"];
944
- // If the target already has a format it takes priority. (e.g. int32)
945
- newTarget["format"] = mergeFormatAndEncoding(newTarget.format, encodeData.encoding, newType["format"]);
946
- return newTarget;
947
- }
948
- return target;
949
- }
950
- function mergeFormatAndEncoding(format, encoding, encodeAsFormat) {
951
- var _a, _b;
952
- switch (format) {
953
- case undefined:
954
- return (_a = encodeAsFormat !== null && encodeAsFormat !== void 0 ? encodeAsFormat : encoding) !== null && _a !== void 0 ? _a : format;
955
- case "date-time":
956
- return encoding;
957
- case "duration":
958
- default:
959
- return (_b = encodeAsFormat !== null && encodeAsFormat !== void 0 ? encodeAsFormat : encoding) !== null && _b !== void 0 ? _b : format;
960
- }
961
- }
962
- function applyIntrinsicDecorators(program, type, result) {
963
- let newResult = { ...result };
964
- const docStr = getDoc(program, type);
965
- const isString = isStringType(program, getPropertyType(type));
966
- const isNumeric = isNumericType(program, getPropertyType(type));
967
- if (!result.description && docStr) {
968
- newResult.description = docStr;
969
- }
970
- newResult = applyEncoding(program, type, newResult);
971
- const pattern = getPattern(program, type);
972
- if (isString && !result.pattern && pattern) {
973
- newResult.pattern = pattern;
974
- }
975
- const minLength = getMinLength(program, type);
976
- if (isString && !result.minLength && minLength !== undefined) {
977
- newResult.minLength = minLength;
978
- }
979
- const maxLength = getMaxLength(program, type);
980
- if (isString && !result.maxLength && maxLength !== undefined) {
981
- newResult.maxLength = maxLength;
982
- }
983
- const minValue = getMinValue(program, type);
984
- if (isNumeric && !result.minimum && minValue !== undefined) {
985
- newResult.minimum = minValue;
986
- }
987
- const maxValue = getMaxValue(program, type);
988
- if (isNumeric && !result.maximum && maxValue !== undefined) {
989
- newResult.maximum = maxValue;
990
- }
991
- const minItems = getMinItems(program, type);
992
- if (!result.minItems && minItems !== undefined) {
993
- newResult.minItems = minItems;
994
- }
995
- const maxItems = getMaxItems(program, type);
996
- if (!result.maxItems && maxItems !== undefined) {
997
- newResult.maxItems = maxItems;
998
- }
999
- return newResult;
1000
- }
1001
- function emitScalar(program, scalar) {
1002
- let result = {};
1003
- const isStd = program.checker.isStdType(scalar);
1004
- if (isStd) {
1005
- result = emitStdScalar(program, scalar);
1006
- }
1007
- else if (scalar.baseScalar) {
1008
- result = emitScalar(program, scalar.baseScalar);
1009
- }
1010
- return applyIntrinsicDecorators(program, scalar, result);
1011
- }
1012
- function emitListOrDict(context, type, usage) {
1013
- if (type.indexer !== undefined) {
1014
- if (!isNeverType(type.indexer.key)) {
1015
- const name = type.indexer.key.name;
1016
- if (name === "string") {
1017
- return {
1018
- type: "dict",
1019
- name: type.name,
1020
- elementType: getType(context, type.indexer.value, { usage })
1021
- };
1022
- }
1023
- else if (name === "integer") {
1024
- return {
1025
- type: "list",
1026
- elementType: getType(context, type.indexer.value, { usage })
1027
- };
1028
- }
1029
- }
1030
- }
1031
- return undefined;
1032
- }
1033
- function mapTypeSpecType(context, type, usage) {
1034
- switch (type.kind) {
1035
- case "Number":
1036
- return constantType(type.value, intOrFloat(type.value));
1037
- case "String":
1038
- return constantType(type.value, "string");
1039
- case "Boolean":
1040
- return constantType(type.value, "boolean");
1041
- case "Model":
1042
- return emitListOrDict(context, type, usage);
1043
- }
1044
- }
1045
- function emitUnion(context, type, usage) {
1046
- var _a, _b, _c;
1047
- let sdkType = getSdkUnion(context, type);
1048
- const isNull = sdkType.kind === "nullable";
1049
- if (sdkType.kind === "nullable") {
1050
- sdkType = sdkType.type;
1051
- }
1052
- const nonNullOptions = getNonNullOptions(type);
1053
- if (sdkType === undefined) {
1054
- throw Error("Should not have an empty union");
1055
- }
1056
- if (sdkType.kind === "union") {
1057
- const unionName = getLibraryName(context, type)
1058
- ? getLibraryName(context, type)
1059
- : type.name;
1060
- const discriminatorPropertyName = (_a = getDiscriminator(context.program, type)) === null || _a === void 0 ? void 0 : _a.propertyName;
1061
- const variantTypes = sdkType.variantTypes.map((x) => {
1062
- const valueType = getType(context, x.__raw, { usage });
1063
- if (valueType.properties && discriminatorPropertyName) {
1064
- valueType.discriminatorValue = valueType.properties.filter((p) => p.clientName === discriminatorPropertyName)[0].type.value;
1065
- }
1066
- return valueType;
1067
- });
1068
- const unionTypeName = unionName
1069
- ? normalizeName(unionName, NameType.Interface)
1070
- : undefined;
1071
- return {
1072
- nullable: isNull,
1073
- name: unionTypeName,
1074
- description: `Type of ${unionTypeName}`,
1075
- internal: true,
1076
- type: "combined",
1077
- types: variantTypes,
1078
- xmlMetadata: {},
1079
- usage,
1080
- discriminator: discriminatorPropertyName,
1081
- alias: unionName === "" || unionName === undefined ? undefined : unionName,
1082
- aliasType: unionName === "" || unionName === undefined
1083
- ? undefined
1084
- : variantTypes.map((x) => getTypeName(x).name).join(" | "),
1085
- tcgcType: sdkType
1086
- };
1087
- }
1088
- else if (sdkType.kind === "enum") {
1089
- let typeName = getLibraryName(context, type)
1090
- ? getLibraryName(context, type)
1091
- : sdkType.isGeneratedName
1092
- ? type.name
1093
- : sdkType.name;
1094
- typeName = typeName
1095
- ? normalizeName(typeName, NameType.Interface)
1096
- : undefined;
1097
- return {
1098
- name: typeName,
1099
- nullable: isNull,
1100
- description: sdkType.doc || `Type of ${typeName}`,
1101
- internal: true,
1102
- type: sdkType.kind,
1103
- valueType: emitSimpleType(sdkType.valueType),
1104
- values: sdkType.values.map((x) => emitEnumMember(context, x)),
1105
- isFixed: sdkType.isFixed,
1106
- isNonExhaustive: (_c = (_b = context.rlcOptions) === null || _b === void 0 ? void 0 : _b.experimentalExtensibleEnums) !== null && _c !== void 0 ? _c : false,
1107
- xmlMetadata: {},
1108
- usage
1109
- };
1110
- }
1111
- else if (nonNullOptions.length === 1 && nonNullOptions[0]) {
1112
- return {
1113
- ...emitType(context, nonNullOptions[0], { usage }),
1114
- nullable: isNull
1115
- };
1116
- }
1117
- else {
1118
- return {
1119
- ...emitType(context, sdkType.__raw, { usage }),
1120
- nullable: isNull
1121
- };
1122
- }
1123
- }
1124
- function getNonNullOptions(type) {
1125
- return [...type.variants.values()]
1126
- .map((x) => x.type)
1127
- .filter((t) => !isNullType(t));
1128
- }
1129
- function emitEnumMember(context, member) {
1130
- var _a;
1131
- const value = (_a = member.value) !== null && _a !== void 0 ? _a : member.name;
1132
- return {
1133
- type: "constant",
1134
- valueType: {
1135
- type: enumMemberType(member)
1136
- },
1137
- value,
1138
- name: member.name ? enumName(member.name) : undefined,
1139
- description: getDoc(context.program, member),
1140
- isConstant: true
1141
- };
1142
- }
1143
- function emitSimpleType(type) {
1144
- return {
1145
- nullable: isNullType(type.__raw),
1146
- type: type.kind === "string" ? "string" : "number", // TODO: handle other types
1147
- doc: "",
1148
- apiVersions: [],
1149
- sdkDefaultValue: undefined,
1150
- format: undefined
1151
- };
1152
- }
1153
- function emitType(context, type, options = {}) {
1154
- if (type.kind === "Credential") {
1155
- return emitCredential(type.scheme);
1156
- }
1157
- if (type.kind === "CredentialTypeUnion") {
1158
- return emitCredentialUnion(type);
1159
- }
1160
- const builtinType = mapTypeSpecType(context, type, options.usage);
1161
- if (builtinType !== undefined) {
1162
- // add in description elements for types derived from primitive types (SecureString, etc.)
1163
- const doc = getDoc(context.program, type);
1164
- if (doc) {
1165
- builtinType.description = doc;
1166
- }
1167
- return builtinType;
1168
- }
1169
- switch (type.kind) {
1170
- case "Intrinsic":
1171
- return { type: type.name };
1172
- case "Model":
1173
- return emitModel(context, type, options);
1174
- case "Scalar":
1175
- return emitScalar(context.program, type);
1176
- case "Union":
1177
- return emitUnion(context, type, options.usage);
1178
- case "UnionVariant":
1179
- return emitType(context, type.type, options);
1180
- case "Enum":
1181
- return emitEnum(context, type);
1182
- case "EnumMember":
1183
- return emitEnumMember(context, type);
1184
- case "ModelProperty":
1185
- return emitType(context, type.type, options);
1186
- default:
1187
- throw Error(`Not supported ${type.kind}`);
1188
- }
1189
- }
1190
- function emitOperationGroups(context, client, rlcModels) {
1191
- var _a, _b, _c, _d, _e, _f, _g;
1192
- const operationGroups = [];
1193
- const groupMapping = new Map();
1194
- const clientOperations = [];
1195
- for (const operation of listOperationsInOperationGroup(context, client)) {
1196
- clientOperations.push(emitOperation(context, operation, "", rlcModels, []));
1197
- }
1198
- if (clientOperations.length > 0) {
1199
- addHierarchyOperationGroup(clientOperations, groupMapping);
1200
- }
1201
- for (const operationGroup of listOperationGroups(context, client, true)) {
1202
- const operations = [];
1203
- const overrideName = getLibraryName(context, operationGroup.type);
1204
- const name = ((_a = context.rlcOptions) === null || _a === void 0 ? void 0 : _a.hierarchyClient) ||
1205
- ((_b = context.rlcOptions) === null || _b === void 0 ? void 0 : _b.enableOperationGroup)
1206
- ? (overrideName !== null && overrideName !== void 0 ? overrideName : operationGroup.type.name)
1207
- : "";
1208
- const hierarchies = ((_c = context.rlcOptions) === null || _c === void 0 ? void 0 : _c.hierarchyClient) ||
1209
- ((_d = context.rlcOptions) === null || _d === void 0 ? void 0 : _d.enableOperationGroup)
1210
- ? operationGroup.groupPath.split(".")
1211
- : [];
1212
- if ((_e = hierarchies[0]) === null || _e === void 0 ? void 0 : _e.endsWith("Client")) {
1213
- hierarchies.shift();
1214
- }
1215
- for (const operation of listOperationsInOperationGroup(context, operationGroup)) {
1216
- operations.push(emitOperation(context, operation, name, rlcModels, hierarchies));
1217
- }
1218
- if (operations.length > 0) {
1219
- addHierarchyOperationGroup(operations, groupMapping);
1220
- }
1221
- }
1222
- groupMapping.forEach((value) => {
1223
- operationGroups.push(value);
1224
- });
1225
- if (((_f = context.rlcOptions) === null || _f === void 0 ? void 0 : _f.hierarchyClient) === false &&
1226
- ((_g = context.rlcOptions) === null || _g === void 0 ? void 0 : _g.enableOperationGroup)) {
1227
- appendOperationGroupPrefix(operationGroups);
1228
- }
1229
- return operationGroups;
1230
- }
1231
- function addHierarchyOperationGroup(operations, groupMapping) {
1232
- if (operations.length > 0) {
1233
- operations.forEach((op) => {
1234
- var _a;
1235
- const groupName = (_a = op.namespaceHierarchies.join("")) !== null && _a !== void 0 ? _a : "";
1236
- if (!groupMapping.has(groupName)) {
1237
- groupMapping.set(groupName, {
1238
- className: groupName,
1239
- propertyName: groupName,
1240
- operations: [op],
1241
- namespaceHierarchies: op.namespaceHierarchies
1242
- });
1243
- }
1244
- else {
1245
- groupMapping.get(groupName).operations.push(op);
1246
- }
1247
- });
1248
- return [...groupMapping.values()];
1249
- }
1250
- return [];
1251
- }
1252
- function appendOperationGroupPrefix(operationGroups) {
1253
- if (operationGroups.length < 2) {
1254
- return;
1255
- }
1256
- // Append operation group prefix
1257
- operationGroups.forEach((g) => g.operations.forEach((op) => {
1258
- op.oriName = op.name;
1259
- op.name = `${g.propertyName}_${op.name}`;
1260
- }));
1261
- }
1262
- function getServerHelper(program, namespace) {
1263
- const servers = getServers(program, namespace);
1264
- if (servers === undefined) {
1265
- return undefined;
1266
- }
1267
- return servers[0];
1268
- }
1269
- function emitServerParams(context, namespace) {
1270
- const server = getServerHelper(context.program, namespace);
1271
- if (server === undefined || server.parameters.size === 0) {
1272
- return [
1273
- {
1274
- optional: false,
1275
- description: "Service host",
1276
- clientName: "endpointParam",
1277
- clientDefaultValue: null,
1278
- restApiName: "endpoint",
1279
- location: "endpointPath",
1280
- type: { type: "string" },
1281
- implementation: "Client",
1282
- inOverload: false
1283
- }
1284
- ];
1285
- }
1286
- if (server.parameters) {
1287
- const params = [];
1288
- for (const param of server.parameters.values()) {
1289
- const serverParameter = {
1290
- type: "endpointPath",
1291
- name: param.name,
1292
- param: param
1293
- };
1294
- const emittedParameter = emitParameter(context, serverParameter, "Client");
1295
- if (emittedParameter === undefined) {
1296
- continue;
1297
- }
1298
- endpointPathParameters.push(emittedParameter);
1299
- if (isApiVersion(context, serverParameter)) {
1300
- emittedParameter.isApiVersion = true;
1301
- serverApiVersionParam = emittedParameter;
1302
- emittedParameter.isApiVersion = true;
1303
- }
1304
- params.push(emittedParameter);
1305
- }
1306
- return params;
1307
- }
1308
- else {
1309
- return [
1310
- {
1311
- optional: false,
1312
- description: "Service host",
1313
- clientName: "endpointParam",
1314
- clientDefaultValue: server.url,
1315
- restApiName: "endpoint",
1316
- location: "path",
1317
- type: { type: "string" },
1318
- implementation: "Client",
1319
- inOverload: false
1320
- }
1321
- ];
1322
- }
1323
- }
1324
- function emitCredentialParam(context, namespace) {
1325
- var _a;
1326
- const auth = getAuthentication(context.program, namespace);
1327
- if (auth) {
1328
- const credential_types = [];
1329
- for (const scheme of getSupportedHttpAuth(context.program, auth)) {
1330
- const type = {
1331
- kind: "Credential",
1332
- scheme: scheme
1333
- };
1334
- credential_types.push(type);
1335
- }
1336
- if (credential_types.length > 0 &&
1337
- ((_a = context.rlcOptions) === null || _a === void 0 ? void 0 : _a.addCredentials) !== false) {
1338
- let type;
1339
- if (credential_types.length === 1 && credential_types[0]) {
1340
- type = credential_types[0];
1341
- }
1342
- else {
1343
- type = {
1344
- kind: "CredentialTypeUnion",
1345
- types: credential_types
1346
- };
1347
- }
1348
- return {
1349
- type: getType(context, type, { usage: UsageFlags.Input }),
1350
- optional: false,
1351
- description: "Credential needed for the client to connect to Azure.",
1352
- clientName: "credential",
1353
- location: "other",
1354
- restApiName: "credential",
1355
- implementation: "Client",
1356
- skipUrlEncoding: true,
1357
- inOverload: false
1358
- };
1359
- }
1360
- }
1361
- return undefined;
1362
- }
1363
- function emitGlobalParameters(context, namespace) {
1364
- const clientParameters = emitServerParams(context, namespace);
1365
- const credentialParam = emitCredentialParam(context, namespace);
1366
- if (credentialParam) {
1367
- clientParameters.push(credentialParam);
1368
- }
1369
- return clientParameters;
1370
- }
1371
- function getMethodApiVersionParameter() {
1372
- if (methodApiVersionParam) {
1373
- return {
1374
- ...methodApiVersionParam,
1375
- isApiVersion: true
1376
- };
1377
- }
1378
- }
1379
- function emitClients(context, rlcModelsMap) {
1380
- var _a;
1381
- const program = context.program;
1382
- const clients = listClients(context);
1383
- const retval = [];
1384
- methodApiVersionParam = undefined;
1385
- for (const client of clients) {
1386
- const sdkPackageClient = context.sdkPackage.clients.find((p) => {
1387
- return p.name === client.name;
1388
- });
1389
- if (!sdkPackageClient) {
1390
- throw new Error(`Client ${client.name} not found in the SDK package`);
1391
- }
1392
- const clientName = client.name.replace("Client", "");
1393
- const server = getServerHelper(program, client.service);
1394
- const rlcModels = rlcModelsMap.get(client.service.name);
1395
- if (!rlcModels) {
1396
- continue;
1397
- }
1398
- const emittedClient = {
1399
- name: (_a = clientName.split(".").at(-1)) !== null && _a !== void 0 ? _a : "",
1400
- description: getDocStr(program, client.type),
1401
- parameters: emitGlobalParameters(context, client.service),
1402
- operationGroups: emitOperationGroups(context, client, rlcModels),
1403
- tcgcClient: sdkPackageClient,
1404
- url: server ? server.url : "",
1405
- apiVersions: [],
1406
- rlcClientName: `${client.name.replace("Client", "")}Context`,
1407
- subfolder: "",
1408
- rlcHelperDetails: rlcModels && rlcModels.helperDetails ? rlcModels.helperDetails : {}
1409
- };
1410
- const methodApiVersionParam = getMethodApiVersionParameter();
1411
- if (methodApiVersionParam &&
1412
- !serverApiVersionParam &&
1413
- context.hasApiVersionInClient) {
1414
- // prompt method-level api version to client level only when there is no client one defined
1415
- emittedClient.parameters.push(methodApiVersionParam);
1416
- // if we have client level api version, we need to remove it from all operations
1417
- emittedClient.operationGroups.map((opGroup) => {
1418
- opGroup.operations.map((op) => {
1419
- op.parameters = op.parameters.filter((param) => {
1420
- return !param.isApiVersion;
1421
- });
1422
- return op;
1423
- });
1424
- return opGroup;
1425
- });
1426
- }
1427
- retval.push(emittedClient);
1428
- }
1429
- return retval;
1430
- }
1431
- function getServiceNamespace(program) {
1432
- return listServices(program)[0].type;
1433
- }
1434
- function getNamespace(context, clientName) {
1435
- // We get client namespaces from the client name. If there's a dot, we add that to the namespace
1436
- const submodule = clientName.split(".").slice(0, -1).join(".").toLowerCase();
1437
- if (!submodule) {
1438
- return getClientNamespaceString(context).toLowerCase();
1439
- }
1440
- return submodule;
1441
- }
1442
- function getNamespaces(context) {
1443
- const namespaces = new Set();
1444
- for (const client of listClients(context)) {
1445
- namespaces.add(getNamespace(context, client.name));
1446
- }
1447
- return namespaces;
1448
- }
1449
- export function emitCodeModel(dpgContext, rlcModelsMap, modularSourcesRoot, project, options = { casing: "snake" }) {
1450
- var _a, _b, _c, _d, _e, _f;
1451
- CASING = (_a = options.casing) !== null && _a !== void 0 ? _a : CASING;
1452
- const clientNamespaceString = (_b = getClientNamespaceString(dpgContext)) === null || _b === void 0 ? void 0 : _b.toLowerCase();
1453
- // Get types
1454
- const codeModel = {
1455
- options: (_c = dpgContext.rlcOptions) !== null && _c !== void 0 ? _c : {},
1456
- modularOptions: {
1457
- sourceRoot: modularSourcesRoot,
1458
- compatibilityMode: !!((_d = dpgContext.rlcOptions) === null || _d === void 0 ? void 0 : _d.compatibilityMode),
1459
- experimentalExtensibleEnums: !!((_e = dpgContext.rlcOptions) === null || _e === void 0 ? void 0 : _e.experimentalExtensibleEnums)
1460
- },
1461
- namespace: clientNamespaceString,
1462
- clients: [],
1463
- types: [],
1464
- project,
1465
- runtimeImports: buildRuntimeImports((_f = dpgContext.rlcOptions) === null || _f === void 0 ? void 0 : _f.flavor)
1466
- };
1467
- typesMap.clear();
1468
- simpleTypesMap.clear();
1469
- const allModels = getAllModels(dpgContext);
1470
- for (const model of allModels) {
1471
- getType(dpgContext, model.__raw, { usage: model.usage });
1472
- }
1473
- for (const namespace of getNamespaces(dpgContext)) {
1474
- if (namespace === clientNamespaceString) {
1475
- codeModel.clients = emitClients(dpgContext, rlcModelsMap);
1476
- codeModel.clients.length > 1 &&
1477
- codeModel.clients.map((client) => {
1478
- client["subfolder"] = normalizeName(client.name.replace("Client", ""), NameType.File);
1479
- });
1480
- }
1481
- }
1482
- codeModel["types"] = [
1483
- { type: "string" },
1484
- ...typesMap.values(),
1485
- ...simpleTypesMap.values()
1486
- ];
1487
- return codeModel;
1488
- }
1489
- //# sourceMappingURL=buildCodeModel.js.map