@microsoft/m365-spec-parser 0.1.1-alpha.1c9557de8.0 → 0.1.1-alpha.228d6f497.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.
@@ -16,6 +16,7 @@ var ErrorType;
16
16
  ErrorType["ResolveServerUrlFailed"] = "resolve-server-url-failed";
17
17
  ErrorType["SwaggerNotSupported"] = "swagger-not-supported";
18
18
  ErrorType["MultipleAuthNotSupported"] = "multiple-auth-not-supported";
19
+ ErrorType["SpecVersionNotSupported"] = "spec-version-not-supported";
19
20
  ErrorType["ListFailed"] = "list-failed";
20
21
  ErrorType["listSupportedAPIInfoFailed"] = "list-supported-api-info-failed";
21
22
  ErrorType["FilterSpecFailed"] = "filter-spec-failed";
@@ -24,6 +25,21 @@ var ErrorType;
24
25
  ErrorType["GenerateFailed"] = "generate-failed";
25
26
  ErrorType["ValidateFailed"] = "validate-failed";
26
27
  ErrorType["GetSpecFailed"] = "get-spec-failed";
28
+ ErrorType["AuthTypeIsNotSupported"] = "auth-type-is-not-supported";
29
+ ErrorType["MissingOperationId"] = "missing-operation-id";
30
+ ErrorType["PostBodyContainMultipleMediaTypes"] = "post-body-contain-multiple-media-types";
31
+ ErrorType["ResponseContainMultipleMediaTypes"] = "response-contain-multiple-media-types";
32
+ ErrorType["ResponseJsonIsEmpty"] = "response-json-is-empty";
33
+ ErrorType["PostBodySchemaIsNotJson"] = "post-body-schema-is-not-json";
34
+ ErrorType["PostBodyContainsRequiredUnsupportedSchema"] = "post-body-contains-required-unsupported-schema";
35
+ ErrorType["ParamsContainRequiredUnsupportedSchema"] = "params-contain-required-unsupported-schema";
36
+ ErrorType["ParamsContainsNestedObject"] = "params-contains-nested-object";
37
+ ErrorType["RequestBodyContainsNestedObject"] = "request-body-contains-nested-object";
38
+ ErrorType["ExceededRequiredParamsLimit"] = "exceeded-required-params-limit";
39
+ ErrorType["NoParameter"] = "no-parameter";
40
+ ErrorType["NoAPIInfo"] = "no-api-info";
41
+ ErrorType["MethodNotAllowed"] = "method-not-allowed";
42
+ ErrorType["UrlPathNotExist"] = "url-path-not-exist";
27
43
  ErrorType["Cancelled"] = "cancelled";
28
44
  ErrorType["Unknown"] = "unknown";
29
45
  })(ErrorType || (ErrorType = {}));
@@ -79,6 +95,7 @@ ConstantString.ResolveServerUrlFailed = "Unable to resolve the server URL: pleas
79
95
  ConstantString.OperationOnlyContainsOptionalParam = "Operation %s contains multiple optional parameters. The first optional parameter is used for this command.";
80
96
  ConstantString.ConvertSwaggerToOpenAPI = "The Swagger 2.0 file has been converted to OpenAPI 3.0.";
81
97
  ConstantString.SwaggerNotSupported = "Swagger 2.0 is not supported. Please convert to OpenAPI 3.0 manually before proceeding.";
98
+ ConstantString.SpecVersionNotSupported = "Unsupported OpenAPI version %s. Please use version 3.0.x.";
82
99
  ConstantString.MultipleAuthNotSupported = "Multiple authentication methods are unsupported. Ensure all selected APIs use identical authentication.";
83
100
  ConstantString.UnsupportedSchema = "Unsupported schema in %s %s: %s";
84
101
  ConstantString.WrappedCardVersion = "devPreview";
@@ -153,7 +170,8 @@ ConstantString.CommandDescriptionMaxLens = 128;
153
170
  ConstantString.ParameterDescriptionMaxLens = 128;
154
171
  ConstantString.CommandTitleMaxLens = 32;
155
172
  ConstantString.ParameterTitleMaxLens = 32;
156
- ConstantString.SMERequiredParamsMaxNum = 5;
173
+ ConstantString.SMERequiredParamsMaxNum = 5;
174
+ ConstantString.DefaultPluginId = "plugin_1";
157
175
 
158
176
  // Copyright (c) Microsoft Corporation.
159
177
  class Utils {
@@ -168,221 +186,9 @@ class Utils {
168
186
  }
169
187
  return false;
170
188
  }
