-
Notifications
You must be signed in to change notification settings - Fork 188
/
utils.ts
433 lines (373 loc) · 12.8 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
"use strict";
import { OpenAPIV3 } from "openapi-types";
import SwaggerParser from "@apidevtools/swagger-parser";
import { ConstantString } from "./constants";
import {
APIMap,
AuthInfo,
ErrorResult,
ErrorType,
ParseOptions,
ProjectType,
ValidateResult,
ValidationStatus,
WarningResult,
WarningType,
} from "./interfaces";
import { IMessagingExtensionCommand, IParameter } from "@microsoft/teams-manifest";
export class Utils {
static hasNestedObjectInSchema(schema: OpenAPIV3.SchemaObject): boolean {
if (schema.type === "object") {
for (const property in schema.properties) {
const nestedSchema = schema.properties[property] as OpenAPIV3.SchemaObject;
if (nestedSchema.type === "object") {
return true;
}
}
}
return false;
}
static containMultipleMediaTypes(
bodyObject: OpenAPIV3.RequestBodyObject | OpenAPIV3.ResponseObject
): boolean {
return Object.keys(bodyObject?.content || {}).length > 1;
}
static isBearerTokenAuth(authScheme: OpenAPIV3.SecuritySchemeObject): boolean {
return authScheme.type === "http" && authScheme.scheme === "bearer";
}
static isAPIKeyAuth(authScheme: OpenAPIV3.SecuritySchemeObject): boolean {
return authScheme.type === "apiKey";
}
static isOAuthWithAuthCodeFlow(authScheme: OpenAPIV3.SecuritySchemeObject): boolean {
return !!(
authScheme.type === "oauth2" &&
authScheme.flows &&
authScheme.flows.authorizationCode
);
}
static getAuthArray(
securities: OpenAPIV3.SecurityRequirementObject[] | undefined,
spec: OpenAPIV3.Document
): AuthInfo[][] {
const result: AuthInfo[][] = [];
const securitySchemas = spec.components?.securitySchemes;
if (securities && securitySchemas) {
for (let i = 0; i < securities.length; i++) {
const security = securities[i];
const authArray: AuthInfo[] = [];
for (const name in security) {
const auth = securitySchemas[name] as OpenAPIV3.SecuritySchemeObject;
authArray.push({
authScheme: auth,
name: name,
});
}
if (authArray.length > 0) {
result.push(authArray);
}
}
}
result.sort((a, b) => a[0].name.localeCompare(b[0].name));
return result;
}
static updateFirstLetter(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
static getResponseJson(operationObject: OpenAPIV3.OperationObject | undefined): {
json: OpenAPIV3.MediaTypeObject;
multipleMediaType: boolean;
} {
let json: OpenAPIV3.MediaTypeObject = {};
let multipleMediaType = false;
for (const code of ConstantString.ResponseCodeFor20X) {
const responseObject = operationObject?.responses?.[code] as OpenAPIV3.ResponseObject;
if (responseObject?.content?.["application/json"]) {
multipleMediaType = false;
json = responseObject.content["application/json"];
if (Utils.containMultipleMediaTypes(responseObject)) {
multipleMediaType = true;
json = {};
} else {
break;
}
}
}
return { json, multipleMediaType };
}
static convertPathToCamelCase(path: string): string {
const pathSegments = path.split(/[./{]/);
const camelCaseSegments = pathSegments.map((segment) => {
segment = segment.replace(/}/g, "");
return segment.charAt(0).toUpperCase() + segment.slice(1);
});
const camelCasePath = camelCaseSegments.join("");
return camelCasePath;
}
static getUrlProtocol(urlString: string): string | undefined {
try {
const url = new URL(urlString);
return url.protocol;
} catch (err) {
return undefined;
}
}
static resolveEnv(str: string): string {
const placeHolderReg = /\${{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*}}/g;
let matches = placeHolderReg.exec(str);
let newStr = str;
while (matches != null) {
const envVar = matches[1];
const envVal = process.env[envVar];
if (!envVal) {
throw new Error(Utils.format(ConstantString.ResolveServerUrlFailed, envVar));
} else {
newStr = newStr.replace(matches[0], envVal);
}
matches = placeHolderReg.exec(str);
}
return newStr;
}
static checkServerUrl(servers: OpenAPIV3.ServerObject[]): ErrorResult[] {
const errors: ErrorResult[] = [];
let serverUrl;
try {
serverUrl = Utils.resolveEnv(servers[0].url);
} catch (err) {
errors.push({
type: ErrorType.ResolveServerUrlFailed,
content: (err as Error).message,
data: servers,
});
return errors;
}
const protocol = Utils.getUrlProtocol(serverUrl);
if (!protocol) {
// Relative server url is not supported
errors.push({
type: ErrorType.RelativeServerUrlNotSupported,
content: ConstantString.RelativeServerUrlNotSupported,
data: servers,
});
} else if (protocol !== "https:") {
// Http server url is not supported
const protocolString = protocol.slice(0, -1);
errors.push({
type: ErrorType.UrlProtocolNotSupported,
content: Utils.format(ConstantString.UrlProtocolNotSupported, protocol.slice(0, -1)),
data: protocolString,
});
}
return errors;
}
static validateServer(spec: OpenAPIV3.Document, options: ParseOptions): ErrorResult[] {
const errors: ErrorResult[] = [];
let hasTopLevelServers = false;
let hasPathLevelServers = false;
let hasOperationLevelServers = false;
if (spec.servers && spec.servers.length >= 1) {
hasTopLevelServers = true;
// for multiple server, we only use the first url
const serverErrors = Utils.checkServerUrl(spec.servers);
errors.push(...serverErrors);
}
const paths = spec.paths;
for (const path in paths) {
const methods = paths[path];
if (methods?.servers && methods.servers.length >= 1) {
hasPathLevelServers = true;
const serverErrors = Utils.checkServerUrl(methods.servers);
errors.push(...serverErrors);
}
for (const method in methods) {
const operationObject = (methods as any)[method] as OpenAPIV3.OperationObject;
if (options.allowMethods?.includes(method) && operationObject) {
if (operationObject?.servers && operationObject.servers.length >= 1) {
hasOperationLevelServers = true;
const serverErrors = Utils.checkServerUrl(operationObject.servers);
errors.push(...serverErrors);
}
}
}
}
if (!hasTopLevelServers && !hasPathLevelServers && !hasOperationLevelServers) {
errors.push({
type: ErrorType.NoServerInformation,
content: ConstantString.NoServerInformation,
});
}
return errors;
}
static isWellKnownName(name: string, wellknownNameList: string[]): boolean {
for (let i = 0; i < wellknownNameList.length; i++) {
name = name.replace(/_/g, "").replace(/-/g, "");
if (name.toLowerCase().includes(wellknownNameList[i])) {
return true;
}
}
return false;
}
static generateParametersFromSchema(
schema: OpenAPIV3.SchemaObject,
name: string,
allowMultipleParameters: boolean,
isRequired = false
): [IParameter[], IParameter[]] {
const requiredParams: IParameter[] = [];
const optionalParams: IParameter[] = [];
if (
schema.type === "string" ||
schema.type === "integer" ||
schema.type === "boolean" ||
schema.type === "number"
) {
const parameter: IParameter = {
name: name,
title: Utils.updateFirstLetter(name).slice(0, ConstantString.ParameterTitleMaxLens),
description: (schema.description ?? "").slice(
0,
ConstantString.ParameterDescriptionMaxLens
),
};
if (allowMultipleParameters) {
Utils.updateParameterWithInputType(schema, parameter);
}
if (isRequired && schema.default === undefined) {
parameter.isRequired = true;
requiredParams.push(parameter);
} else {
optionalParams.push(parameter);
}
} else if (schema.type === "object") {
const { properties } = schema;
for (const property in properties) {
let isRequired = false;
if (schema.required && schema.required?.indexOf(property) >= 0) {
isRequired = true;
}
const [requiredP, optionalP] = Utils.generateParametersFromSchema(
properties[property] as OpenAPIV3.SchemaObject,
property,
allowMultipleParameters,
isRequired
);
requiredParams.push(...requiredP);
optionalParams.push(...optionalP);
}
}
return [requiredParams, optionalParams];
}
static updateParameterWithInputType(schema: OpenAPIV3.SchemaObject, param: IParameter): void {
if (schema.enum) {
param.inputType = "choiceset";
param.choices = [];
for (let i = 0; i < schema.enum.length; i++) {
param.choices.push({
title: schema.enum[i],
value: schema.enum[i],
});
}
} else if (schema.type === "string") {
param.inputType = "text";
} else if (schema.type === "integer" || schema.type === "number") {
param.inputType = "number";
} else if (schema.type === "boolean") {
param.inputType = "toggle";
}
if (schema.default) {
param.value = schema.default;
}
}
static parseApiInfo(
operationItem: OpenAPIV3.OperationObject,
options: ParseOptions
): IMessagingExtensionCommand {
const requiredParams: IParameter[] = [];
const optionalParams: IParameter[] = [];
const paramObject = operationItem.parameters as OpenAPIV3.ParameterObject[];
if (paramObject) {
paramObject.forEach((param: OpenAPIV3.ParameterObject) => {
const parameter: IParameter = {
name: param.name,
title: Utils.updateFirstLetter(param.name).slice(0, ConstantString.ParameterTitleMaxLens),
description: (param.description ?? "").slice(
0,
ConstantString.ParameterDescriptionMaxLens
),
};
const schema = param.schema as OpenAPIV3.SchemaObject;
if (options.allowMultipleParameters && schema) {
Utils.updateParameterWithInputType(schema, parameter);
}
if (param.in !== "header" && param.in !== "cookie") {
if (param.required && schema?.default === undefined) {
parameter.isRequired = true;
requiredParams.push(parameter);
} else {
optionalParams.push(parameter);
}
}
});
}
if (operationItem.requestBody) {
const requestBody = operationItem.requestBody as OpenAPIV3.RequestBodyObject;
const requestJson = requestBody.content["application/json"];
if (Object.keys(requestJson).length !== 0) {
const schema = requestJson.schema as OpenAPIV3.SchemaObject;
const [requiredP, optionalP] = Utils.generateParametersFromSchema(
schema,
"requestBody",
!!options.allowMultipleParameters,
requestBody.required
);
requiredParams.push(...requiredP);
optionalParams.push(...optionalP);
}
}
const operationId = operationItem.operationId!;
const parameters = [...requiredParams, ...optionalParams];
const command: IMessagingExtensionCommand = {
context: ["compose"],
type: "query",
title: (operationItem.summary ?? "").slice(0, ConstantString.CommandTitleMaxLens),
id: operationId,
parameters: parameters,
description: (operationItem.description ?? "").slice(
0,
ConstantString.CommandDescriptionMaxLens
),
};
return command;
}
static format(str: string, ...args: string[]): string {
let index = 0;
return str.replace(/%s/g, () => {
const arg = args[index++];
return arg !== undefined ? arg : "";
});
}
static getSafeRegistrationIdEnvName(authName: string): string {
if (!authName) {
return "";
}
let safeRegistrationIdEnvName = authName.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
if (!safeRegistrationIdEnvName.match(/^[A-Z]/)) {
safeRegistrationIdEnvName = "PREFIX_" + safeRegistrationIdEnvName;
}
return safeRegistrationIdEnvName;
}
static getServerObject(
spec: OpenAPIV3.Document,
method: string,
path: string
): OpenAPIV3.ServerObject | undefined {
const pathObj = spec.paths[path] as any;
const operationObject = pathObj[method] as OpenAPIV3.OperationObject;
const rootServer = spec.servers && spec.servers[0];
const methodServer = spec.paths[path]!.servers && spec.paths[path]!.servers![0];
const operationServer = operationObject.servers && operationObject.servers[0];
const serverUrl = operationServer || methodServer || rootServer;
return serverUrl;
}
}