171
- static checkParameters(paramObject, isCopilot) {
172
- const paramResult = {
173
- requiredNum: 0,
174
- optionalNum: 0,
175
- isValid: true,
176
- };
177
- if (!paramObject) {
178
- return paramResult;
179
- }
180
- for (let i = 0; i < paramObject.length; i++) {
181
- const param = paramObject[i];
182
- const schema = param.schema;
183
- if (isCopilot && this.hasNestedObjectInSchema(schema)) {
184
- paramResult.isValid = false;
185
- continue;
186
- }
187
- const isRequiredWithoutDefault = param.required && schema.default === undefined;
188
- if (isCopilot) {
189
- if (isRequiredWithoutDefault) {
190
- paramResult.requiredNum = paramResult.requiredNum + 1;
191
- }
192
- else {
193
- paramResult.optionalNum = paramResult.optionalNum + 1;
194
- }
195
- continue;
196
- }
197
- if (param.in === "header" || param.in === "cookie") {
198
- if (isRequiredWithoutDefault) {
199
- paramResult.isValid = false;
200
- }
201
- continue;
202
- }
203
- if (schema.type !== "boolean" &&
204
- schema.type !== "string" &&
205
- schema.type !== "number" &&
206
- schema.type !== "integer") {
207
- if (isRequiredWithoutDefault) {
208
- paramResult.isValid = false;
209
- }
210
- continue;
211
- }
212
- if (param.in === "query" || param.in === "path") {
213
- if (isRequiredWithoutDefault) {
214
- paramResult.requiredNum = paramResult.requiredNum + 1;
215
- }
216
- else {
217
- paramResult.optionalNum = paramResult.optionalNum + 1;
218
- }
219
- }
220
- }
221
- return paramResult;
222
- }
223
- static checkPostBody(schema, isRequired = false, isCopilot = false) {
224
- var _a;
225
- const paramResult = {
226
- requiredNum: 0,
227
- optionalNum: 0,
228
- isValid: true,
229
- };
230
- if (Object.keys(schema).length === 0) {
231
- return paramResult;
232
- }
233
- const isRequiredWithoutDefault = isRequired && schema.default === undefined;
234
- if (isCopilot && this.hasNestedObjectInSchema(schema)) {
235
- paramResult.isValid = false;
236
- return paramResult;
237
- }
238
- if (schema.type === "string" ||
239
- schema.type === "integer" ||
240
- schema.type === "boolean" ||
241
- schema.type === "number") {
242
- if (isRequiredWithoutDefault) {
243
- paramResult.requiredNum = paramResult.requiredNum + 1;
244
- }
245
- else {
246
- paramResult.optionalNum = paramResult.optionalNum + 1;
247
- }
248
- }
249
- else if (schema.type === "object") {
250
- const { properties } = schema;
251
- for (const property in properties) {
252
- let isRequired = false;
253
- if (schema.required && ((_a = schema.required) === null || _a === void 0 ? void 0 : _a.indexOf(property)) >= 0) {
254
- isRequired = true;
255
- }
256
- const result = Utils.checkPostBody(properties[property], isRequired, isCopilot);
257
- paramResult.requiredNum += result.requiredNum;
258
- paramResult.optionalNum += result.optionalNum;
259
- paramResult.isValid = paramResult.isValid && result.isValid;
260
- }
261
- }
262
- else {
263
- if (isRequiredWithoutDefault && !isCopilot) {
264
- paramResult.isValid = false;
265
- }
266
- }
267
- return paramResult;
268
- }
269
189
  static containMultipleMediaTypes(bodyObject) {
270
190
  return Object.keys((bodyObject === null || bodyObject === void 0 ? void 0 : bodyObject.content) || {}).length > 1;
271
191
  }
272
- /**
273
- * Checks if the given API is supported.
274
- * @param {string} method - The HTTP method of the API.
275
- * @param {string} path - The path of the API.
276
- * @param {OpenAPIV3.Document} spec - The OpenAPI specification document.
277
- * @returns {boolean} - Returns true if the API is supported, false otherwise.
278
- * @description The following APIs are supported:
279
- * 1. only support Get/Post operation without auth property
280
- * 2. parameter inside query or path only support string, number, boolean and integer
281
- * 3. parameter inside post body only support string, number, boolean, integer and object
282
- * 4. request body + required parameters <= 1
283
- * 5. response body should be “application/json” and not empty, and response code should be 20X
284
- * 6. only support request body with “application/json” content type
285
- */
286
- static isSupportedApi(method, path, spec, options) {
287
- var _a;
288
- const pathObj = spec.paths[path];
289
- method = method.toLocaleLowerCase();
290
- if (pathObj) {
291
- if (((_a = options.allowMethods) === null || _a === void 0 ? void 0 : _a.includes(method)) && pathObj[method]) {
292
- const securities = pathObj[method].security;
293
- const isTeamsAi = options.projectType === ProjectType.TeamsAi;
294
- const isCopilot = options.projectType === ProjectType.Copilot;
295
- // Teams AI project doesn't care about auth, it will use authProvider for user to implement
296
- if (!isTeamsAi) {
297
- const authArray = Utils.getAuthArray(securities, spec);
298
- if (!Utils.isSupportedAuth(authArray, options)) {
299
- return false;
300
- }
301
- }
302
- const operationObject = pathObj[method];
303
- if (!options.allowMissingId && !operationObject.operationId) {
304
- return false;
305
- }
306
- const paramObject = operationObject.parameters;
307
- const requestBody = operationObject.requestBody;
308
- const requestJsonBody = requestBody === null || requestBody === void 0 ? void 0 : requestBody.content["application/json"];
309
- if (!isTeamsAi && Utils.containMultipleMediaTypes(requestBody)) {
310
- return false;
311
- }
312
- const responseJson = Utils.getResponseJson(operationObject, isTeamsAi);
313
- if (Object.keys(responseJson).length === 0) {
314
- return false;
315
- }
316
- // Teams AI project doesn't care about request parameters/body
317
- if (isTeamsAi) {
318
- return true;
319
- }
320
- let requestBodyParamResult = {
321
- requiredNum: 0,
322
- optionalNum: 0,
323
- isValid: true,
324
- };
325
- if (requestJsonBody) {
326
- const requestBodySchema = requestJsonBody.schema;
327
- if (isCopilot && requestBodySchema.type !== "object") {
328
- return false;
329
- }
330
- requestBodyParamResult = Utils.checkPostBody(requestBodySchema, requestBody.required, isCopilot);
331
- }
332
- if (!requestBodyParamResult.isValid) {
333
- return false;
334
- }
335
- const paramResult = Utils.checkParameters(paramObject, isCopilot);
336
- if (!paramResult.isValid) {
337
- return false;
338
- }
339
- // Copilot support arbitrary parameters
340
- if (isCopilot) {
341
- return true;
342
- }
343
- if (requestBodyParamResult.requiredNum + paramResult.requiredNum > 1) {
344
- if (options.allowMultipleParameters &&
345
- requestBodyParamResult.requiredNum + paramResult.requiredNum <=
346
- ConstantString.SMERequiredParamsMaxNum) {
347
- return true;
348
- }
349
- return false;
350
- }
351
- else if (requestBodyParamResult.requiredNum +
352
- requestBodyParamResult.optionalNum +
353
- paramResult.requiredNum +
354
- paramResult.optionalNum ===
355
- 0) {
356
- return false;
357
- }
358
- else {
359
- return true;
360
- }
361
- }
362
- }
363
- return false;
364
- }
365
- static isSupportedAuth(authSchemeArray, options) {
366
- if (authSchemeArray.length === 0) {
367
- return true;
368
- }
369
- if (options.allowAPIKeyAuth || options.allowOauth2 || options.allowBearerTokenAuth) {
370
- // Currently we don't support multiple auth in one operation
371
- if (authSchemeArray.length > 0 && authSchemeArray.every((auths) => auths.length > 1)) {
372
- return false;
373
- }
374
- for (const auths of authSchemeArray) {
375
- if (auths.length === 1) {
376
- if ((options.allowAPIKeyAuth && Utils.isAPIKeyAuth(auths[0].authScheme)) ||
377
- (options.allowOauth2 && Utils.isOAuthWithAuthCodeFlow(auths[0].authScheme)) ||
378
- (options.allowBearerTokenAuth && Utils.isBearerTokenAuth(auths[0].authScheme))) {
379
- return true;
380
- }
381
- }
382
- }
383
- }
384
- return false;
385
- }
386
192
  static isBearerTokenAuth(authScheme) {
387
193
  return authScheme.type === "http" && authScheme.scheme === "bearer";
388
194
  }
@@ -390,10 +196,9 @@ class Utils {
390
196
  return authScheme.type === "apiKey";
391
197
  }
392
198
  static isOAuthWithAuthCodeFlow(authScheme) {
393
- if (authScheme.type === "oauth2" && authScheme.flows && authScheme.flows.authorizationCode) {
394
- return true;
395
- }
396
- return false;
199
+ return !!(authScheme.type === "oauth2" &&
200
+ authScheme.flows &&
201
+ authScheme.flows.authorizationCode);
397
202
  }
398
203
  static getAuthArray(securities, spec) {
399
204
  var _a;
@@ -421,14 +226,17 @@ class Utils {
421
226
  static updateFirstLetter(str) {
422
227
  return str.charAt(0).toUpperCase() + str.slice(1);
423
228
  }
424
- static getResponseJson(operationObject, isTeamsAiProject = false) {
229
+ static getResponseJson(operationObject) {
425
230
  var _a, _b;
426
231
  let json = {};
232
+ let multipleMediaType = false;
427
233
  for (const code of ConstantString.ResponseCodeFor20X) {
428
234
  const responseObject = (_a = operationObject === null || operationObject === void 0 ? void 0 : operationObject.responses) === null || _a === void 0 ? void 0 : _a[code];
429
235
  if ((_b = responseObject === null || responseObject === void 0 ? void 0 : responseObject.content) === null || _b === void 0 ? void 0 : _b["application/json"]) {
236
+ multipleMediaType = false;
430
237
  json = responseObject.content["application/json"];
431
- if (!isTeamsAiProject && Utils.containMultipleMediaTypes(responseObject)) {
238
+ if (Utils.containMultipleMediaTypes(responseObject)) {
239
+ multipleMediaType = true;
432
240
  json = {};
433
241
  }
434
242
  else {
@@ -436,7 +244,7 @@ class Utils {
436
244
  }
437
245
  }
438
246
  }
439
- return json;
247
+ return { json, multipleMediaType };
440
248
  }
441
249
  static convertPathToCamelCase(path) {
442
250
  const pathSegments = path.split(/[./{]/);
@@ -456,10 +264,10 @@ class Utils {
456
264
  return undefined;
457
265
  }
458
266
  }
459
- static resolveServerUrl(url) {
267
+ static resolveEnv(str) {
460
268
  const placeHolderReg = /\${{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*}}/g;
461
- let matches = placeHolderReg.exec(url);
462
- let newUrl = url;
269
+ let matches = placeHolderReg.exec(str);
270
+ let newStr = str;
463
271
  while (matches != null) {
464
272
  const envVar = matches[1];
465
273
  const envVal = process.env[envVar];
@@ -467,17 +275,17 @@ class Utils {
467
275
  throw new Error(Utils.format(ConstantString.ResolveServerUrlFailed, envVar));
468
276
  }
469
277
  else {
470
- newUrl = newUrl.replace(matches[0], envVal);
278
+ newStr = newStr.replace(matches[0], envVal);
471
279
  }
472
- matches = placeHolderReg.exec(url);
280
+ matches = placeHolderReg.exec(str);
473
281
  }
474
- return newUrl;
282
+ return newStr;
475
283
  }
476
284
  static checkServerUrl(servers) {
477
285
  const errors = [];
478
286
  let serverUrl;
479
287
  try {
480
- serverUrl = Utils.resolveServerUrl(servers[0].url);
288
+ serverUrl = Utils.resolveEnv(servers[0].url);
481
289
  }
482
290
  catch (err) {
483
291
  errors.push({
@@ -508,6 +316,7 @@ class Utils {
508
316
  return errors;
509
317
  }
510
318
  static validateServer(spec, options) {
319
+ var _a;
511
320
  const errors = [];
512
321
  let hasTopLevelServers = false;
513
322
  let hasPathLevelServers = false;
@@ -528,7 +337,7 @@ class Utils {
528
337
  }
529
338
  for (const method in methods) {
530
339
  const operationObject = methods[method];
531
- if (Utils.isSupportedApi(method, path, spec, options)) {
340
+ if (((_a = options.allowMethods) === null || _a === void 0 ? void 0 : _a.includes(method)) && operationObject) {
532
341
  if ((operationObject === null || operationObject === void 0 ? void 0 : operationObject.servers) && operationObject.servers.length >= 1) {
533
342
  hasOperationLevelServers = true;
534
343
  const serverErrors = Utils.checkServerUrl(operationObject.servers);
@@ -655,13 +464,7 @@ class Utils {
655
464
  }
656
465
  }
657
466
  const operationId = operationItem.operationId;
658
- const parameters = [];
659
- if (requiredParams.length !== 0) {
660
- parameters.push(...requiredParams);
661
- }
662
- else {
663
- parameters.push(optionalParams[0]);
664
- }
467
+ const parameters = [...requiredParams, ...optionalParams];
665
468
  const command = {
666
469
  context: ["compose"],
667
470
  type: "query",
@@ -670,117 +473,526 @@ class Utils {
670
473
  parameters: parameters,
671
474
  description: ((_b = operationItem.description) !== null && _b !== void 0 ? _b : "").slice(0, ConstantString.CommandDescriptionMaxLens),
672
475
  };
673
- let warning = undefined;
674
- if (requiredParams.length === 0 && optionalParams.length > 1) {
675
- warning = {
676
- type: WarningType.OperationOnlyContainsOptionalParam,
677
- content: Utils.format(ConstantString.OperationOnlyContainsOptionalParam, operationId),
678
- data: operationId,
679
- };
476
+ return command;
477
+ }
478
+ static format(str, ...args) {
479
+ let index = 0;
480
+ return str.replace(/%s/g, () => {
481
+ const arg = args[index++];
482
+ return arg !== undefined ? arg : "";
483
+ });
484
+ }
485
+ static getSafeRegistrationIdEnvName(authName) {
486
+ if (!authName) {
487
+ return "";
680
488
  }
681
- return [command, warning];
489
+ let safeRegistrationIdEnvName = authName.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
490
+ if (!safeRegistrationIdEnvName.match(/^[A-Z]/)) {
491
+ safeRegistrationIdEnvName = "PREFIX_" + safeRegistrationIdEnvName;
492
+ }
493
+ return safeRegistrationIdEnvName;
682
494
  }
683
- static listSupportedAPIs(spec, options) {
684
- const paths = spec.paths;
495
+ static getServerObject(spec, method, path) {
496
+ const pathObj = spec.paths[path];
497
+ const operationObject = pathObj[method];
498
+ const rootServer = spec.servers && spec.servers[0];
499
+ const methodServer = spec.paths[path].servers && spec.paths[path].servers[0];
500
+ const operationServer = operationObject.servers && operationObject.servers[0];
501
+ const serverUrl = operationServer || methodServer || rootServer;
502
+ return serverUrl;
503
+ }
504
+ }
505
+
506
+ // Copyright (c) Microsoft Corporation.
507
+ class Validator {
508
+ listAPIs() {
509
+ var _a;
510
+ if (this.apiMap) {
511
+ return this.apiMap;
512
+ }
513
+ const paths = this.spec.paths;
685
514
  const result = {};
686
515
  for (const path in paths) {
687
516
  const methods = paths[path];
688
517
  for (const method in methods) {
689
- if (Utils.isSupportedApi(method, path, spec, options)) {
690
- const operationObject = methods[method];
691
- result[`${method.toUpperCase()} ${path}`] = operationObject;
518
+ const operationObject = methods[method];
519
+ if (((_a = this.options.allowMethods) === null || _a === void 0 ? void 0 : _a.includes(method)) && operationObject) {
520
+ const validateResult = this.validateAPI(method, path);
521
+ result[`${method.toUpperCase()} ${path}`] = {
522
+ operation: operationObject,
523
+ isValid: validateResult.isValid,
524
+ reason: validateResult.reason,
525
+ };
692
526
  }
693
527
  }
694
528
  }
529
+ this.apiMap = result;
695
530
  return result;
696
531
  }
697
- static validateSpec(spec, parser, isSwaggerFile, options) {
698
- const errors = [];
699
- const warnings = [];
700
- if (isSwaggerFile) {
701
- warnings.push({
702
- type: WarningType.ConvertSwaggerToOpenAPI,
703
- content: ConstantString.ConvertSwaggerToOpenAPI,
704
- });
705
- }
706
- // Server validation
707
- const serverErrors = Utils.validateServer(spec, options);
708
- errors.push(...serverErrors);
709
- // Remote reference not supported
710
- const refPaths = parser.$refs.paths();
711
- // refPaths [0] is the current spec file path
712
- if (refPaths.length > 1) {
713
- errors.push({
714
- type: ErrorType.RemoteRefNotSupported,
715
- content: Utils.format(ConstantString.RemoteRefNotSupported, refPaths.join(", ")),
716
- data: refPaths,
532
+ validateSpecVersion() {
533
+ const result = { errors: [], warnings: [] };
534
+ if (this.spec.openapi >= "3.1.0") {
535
+ result.errors.push({
536
+ type: ErrorType.SpecVersionNotSupported,
537
+ content: Utils.format(ConstantString.SpecVersionNotSupported, this.spec.openapi),
538
+ data: this.spec.openapi,
717
539
  });
718
540
  }
719
- // No supported API
720
- const apiMap = Utils.listSupportedAPIs(spec, options);
721
- if (Object.keys(apiMap).length === 0) {
722
- errors.push({
541
+ return result;
542
+ }
543
+ validateSpecServer() {
544
+ const result = { errors: [], warnings: [] };
545
+ const serverErrors = Utils.validateServer(this.spec, this.options);
546
+ result.errors.push(...serverErrors);
547
+ return result;
548
+ }
549
+ validateSpecNoSupportAPI() {
550
+ const result = { errors: [], warnings: [] };
551
+ const apiMap = this.listAPIs();
552
+ const validAPIs = Object.entries(apiMap).filter(([, value]) => value.isValid);
553
+ if (validAPIs.length === 0) {
554
+ result.errors.push({
723
555
  type: ErrorType.NoSupportedApi,
724
556
  content: ConstantString.NoSupportedApi,
725
557
  });
726
558
  }
559
+ return result;
560
+ }
561
+ validateSpecOperationId() {
562
+ const result = { errors: [], warnings: [] };
563
+ const apiMap = this.listAPIs();
727
564
  // OperationId missing
728
565
  const apisMissingOperationId = [];
729
566
  for (const key in apiMap) {
730
- const pathObjectItem = apiMap[key];
731
- if (!pathObjectItem.operationId) {
567
+ const { operation } = apiMap[key];
568
+ if (!operation.operationId) {
732
569
  apisMissingOperationId.push(key);
733
570
  }
734
571
  }
735
572
  if (apisMissingOperationId.length > 0) {
736
- warnings.push({
573
+ result.warnings.push({
737
574
  type: WarningType.OperationIdMissing,
738
575
  content: Utils.format(ConstantString.MissingOperationId, apisMissingOperationId.join(", ")),
739
576
  data: apisMissingOperationId,
740
577
  });
741
578
  }
742
- let status = ValidationStatus.Valid;
743
- if (warnings.length > 0 && errors.length === 0) {
744
- status = ValidationStatus.Warning;
579
+ return result;
580
+ }
581
+ validateMethodAndPath(method, path) {
582
+ const result = { isValid: true, reason: [] };
583
+ if (this.options.allowMethods && !this.options.allowMethods.includes(method)) {
584
+ result.isValid = false;
585
+ result.reason.push(ErrorType.MethodNotAllowed);
586
+ return result;
745
587
  }
746
- else if (errors.length > 0) {
747
- status = ValidationStatus.Error;
588
+ const pathObj = this.spec.paths[path];
589
+ if (!pathObj || !pathObj[method]) {
590
+ result.isValid = false;
591
+ result.reason.push(ErrorType.UrlPathNotExist);
592
+ return result;
748
593
  }
749
- return {
750
- status,
751
- warnings,
752
- errors,
753
- };
594
+ return result;
754
595
  }
755
- static format(str, ...args) {
756
- let index = 0;
757
- return str.replace(/%s/g, () => {
758
- const arg = args[index++];
759
- return arg !== undefined ? arg : "";
760
- });
596
+ validateResponse(method, path) {
597
+ const result = { isValid: true, reason: [] };
598
+ const operationObject = this.spec.paths[path][method];
599
+ const { json, multipleMediaType } = Utils.getResponseJson(operationObject);
600
+ // only support response body only contains “application/json” content type
601
+ if (multipleMediaType) {
602
+ result.reason.push(ErrorType.ResponseContainMultipleMediaTypes);
603
+ }
604
+ else if (Object.keys(json).length === 0) {
605
+ // response body should not be empty
606
+ result.reason.push(ErrorType.ResponseJsonIsEmpty);
607
+ }
608
+ return result;
761
609
  }
762
- static getSafeRegistrationIdEnvName(authName) {
763
- if (!authName) {
764
- return "";
610
+ validateServer(method, path) {
611
+ const result = { isValid: true, reason: [] };
612
+ const serverObj = Utils.getServerObject(this.spec, method, path);
613
+ if (!serverObj) {
614
+ // should contain server URL
615
+ result.reason.push(ErrorType.NoServerInformation);
765
616
  }
766
- let safeRegistrationIdEnvName = authName.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
767
- if (!safeRegistrationIdEnvName.match(/^[A-Z]/)) {
768
- safeRegistrationIdEnvName = "PREFIX_" + safeRegistrationIdEnvName;
617
+ else {
618
+ // server url should be absolute url with https protocol
619
+ const serverValidateResult = Utils.checkServerUrl([serverObj]);
620
+ result.reason.push(...serverValidateResult.map((item) => item.type));
769
621
  }
770
- return safeRegistrationIdEnvName;
622
+ return result;
771
623
  }
772
- static getAllAPICount(spec) {
773
- let count = 0;
774
- const paths = spec.paths;
775
- for (const path in paths) {
776
- const methods = paths[path];
777
- for (const method in methods) {
778
- if (ConstantString.AllOperationMethods.includes(method)) {
779
- count++;
624
+ validateAuth(method, path) {
625
+ const pathObj = this.spec.paths[path];
626
+ const operationObject = pathObj[method];
627
+ const securities = operationObject.security;
628
+ const authSchemeArray = Utils.getAuthArray(securities, this.spec);
629
+ if (authSchemeArray.length === 0) {
630
+ return { isValid: true, reason: [] };
631
+ }
632
+ if (this.options.allowAPIKeyAuth ||
633
+ this.options.allowOauth2 ||
634
+ this.options.allowBearerTokenAuth) {
635
+ // Currently we don't support multiple auth in one operation
636
+ if (authSchemeArray.length > 0 && authSchemeArray.every((auths) => auths.length > 1)) {
637
+ return {
638
+ isValid: false,
639
+ reason: [ErrorType.MultipleAuthNotSupported],
640
+ };
641
+ }
642
+ for (const auths of authSchemeArray) {
643
+ if (auths.length === 1) {
644
+ if ((this.options.allowAPIKeyAuth && Utils.isAPIKeyAuth(auths[0].authScheme)) ||
645
+ (this.options.allowOauth2 && Utils.isOAuthWithAuthCodeFlow(auths[0].authScheme)) ||
646
+ (this.options.allowBearerTokenAuth && Utils.isBearerTokenAuth(auths[0].authScheme))) {
647
+ return { isValid: true, reason: [] };
648
+ }
649
+ }
650
+ }
651
+ }
652
+ return { isValid: false, reason: [ErrorType.AuthTypeIsNotSupported] };
653
+ }
654
+ checkPostBodySchema(schema, isRequired = false) {
655
+ var _a;
656
+ const paramResult = {
657
+ requiredNum: 0,
658
+ optionalNum: 0,
659
+ isValid: true,
660
+ reason: [],
661
+ };
662
+ if (Object.keys(schema).length === 0) {
663
+ return paramResult;
664
+ }
665
+ const isRequiredWithoutDefault = isRequired && schema.default === undefined;
666
+ const isCopilot = this.projectType === ProjectType.Copilot;
667
+ if (isCopilot && this.hasNestedObjectInSchema(schema)) {
668
+ paramResult.isValid = false;
669
+ paramResult.reason = [ErrorType.RequestBodyContainsNestedObject];
670
+ return paramResult;
671
+ }
672
+ if (schema.type === "string" ||
673
+ schema.type === "integer" ||
674
+ schema.type === "boolean" ||
675
+ schema.type === "number") {
676
+ if (isRequiredWithoutDefault) {
677
+ paramResult.requiredNum = paramResult.requiredNum + 1;
678
+ }
679
+ else {
680
+ paramResult.optionalNum = paramResult.optionalNum + 1;
681
+ }
682
+ }
683
+ else if (schema.type === "object") {
684
+ const { properties } = schema;
685
+ for (const property in properties) {
686
+ let isRequired = false;
687
+ if (schema.required && ((_a = schema.required) === null || _a === void 0 ? void 0 : _a.indexOf(property)) >= 0) {
688
+ isRequired = true;
689
+ }
690
+ const result = this.checkPostBodySchema(properties[property], isRequired);
691
+ paramResult.requiredNum += result.requiredNum;
692
+ paramResult.optionalNum += result.optionalNum;
693
+ paramResult.isValid = paramResult.isValid && result.isValid;
694
+ paramResult.reason.push(...result.reason);
695
+ }
696
+ }
697
+ else {
698
+ if (isRequiredWithoutDefault && !isCopilot) {
699
+ paramResult.isValid = false;
700
+ paramResult.reason.push(ErrorType.PostBodyContainsRequiredUnsupportedSchema);
701
+ }
702
+ }
703
+ return paramResult;
704
+ }
705
+ checkParamSchema(paramObject) {
706
+ const paramResult = {
707
+ requiredNum: 0,
708
+ optionalNum: 0,
709
+ isValid: true,
710
+ reason: [],
711
+ };
712
+ if (!paramObject) {
713
+ return paramResult;
714
+ }
715
+ const isCopilot = this.projectType === ProjectType.Copilot;
716
+ for (let i = 0; i < paramObject.length; i++) {
717
+ const param = paramObject[i];
718
+ const schema = param.schema;
719
+ if (isCopilot && this.hasNestedObjectInSchema(schema)) {
720
+ paramResult.isValid = false;
721
+ paramResult.reason.push(ErrorType.ParamsContainsNestedObject);
722
+ continue;
723
+ }
724
+ const isRequiredWithoutDefault = param.required && schema.default === undefined;
725
+ if (isCopilot) {
726
+ if (isRequiredWithoutDefault) {
727
+ paramResult.requiredNum = paramResult.requiredNum + 1;
728
+ }
729
+ else {
730
+ paramResult.optionalNum = paramResult.optionalNum + 1;
731
+ }
732
+ continue;
733
+ }
734
+ if (param.in === "header" || param.in === "cookie") {
735
+ if (isRequiredWithoutDefault) {
736
+ paramResult.isValid = false;
737
+ paramResult.reason.push(ErrorType.ParamsContainRequiredUnsupportedSchema);
738
+ }
739
+ continue;
740
+ }
741
+ if (schema.type !== "boolean" &&
742
+ schema.type !== "string" &&
743
+ schema.type !== "number" &&
744
+ schema.type !== "integer") {
745
+ if (isRequiredWithoutDefault) {
746
+ paramResult.isValid = false;
747
+ paramResult.reason.push(ErrorType.ParamsContainRequiredUnsupportedSchema);
748
+ }
749
+ continue;
750
+ }
751
+ if (param.in === "query" || param.in === "path") {
752
+ if (isRequiredWithoutDefault) {
753
+ paramResult.requiredNum = paramResult.requiredNum + 1;
754
+ }
755
+ else {
756
+ paramResult.optionalNum = paramResult.optionalNum + 1;
757
+ }
758
+ }
759
+ }
760
+ return paramResult;
761
+ }
762
+ hasNestedObjectInSchema(schema) {
763
+ if (schema.type === "object") {
764
+ for (const property in schema.properties) {
765
+ const nestedSchema = schema.properties[property];
766
+ if (nestedSchema.type === "object") {
767
+ return true;
780
768
  }
781
769
  }
782
770
  }
783
- return count;
771
+ return false;
772
+ }
773
+ }
774
+
775
+ // Copyright (c) Microsoft Corporation.
776
+ class CopilotValidator extends Validator {
777
+ constructor(spec, options) {
778
+ super();
779
+ this.projectType = ProjectType.Copilot;
780
+ this.options = options;
781
+ this.spec = spec;
782
+ }
783
+ validateSpec() {
784
+ const result = { errors: [], warnings: [] };
785
+ // validate spec version
786
+ let validationResult = this.validateSpecVersion();
787
+ result.errors.push(...validationResult.errors);
788
+ // validate spec server
789
+ validationResult = this.validateSpecServer();
790
+ result.errors.push(...validationResult.errors);
791
+ // validate no supported API
792
+ validationResult = this.validateSpecNoSupportAPI();
793
+ result.errors.push(...validationResult.errors);
794
+ // validate operationId missing
795
+ validationResult = this.validateSpecOperationId();
796
+ result.warnings.push(...validationResult.warnings);
797
+ return result;
798
+ }
799
+ validateAPI(method, path) {
800
+ const result = { isValid: true, reason: [] };
801
+ method = method.toLocaleLowerCase();
802
+ // validate method and path
803
+ const methodAndPathResult = this.validateMethodAndPath(method, path);
804
+ if (!methodAndPathResult.isValid) {
805
+ return methodAndPathResult;
806
+ }
807
+ const operationObject = this.spec.paths[path][method];
808
+ // validate auth
809
+ const authCheckResult = this.validateAuth(method, path);
810
+ result.reason.push(...authCheckResult.reason);
811
+ // validate operationId
812
+ if (!this.options.allowMissingId && !operationObject.operationId) {
813
+ result.reason.push(ErrorType.MissingOperationId);
814
+ }
815
+ // validate server
816
+ const validateServerResult = this.validateServer(method, path);
817
+ result.reason.push(...validateServerResult.reason);
818
+ // validate response
819
+ const validateResponseResult = this.validateResponse(method, path);
820
+ result.reason.push(...validateResponseResult.reason);
821
+ // validate requestBody
822
+ const requestBody = operationObject.requestBody;
823
+ const requestJsonBody = requestBody === null || requestBody === void 0 ? void 0 : requestBody.content["application/json"];
824
+ if (Utils.containMultipleMediaTypes(requestBody)) {
825
+ result.reason.push(ErrorType.PostBodyContainMultipleMediaTypes);
826
+ }
827
+ if (requestJsonBody) {
828
+ const requestBodySchema = requestJsonBody.schema;
829
+ if (requestBodySchema.type !== "object") {
830
+ result.reason.push(ErrorType.PostBodySchemaIsNotJson);
831
+ }
832
+ const requestBodyParamResult = this.checkPostBodySchema(requestBodySchema, requestBody.required);
833
+ result.reason.push(...requestBodyParamResult.reason);
834
+ }
835
+ // validate parameters
836
+ const paramObject = operationObject.parameters;
837
+ const paramResult = this.checkParamSchema(paramObject);
838
+ result.reason.push(...paramResult.reason);
839
+ if (result.reason.length > 0) {
840
+ result.isValid = false;
841
+ }
842
+ return result;
843
+ }
844
+ }
845
+
846
+ // Copyright (c) Microsoft Corporation.
847
+ class SMEValidator extends Validator {
848
+ constructor(spec, options) {
849
+ super();
850
+ this.projectType = ProjectType.SME;
851
+ this.options = options;
852
+ this.spec = spec;
853
+ }
854
+ validateSpec() {
855
+ const result = { errors: [], warnings: [] };
856
+ // validate spec version
857
+ let validationResult = this.validateSpecVersion();
858
+ result.errors.push(...validationResult.errors);
859
+ // validate spec server
860
+ validationResult = this.validateSpecServer();
861
+ result.errors.push(...validationResult.errors);
862
+ // validate no supported API
863
+ validationResult = this.validateSpecNoSupportAPI();
864
+ result.errors.push(...validationResult.errors);
865
+ // validate operationId missing
866
+ validationResult = this.validateSpecOperationId();
867
+ result.warnings.push(...validationResult.warnings);
868
+ return result;
869
+ }
870
+ validateAPI(method, path) {
871
+ const result = { isValid: true, reason: [] };
872
+ method = method.toLocaleLowerCase();
873
+ // validate method and path
874
+ const methodAndPathResult = this.validateMethodAndPath(method, path);
875
+ if (!methodAndPathResult.isValid) {
876
+ return methodAndPathResult;
877
+ }
878
+ const operationObject = this.spec.paths[path][method];
879
+ // validate auth
880
+ const authCheckResult = this.validateAuth(method, path);
881
+ result.reason.push(...authCheckResult.reason);
882
+ // validate operationId
883
+ if (!this.options.allowMissingId && !operationObject.operationId) {
884
+ result.reason.push(ErrorType.MissingOperationId);
885
+ }
886
+ // validate server
887
+ const validateServerResult = this.validateServer(method, path);
888
+ result.reason.push(...validateServerResult.reason);
889
+ // validate response
890
+ const validateResponseResult = this.validateResponse(method, path);
891
+ result.reason.push(...validateResponseResult.reason);
892
+ let postBodyResult = {
893
+ requiredNum: 0,
894
+ optionalNum: 0,
895
+ isValid: true,
896
+ reason: [],
897
+ };
898
+ // validate requestBody
899
+ const requestBody = operationObject.requestBody;
900
+ const requestJsonBody = requestBody === null || requestBody === void 0 ? void 0 : requestBody.content["application/json"];
901
+ if (Utils.containMultipleMediaTypes(requestBody)) {
902
+ result.reason.push(ErrorType.PostBodyContainMultipleMediaTypes);
903
+ }
904
+ if (requestJsonBody) {
905
+ const requestBodySchema = requestJsonBody.schema;
906
+ postBodyResult = this.checkPostBodySchema(requestBodySchema, requestBody.required);
907
+ result.reason.push(...postBodyResult.reason);
908
+ }
909
+ // validate parameters
910
+ const paramObject = operationObject.parameters;
911
+ const paramResult = this.checkParamSchema(paramObject);
912
+ result.reason.push(...paramResult.reason);
913
+ // validate total parameters count
914
+ if (paramResult.isValid && postBodyResult.isValid) {
915
+ const paramCountResult = this.validateParamCount(postBodyResult, paramResult);
916
+ result.reason.push(...paramCountResult.reason);
917
+ }
918
+ if (result.reason.length > 0) {
919
+ result.isValid = false;
920
+ }
921
+ return result;
922
+ }
923
+ validateParamCount(postBodyResult, paramResult) {
924
+ const result = { isValid: true, reason: [] };
925
+ const totalRequiredParams = postBodyResult.requiredNum + paramResult.requiredNum;
926
+ const totalParams = totalRequiredParams + postBodyResult.optionalNum + paramResult.optionalNum;
927
+ if (totalRequiredParams > 1) {
928
+ if (!this.options.allowMultipleParameters ||
929
+ totalRequiredParams > SMEValidator.SMERequiredParamsMaxNum) {
930
+ result.reason.push(ErrorType.ExceededRequiredParamsLimit);
931
+ }
932
+ }
933
+ else if (totalParams === 0) {
934
+ result.reason.push(ErrorType.NoParameter);
935
+ }
936
+ return result;
937
+ }
938
+ }
939
+ SMEValidator.SMERequiredParamsMaxNum = 5;
940
+
941
+ // Copyright (c) Microsoft Corporation.
942
+ class TeamsAIValidator extends Validator {
943
+ constructor(spec, options) {
944
+ super();
945
+ this.projectType = ProjectType.TeamsAi;
946
+ this.options = options;
947
+ this.spec = spec;
948
+ }
949
+ validateSpec() {
950
+ const result = { errors: [], warnings: [] };
951
+ // validate spec server
952
+ let validationResult = this.validateSpecServer();
953
+ result.errors.push(...validationResult.errors);
954
+ // validate no supported API
955
+ validationResult = this.validateSpecNoSupportAPI();
956
+ result.errors.push(...validationResult.errors);
957
+ return result;
958
+ }
959
+ validateAPI(method, path) {
960
+ const result = { isValid: true, reason: [] };
961
+ method = method.toLocaleLowerCase();
962
+ // validate method and path
963
+ const methodAndPathResult = this.validateMethodAndPath(method, path);
964
+ if (!methodAndPathResult.isValid) {
965
+ return methodAndPathResult;
966
+ }
967
+ const operationObject = this.spec.paths[path][method];
968
+ // validate operationId
969
+ if (!this.options.allowMissingId && !operationObject.operationId) {
970
+ result.reason.push(ErrorType.MissingOperationId);
971
+ }
972
+ // validate server
973
+ const validateServerResult = this.validateServer(method, path);
974
+ result.reason.push(...validateServerResult.reason);
975
+ if (result.reason.length > 0) {
976
+ result.isValid = false;
977
+ }
978
+ return result;
979
+ }
980
+ }
981
+
982
+ class ValidatorFactory {
983
+ static create(spec, options) {
984
+ var _a;
985
+ const type = (_a = options.projectType) !== null && _a !== void 0 ? _a : ProjectType.SME;
986
+ switch (type) {
987
+ case ProjectType.SME:
988
+ return new SMEValidator(spec, options);
989
+ case ProjectType.Copilot:
990
+ return new CopilotValidator(spec, options);
991
+ case ProjectType.TeamsAi:
992
+ return new TeamsAIValidator(spec, options);
993
+ default:
994
+ throw new Error(`Invalid project type: ${type}`);
995
+ }
784
996
  }
785
997
  }
786
998
 
@@ -818,11 +1030,7 @@ class SpecParser {
818
1030
  try {
819
1031
  try {
820
1032
  await this.loadSpec();
821
- await this.parser.validate(this.spec, {
822
- validate: {
823
- schema: false,
824
- },
825
- });
1033
+ await this.parser.validate(this.spec);
826
1034
  }
827
1035
  catch (e) {
828
1036
  return {
@@ -831,16 +1039,46 @@ class SpecParser {
831
1039
  errors: [{ type: ErrorType.SpecNotValid, content: e.toString() }],
832
1040
  };
833
1041
  }
1042
+ const errors = [];
1043
+ const warnings = [];
834
1044
  if (!this.options.allowSwagger && this.isSwaggerFile) {
835
1045
  return {
836
1046
  status: ValidationStatus.Error,
837
1047
  warnings: [],
838
1048
  errors: [
839
- { type: ErrorType.SwaggerNotSupported, content: ConstantString.SwaggerNotSupported },
1049
+ {
1050
+ type: ErrorType.SwaggerNotSupported,
1051
+ content: ConstantString.SwaggerNotSupported,
1052
+ },
840
1053
  ],
841
1054
  };
842
1055
  }
843
- return Utils.validateSpec(this.spec, this.parser, !!this.isSwaggerFile, this.options);
1056
+ // Remote reference not supported
1057
+ const refPaths = this.parser.$refs.paths();
1058
+ // refPaths [0] is the current spec file path
1059
+ if (refPaths.length > 1) {
1060
+ errors.push({
1061
+ type: ErrorType.RemoteRefNotSupported,
1062
+ content: Utils.format(ConstantString.RemoteRefNotSupported, refPaths.join(", ")),
1063
+ data: refPaths,
1064
+ });
1065
+ }
1066
+ const validator = this.getValidator(this.spec);
1067
+ const validationResult = validator.validateSpec();
1068
+ warnings.push(...validationResult.warnings);
1069
+ errors.push(...validationResult.errors);
1070
+ let status = ValidationStatus.Valid;
1071
+ if (warnings.length > 0 && errors.length === 0) {
1072
+ status = ValidationStatus.Warning;
1073
+ }
1074
+ else if (errors.length > 0) {
1075
+ status = ValidationStatus.Error;
1076
+ }
1077
+ return {
1078
+ status: status,
1079
+ warnings: warnings,
1080
+ errors: errors,
1081
+ };
844
1082
  }
845
1083
  catch (err) {
846
1084
  throw new SpecParserError(err.toString(), ErrorType.ValidateFailed);
@@ -849,17 +1087,20 @@ class SpecParser {
849
1087
  async listSupportedAPIInfo() {
850
1088
  try {
851
1089
  await this.loadSpec();
852
- const apiMap = this.getAllSupportedAPIs(this.spec);
1090
+ const apiMap = this.getAPIs(this.spec);
853
1091
  const apiInfos = [];
854
1092
  for (const key in apiMap) {
855
- const pathObjectItem = apiMap[key];
1093
+ const { operation, isValid } = apiMap[key];
1094
+ if (!isValid) {
1095
+ continue;
1096
+ }
856
1097
  const [method, path] = key.split(" ");
857
- const operationId = pathObjectItem.operationId;
1098
+ const operationId = operation.operationId;
858
1099
  // In Browser environment, this api is by default not support api without operationId
859
1100
  if (!operationId) {
860
1101
  continue;
861
1102
  }
862
- const [command, warning] = Utils.parseApiInfo(pathObjectItem, this.options);
1103
+ const command = Utils.parseApiInfo(operation, this.options);
863
1104
  const apiInfo = {
864
1105
  method: method,
865
1106
  path: path,
@@ -868,9 +1109,6 @@ class SpecParser {
868
1109
  parameters: command.parameters,
869
1110
  description: command.description,
870
1111
  };
871
- if (warning) {
872
- apiInfo.warning = warning;
873
- }
874
1112
  apiInfos.push(apiInfo);
875
1113
  }
876
1114
  return apiInfos;
@@ -929,13 +1167,22 @@ class SpecParser {
929
1167
  this.spec = (await this.parser.dereference(clonedUnResolveSpec));
930
1168
  }
931
1169
  }
932
- getAllSupportedAPIs(spec) {
1170
+ getAPIs(spec) {
933
1171
  if (this.apiMap !== undefined) {
934
1172
  return this.apiMap;
935
1173
  }
936
- const result = Utils.listSupportedAPIs(spec, this.options);
937
- this.apiMap = result;
938
- return result;
1174
+ const validator = this.getValidator(spec);
1175
+ const apiMap = validator.listAPIs();
1176
+ this.apiMap = apiMap;
1177
+ return apiMap;
1178
+ }
1179
+ getValidator(spec) {
1180
+ if (this.validator) {
1181
+ return this.validator;
1182
+ }
1183
+ const validator = ValidatorFactory.create(spec, this.options);
1184
+ this.validator = validator;
1185
+ return validator;
939
1186
  }
940
1187
  }
941
1188
 
@@ -943,7 +1190,7 @@ class SpecParser {
943
1190
  class AdaptiveCardGenerator {
944
1191
  static generateAdaptiveCard(operationItem) {
945
1192
  try {
946
- const json = Utils.getResponseJson(operationItem);
1193
+ const { json } = Utils.getResponseJson(operationItem);
947
1194
  let cardBody = [];
948
1195
  let schema = json.schema;
949
1196
  let jsonPath = "$";