-
Notifications
You must be signed in to change notification settings - Fork 370
Expand file tree
/
Copy pathopenapi.ts
More file actions
2085 lines (1901 loc) · 64.2 KB
/
openapi.ts
File metadata and controls
2085 lines (1901 loc) · 64.2 KB
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AssetEmitter, EmitEntity } from "@typespec/asset-emitter";
import {
compilerAssert,
createDiagnosticCollector,
Diagnostic,
DiagnosticCollector,
EmitContext,
emitFile,
Example,
getAllTags,
getAnyExtensionFromPath,
getDoc,
getFormat,
getMaxItems,
getMaxLength,
getMaxValueExclusive,
getMinItems,
getMinLength,
getMinValueExclusive,
getNamespaceFullName,
getPattern,
getService,
getSummary,
ignoreDiagnostics,
interpolatePath,
isDeprecated,
isGlobalNamespace,
isNeverType,
isSecret,
isVoidType,
listServices,
ModelProperty,
Namespace,
navigateTypesInNamespace,
NewLine,
Program,
resolvePath,
Service,
Type,
TypeNameOptions,
} from "@typespec/compiler";
import {
unsafe_mutateSubgraphWithNamespace,
unsafe_MutatorWithNamespace,
} from "@typespec/compiler/experimental";
import { $ } from "@typespec/compiler/typekit";
import { createPerfReporter, perf } from "@typespec/compiler/utils";
import {
AuthenticationOptionReference,
AuthenticationReference,
createMetadataInfo,
getHttpService,
getServers,
getStatusCodeDescription,
HttpAuth,
HttpOperation,
HttpOperationMultipartBody,
HttpOperationPart,
HttpOperationResponse,
HttpOperationResponseContent,
HttpPayloadBody,
HttpProperty,
HttpServer,
HttpServiceAuthentication,
isOrExtendsHttpFile,
isOverloadSameEndpoint,
MetadataInfo,
reportIfNoRoutes,
resolveAuthentication,
resolveRequestVisibility,
Visibility,
} from "@typespec/http";
import { getStreamMetadata } from "@typespec/http/experimental";
import {
getExtensions,
getExternalDocs,
getOpenAPITypeName,
getParameterKey,
getTagsMetadata,
isReadonlyProperty,
shouldInline,
} from "@typespec/openapi";
import { stringify } from "yaml";
import { getRef } from "./decorators.js";
import { getExampleOrExamples, OperationExamples, resolveOperationExamples } from "./examples.js";
import { JsonSchemaModule, resolveJsonSchemaModule } from "./json-schema.js";
import {
createDiagnostic,
FileType,
OpenAPI3EmitterOptions,
OpenAPIVersion,
OperationIdStrategy,
reportDiagnostic,
} from "./lib.js";
import { getOpenApiSpecProps } from "./openapi-spec-mappings.js";
import { OperationIdResolver } from "./operation-id-resolver/operation-id-resolver.js";
import { getParameterStyle } from "./parameters.js";
import { getMaxValueAsJson, getMinValueAsJson } from "./range.js";
import { resolveSSEModule, SSEModule } from "./sse-module.js";
import { getOpenAPI3StatusCodes } from "./status-codes.js";
import {
OpenAPI3Encoding,
OpenAPI3Header,
OpenAPI3MediaType,
OpenAPI3OAuthFlows,
OpenAPI3Operation,
OpenAPI3Parameter,
OpenAPI3ParameterBase,
OpenAPI3RequestBody,
OpenAPI3Response,
OpenAPI3Schema,
OpenAPI3SecurityScheme,
OpenAPI3Server,
OpenAPI3ServerVariable,
OpenAPI3ServiceRecord,
OpenAPI3StatusCode,
OpenAPI3Tag,
OpenAPI3VersionedServiceRecord,
OpenAPISchema3_1,
OpenAPITag3_2,
Refable,
SupportedOpenAPIDocuments,
} from "./types.js";
import {
deepEquals,
ensureValidComponentFixedFieldKey,
getDefaultValue,
HttpParameterProperties,
isBytesKeptRaw,
isSharedHttpOperation,
SharedHttpOperation,
} from "./util.js";
import { resolveVersioningModule } from "./versioning-module.js";
import { resolveVisibilityUsage, VisibilityUsageTracker } from "./visibility-usage.js";
import { resolveXmlModule, XmlModule } from "./xml-module.js";
const defaultFileType: FileType = "yaml";
const defaultOptions = {
"new-line": "lf",
"omit-unreachable-types": false,
"include-x-typespec-name": "never",
"safeint-strategy": "int64",
"seal-object-schemas": false,
} as const;
export async function $onEmit(context: EmitContext<OpenAPI3EmitterOptions>) {
const options = resolveOptions(context);
for (const specVersion of options.openapiVersions) {
const emitter = createOAPIEmitter(context, options, specVersion);
const { perf } = await emitter.emitOpenAPI();
for (const [key, duration] of Object.entries(perf)) {
context.perf.report(key, duration);
}
}
}
type IrrelevantOpenAPI3EmitterOptionsForObject = "file-type" | "output-file" | "new-line";
/**
* Get the OpenAPI 3 document records from the given program. The documents are
* returned as a JS object.
*
* @param program The program to emit to OpenAPI 3
* @param options OpenAPI 3 emit options
* @returns An array of OpenAPI 3 document records.
*/
export async function getOpenAPI3(
program: Program,
options: Omit<OpenAPI3EmitterOptions, IrrelevantOpenAPI3EmitterOptionsForObject> = {},
): Promise<OpenAPI3ServiceRecord[]> {
const context: EmitContext<any> = {
program,
// this value doesn't matter for getting the OpenAPI3 objects
emitterOutputDir: "tsp-output",
options: options,
perf: createPerfReporter(),
};
const resolvedOptions = resolveOptions(context);
const serviceRecords: OpenAPI3ServiceRecord[] = [];
for (const specVersion of resolvedOptions.openapiVersions) {
const emitter = createOAPIEmitter(context, resolvedOptions, specVersion);
serviceRecords.push(...(await emitter.getOpenAPI()));
}
return serviceRecords;
}
function findFileTypeFromFilename(filename: string | undefined): FileType {
if (filename === undefined) {
return defaultFileType;
}
switch (getAnyExtensionFromPath(filename)) {
case ".yaml":
case ".yml":
return "yaml";
case ".json":
return "json";
default:
return defaultFileType;
}
}
export function resolveOptions(
context: EmitContext<OpenAPI3EmitterOptions>,
): ResolvedOpenAPI3EmitterOptions {
const resolvedOptions = { ...defaultOptions, ...context.options };
const rawFileType = resolvedOptions["file-type"];
const fileTypes: FileType[] = Array.isArray(rawFileType)
? rawFileType
: [rawFileType ?? findFileTypeFromFilename(resolvedOptions["output-file"])];
const outputFile =
resolvedOptions["output-file"] ??
(fileTypes.length > 1
? `openapi.{service-name-if-multiple}.{version}.{file-type}`
: `openapi.{service-name-if-multiple}.{version}.${fileTypes[0]}`);
const openapiVersions = resolvedOptions["openapi-versions"] ?? ["3.0.0"];
const specDir = openapiVersions.length > 1 ? "{openapi-version}" : "";
return {
fileTypes,
newLine: resolvedOptions["new-line"],
omitUnreachableTypes: resolvedOptions["omit-unreachable-types"],
includeXTypeSpecName: resolvedOptions["include-x-typespec-name"],
safeintStrategy: resolvedOptions["safeint-strategy"],
outputFile: resolvePath(context.emitterOutputDir, specDir, outputFile),
openapiVersions,
sealObjectSchemas: resolvedOptions["seal-object-schemas"],
parameterExamplesStrategy: resolvedOptions["experimental-parameter-examples"],
operationIdStrategy: resolveOperationIdStrategy(resolvedOptions["operation-id-strategy"]),
};
}
const defaultOperationIdStrategy = { kind: "parent-container", separator: "_" } as const;
function resolveOperationIdStrategy(
strategy?: OperationIdStrategy | { kind: OperationIdStrategy; separator?: string },
): { kind: OperationIdStrategy; separator: string } {
if (strategy === undefined) {
return defaultOperationIdStrategy;
}
if (typeof strategy === "string") {
return { kind: strategy, separator: resolveOperationIdDefaultStrategySeparator(strategy) };
}
return {
kind: strategy.kind,
separator: strategy.separator ?? resolveOperationIdDefaultStrategySeparator(strategy.kind),
};
}
function resolveOperationIdDefaultStrategySeparator(strategy: OperationIdStrategy) {
switch (strategy) {
case "parent-container":
return "_";
case "fqn":
return ".";
case "explicit-only":
return "";
}
}
export interface ResolvedOpenAPI3EmitterOptions {
fileTypes: FileType[];
outputFile: string;
openapiVersions: OpenAPIVersion[];
newLine: NewLine;
omitUnreachableTypes: boolean;
includeXTypeSpecName: "inline-only" | "never";
safeintStrategy: "double-int" | "int64";
sealObjectSchemas: boolean;
parameterExamplesStrategy?: "data" | "serialized";
operationIdStrategy: { kind: OperationIdStrategy; separator: string };
}
function createOAPIEmitter(
context: EmitContext<OpenAPI3EmitterOptions>,
options: ResolvedOpenAPI3EmitterOptions,
specVersion: OpenAPIVersion = "3.0.0",
) {
const {
applyEncoding,
createRootDoc,
createSchemaEmitter,
getRawBinarySchema,
isRawBinarySchema,
} = getOpenApiSpecProps(specVersion);
const program = context.program;
let schemaEmitter: AssetEmitter<OpenAPI3Schema | OpenAPISchema3_1, OpenAPI3EmitterOptions>;
let operationIdResolver: OperationIdResolver;
let root: SupportedOpenAPIDocuments;
let diagnostics: DiagnosticCollector;
let currentService: Service;
let serviceAuth: HttpServiceAuthentication;
// Get the service namespace string for use in name shortening
let serviceNamespaceName: string | undefined;
let currentPath: any;
let metadataInfo: MetadataInfo;
let visibilityUsage: VisibilityUsageTracker;
let sseModule: SSEModule | undefined;
let jsonSchemaModule: JsonSchemaModule | undefined;
// Map model properties that represent shared parameters to their parameter
// definition that will go in #/components/parameters. Inlined parameters do not go in
// this map.
let params: Map<ModelProperty, any>;
// Keep track of models that have had properties spread into parameters. We won't
// consider these unreferenced when emitting unreferenced types.
let paramModels: Set<Type>;
// De-dupe the per-endpoint tags that will be added into the #/tags
let tagsUsedInOperations: Set<string>;
const typeNameOptions: TypeNameOptions = {
// shorten type names by removing TypeSpec and service namespace
namespaceFilter(ns) {
const name = getNamespaceFullName(ns);
return name !== serviceNamespaceName;
},
};
return { emitOpenAPI, getOpenAPI };
/**
* Check if an HTTP operation or its container (interface/namespace) is deprecated
*/
function isOperationDeprecated(httpOp: HttpOperation): boolean {
if (isDeprecated(program, httpOp.operation)) {
return true;
}
if (isDeprecated(program, httpOp.container)) {
return true;
}
// Check parent namespaces recursively
let current = httpOp.container.namespace;
while (current && current.name !== "") {
if (isDeprecated(program, current)) {
return true;
}
current = current.namespace;
}
return false;
}
async function emitOpenAPI() {
const computeTimer = perf.startTimer();
const services = await getOpenAPI();
const computeTime = computeTimer.end();
// first, emit diagnostics
for (const serviceRecord of services) {
if (serviceRecord.versioned) {
for (const documentRecord of serviceRecord.versions) {
program.reportDiagnostics(documentRecord.diagnostics);
}
} else {
program.reportDiagnostics(serviceRecord.diagnostics);
}
}
if (program.compilerOptions.dryRun || program.hasError()) {
return { perf: { compute: computeTime } };
}
const multipleService = services.length > 1;
const writeTimer = perf.startTimer();
for (const serviceRecord of services) {
for (const fileType of options.fileTypes) {
if (serviceRecord.versioned) {
for (const documentRecord of serviceRecord.versions) {
await emitFile(program, {
path: resolveOutputFile(
serviceRecord.service,
multipleService,
fileType,
documentRecord.version,
),
content: serializeDocument(documentRecord.document, fileType),
newLine: options.newLine,
});
}
} else {
await emitFile(program, {
path: resolveOutputFile(serviceRecord.service, multipleService, fileType),
content: serializeDocument(serviceRecord.document, fileType),
newLine: options.newLine,
});
}
}
}
const writeTime = writeTimer.end();
return {
perf: {
compute: computeTime,
write: writeTime,
},
};
}
function initializeEmitter(
service: Service,
allHttpAuthentications: HttpAuth[],
defaultAuth: AuthenticationReference,
optionalDependencies: {
jsonSchemaModule?: JsonSchemaModule;
xmlModule?: XmlModule;
sseModule?: SSEModule;
},
version?: string,
) {
diagnostics = createDiagnosticCollector();
currentService = service;
sseModule = optionalDependencies.sseModule;
jsonSchemaModule = optionalDependencies.jsonSchemaModule;
metadataInfo = createMetadataInfo(program, {
canonicalVisibility: Visibility.Read,
canShareProperty: (p) => isReadonlyProperty(program, p),
});
visibilityUsage = resolveVisibilityUsage(
program,
metadataInfo,
service.type,
options.omitUnreachableTypes,
);
schemaEmitter = createSchemaEmitter({
program,
context,
metadataInfo,
visibilityUsage,
options,
optionalDependencies,
});
operationIdResolver = new OperationIdResolver(program, {
strategy: options.operationIdStrategy.kind,
separator: options.operationIdStrategy.separator,
});
const securitySchemes = getOpenAPISecuritySchemes(allHttpAuthentications);
const security = getOpenAPISecurity(defaultAuth);
root = createRootDoc(program, service.type, version);
if (security.length > 0) {
root.security = security;
}
root.components!.securitySchemes = securitySchemes;
const servers = getServers(program, service.type);
if (servers) {
root.servers = resolveServers(servers);
}
attachExtensions(program, service.type, root);
serviceNamespaceName = getNamespaceFullName(service.type);
currentPath = root.paths;
params = new Map();
paramModels = new Set();
tagsUsedInOperations = new Set();
}
function isValidServerVariableType(program: Program, type: Type): boolean {
const tk = $(program);
switch (type.kind) {
case "String":
case "Union":
case "Scalar":
return tk.type.isAssignableTo(type, tk.builtin.string, type);
case "Enum":
for (const member of type.members.values()) {
if (member.value && typeof member.value !== "string") {
return false;
}
}
return true;
default:
return false;
}
}
function validateValidServerVariable(program: Program, prop: ModelProperty) {
const isValid = isValidServerVariableType(program, prop.type);
if (!isValid) {
diagnostics.add(
createDiagnostic({
code: "invalid-server-variable",
format: { propName: prop.name },
target: prop,
}),
);
}
return isValid;
}
function resolveServers(servers: HttpServer[]): OpenAPI3Server[] {
return servers.map((server) => {
const variables: Record<string, OpenAPI3ServerVariable> = {};
for (const [name, prop] of server.parameters) {
if (!validateValidServerVariable(program, prop)) {
continue;
}
const variable: OpenAPI3ServerVariable = {
default: prop.defaultValue ? getDefaultValue(program, prop.defaultValue, prop) : "",
description: getDoc(program, prop),
};
if (prop.type.kind === "Enum") {
variable.enum = getSchemaValue(prop.type, Visibility.Read, "application/json")
.enum as any;
} else if (prop.type.kind === "Union") {
variable.enum = getSchemaValue(prop.type, Visibility.Read, "application/json")
.enum as any;
} else if (prop.type.kind === "String") {
variable.enum = [prop.type.value];
}
attachExtensions(program, prop, variable);
variables[name] = variable;
}
return {
url: server.url,
description: server.description,
variables,
};
});
}
async function getOpenAPI(): Promise<OpenAPI3ServiceRecord[]> {
const versioningModule = await resolveVersioningModule();
const serviceRecords: OpenAPI3ServiceRecord[] = [];
const services = listServices(program);
if (services.length === 0) {
services.push({ type: program.getGlobalNamespaceType() });
}
for (const service of services) {
const versions = versioningModule?.getVersioningMutators(program, service.type);
if (versions === undefined) {
const document = await getOpenApiFromVersion(service);
if (document === undefined) {
// an error occurred producing this document, so don't return it
return serviceRecords;
}
serviceRecords.push({
service,
versioned: false,
document: document[0],
diagnostics: document[1],
});
} else if (versions.kind === "transient") {
const document = await getVersionSnapshotDocument(service, versions.mutator);
if (document === undefined) {
// an error occurred producing this document, so don't return it
return serviceRecords;
}
serviceRecords.push({
service,
versioned: false,
document: document[0],
diagnostics: document[1],
});
} else {
// versioned spec
const serviceRecord: OpenAPI3VersionedServiceRecord = {
service,
versioned: true,
versions: [],
};
serviceRecords.push(serviceRecord);
for (const snapshot of versions.snapshots) {
const document = await getVersionSnapshotDocument(
service,
snapshot.mutator,
snapshot.version?.value,
);
if (document === undefined) {
// an error occurred producing this document
continue;
}
serviceRecord.versions.push({
service,
version: snapshot.version!.value,
document: document[0],
diagnostics: document[1],
});
}
}
}
return serviceRecords;
}
async function getVersionSnapshotDocument(
service: Service,
mutator: unsafe_MutatorWithNamespace,
version?: string,
) {
const subgraph = unsafe_mutateSubgraphWithNamespace(program, [mutator], service.type);
compilerAssert(subgraph.type.kind === "Namespace", "Should not have mutated to another type");
const document = await getOpenApiFromVersion(getService(program, subgraph.type)!, version);
return document;
}
function resolveOutputFile(
service: Service,
multipleService: boolean,
fileType: FileType,
version?: string,
): string {
return interpolatePath(options.outputFile, {
"openapi-version": specVersion,
"service-name-if-multiple": multipleService ? getNamespaceFullName(service.type) : undefined,
"service-name": getNamespaceFullName(service.type),
"file-type": fileType,
version,
});
}
/**
* Validates that common responses are consistent and returns the minimal set that describes the differences.
*/
function deduplicateCommonResponses(
statusCodeResponses: HttpOperationResponse[],
): HttpOperationResponse[] {
const ref = statusCodeResponses[0];
const sameTypeKind = statusCodeResponses.every((r) => r.type.kind === ref.type.kind);
const sameTypeValue = statusCodeResponses.every((r) => r.type === ref.type);
if (sameTypeKind && sameTypeValue) {
// response is consistent and in all shared operations. Only need one copy.
return [ref];
} else {
return statusCodeResponses;
}
}
/**
* Validates that common parameters are consistent and returns the minimal set that describes the differences.
*/
function resolveSharedRouteParameters(ops: HttpOperation[]): HttpProperty[] {
const finalProps: HttpParameterProperties[] = [];
const properties = new Map<string, HttpParameterProperties[]>();
for (const op of ops) {
for (const property of op.parameters.properties) {
if (!isHttpParameterProperty(property)) {
continue;
}
const existing = properties.get(property.options.name);
if (existing) {
existing.push(property);
} else {
properties.set(property.options.name, [property]);
}
}
}
if (properties.size === 0) {
return [];
}
for (const sharedParams of properties.values()) {
const reference = sharedParams[0];
const inAllOps = ops.length === sharedParams.length;
const sameLocations = sharedParams.every((p) => p.kind === reference.kind);
const sameOptionality = sharedParams.every(
(p) => p.property.optional === reference.property.optional,
);
const sameTypeKind = sharedParams.every(
(p) => p.property.type.kind === reference.property.type.kind,
);
const sameTypeValue = sharedParams.every((p) => p.property.type === reference.property.type);
if (inAllOps && sameLocations && sameOptionality && sameTypeKind && sameTypeValue) {
// param is consistent and in all shared operations. Only need one copy.
finalProps.push(reference);
} else if (!inAllOps && sameLocations && sameOptionality && sameTypeKind && sameTypeValue) {
// param is consistent when used, but does not appear in all shared operations. Only need one copy, but it must be optional.
reference.property.optional = true;
finalProps.push(reference);
} else if (inAllOps && !(sameLocations && sameOptionality && sameTypeKind)) {
// param is in all shared operations, but is not consistent. Need multiple copies, which must be optional.
// exception allowed when the params only differ by their value (e.g. string enum values)
sharedParams.forEach((p) => {
p.property.optional = true;
});
finalProps.push(...sharedParams);
} else {
finalProps.push(...sharedParams);
}
}
return finalProps;
}
function buildSharedOperation(operations: HttpOperation[]): SharedHttpOperation {
return {
kind: "shared",
operations: operations,
};
}
/**
* Groups HttpOperations together if they share the same route.
*/
function resolveOperations(operations: HttpOperation[]): (HttpOperation | SharedHttpOperation)[] {
const result: (HttpOperation | SharedHttpOperation)[] = [];
const pathMap = new Map<string, HttpOperation[]>();
operations.forEach((op) => {
// we don't emit overloads anyhow so emit them from grouping
if (op.overloading !== undefined && isOverloadSameEndpoint(op as any)) {
return;
}
const opKey = `${op.verb}|${op.path}`;
pathMap.has(opKey) ? pathMap.get(opKey)!.push(op) : pathMap.set(opKey, [op]);
});
// now push either the singular HttpOperations or the constructed SharedHttpOperations
for (const [_, ops] of pathMap) {
if (ops.length === 1) {
result.push(ops[0]);
} else {
result.push(buildSharedOperation(ops));
}
}
return result;
}
async function getOpenApiFromVersion(
service: Service,
version?: string,
): Promise<[SupportedOpenAPIDocuments, Readonly<Diagnostic[]>] | undefined> {
try {
const httpService = ignoreDiagnostics(getHttpService(program, service.type));
const auth = (serviceAuth = resolveAuthentication(httpService));
const xmlModule = await resolveXmlModule();
const jsonSchemaModule = await resolveJsonSchemaModule();
const sseModule = await resolveSSEModule();
initializeEmitter(
service,
auth.schemes,
auth.defaultAuth,
{ xmlModule, jsonSchemaModule, sseModule },
version,
);
reportIfNoRoutes(program, httpService.operations);
for (const op of resolveOperations(httpService.operations)) {
const result = getOperationOrSharedOperation(op);
if (result) {
const { operation, path, verb } = result;
currentPath[path] ??= {};
currentPath[path][verb] = operation;
}
}
emitParameters();
emitSchemas(service.type);
root.tags = resolveDocumentTags(service);
// Clean up empty entries
if (root.components) {
for (const elem of Object.keys(root.components)) {
if (Object.keys(root.components[elem as any]).length === 0) {
delete root.components[elem as any];
}
}
}
return [root, diagnostics.diagnostics];
} catch (err) {
if (err instanceof ErrorTypeFoundError) {
// Return early, there must be a parse error if an ErrorType was
// inserted into the TypeSpec output
return;
} else {
throw err;
}
}
}
function joinOps(
operations: HttpOperation[],
func: (program: Program, type: Type) => string | undefined,
joinChar: string,
): string | undefined {
const values = operations
.map((op) => func(program, op.operation))
.filter((op) => op !== undefined) as string[];
if (values.length) {
return values.join(joinChar);
} else {
return undefined;
}
}
function computeSharedOperationId(shared: SharedHttpOperation) {
if (options.operationIdStrategy.kind === "explicit-only") return undefined;
const operationIds = shared.operations.map((op) => operationIdResolver.resolve(op.operation)!);
const uniqueOpIds = new Set<string>(operationIds);
if (uniqueOpIds.size === 1) return uniqueOpIds.values().next().value;
return operationIds.join("_");
}
function getOperationOrSharedOperation(operation: HttpOperation | SharedHttpOperation):
| {
operation: OpenAPI3Operation;
path: string;
verb: string;
}
| undefined {
if (isSharedHttpOperation(operation)) {
return getSharedOperation(operation);
} else {
return getOperation(operation);
}
}
function getSharedOperation(shared: SharedHttpOperation): {
operation: OpenAPI3Operation;
path: string;
verb: string;
} {
const operations = shared.operations;
const verb = operations[0].verb;
const path = operations[0].path;
const examples = resolveOperationExamples(program, shared, {
parameterExamplesStrategy: options.parameterExamplesStrategy,
});
const oai3Operation: OpenAPI3Operation = {
operationId: computeSharedOperationId(shared),
parameters: [],
description: joinOps(operations, getDoc, " "),
summary: joinOps(operations, getSummary, " "),
responses: getSharedResponses(shared, examples),
};
for (const op of operations) {
applyExternalDocs(op.operation, oai3Operation);
attachExtensions(program, op.operation, oai3Operation);
if (isOperationDeprecated(op)) {
oai3Operation.deprecated = true;
}
}
for (const op of operations) {
const opTags = getAllTags(program, op.operation);
if (opTags) {
const currentTags = oai3Operation.tags;
if (currentTags) {
// combine tags but eliminate duplicates
oai3Operation.tags = [...new Set([...currentTags, ...opTags])];
} else {
oai3Operation.tags = opTags;
}
for (const tag of opTags) {
// Add to root tags if not already there
tagsUsedInOperations.add(tag);
}
}
}
// Error out if shared routes do not have consistent `@parameterVisibility`. We can
// lift this restriction in the future if a use case develops.
const visibilities = operations.map((op) =>
resolveRequestVisibility(program, op.operation, verb),
);
if (visibilities.some((v) => v !== visibilities[0])) {
diagnostics.add(
createDiagnostic({
code: "inconsistent-shared-route-request-visibility",
target: operations[0].operation,
}),
);
}
const visibility = visibilities[0];
oai3Operation.parameters = getEndpointParameters(
resolveSharedRouteParameters(operations),
visibility,
examples,
);
const bodies = [
...new Set(operations.map((op) => op.parameters.body).filter((x) => x !== undefined)),
];
if (bodies) {
oai3Operation.requestBody = getRequestBody(bodies, visibility, examples);
}
const authReference = serviceAuth.operationsAuth.get(shared.operations[0].operation);
if (authReference) {
oai3Operation.security = getEndpointSecurity(authReference);
}
return { operation: oai3Operation, verb, path };
}
function getOperation(
operation: HttpOperation,
): { operation: OpenAPI3Operation; path: string; verb: string } | undefined {
const { path: fullPath, operation: op, verb, parameters } = operation;
// If path contains a query string, issue msg and don't emit this endpoint
if (fullPath.indexOf("?") > 0) {
diagnostics.add(createDiagnostic({ code: "path-query", target: op }));
return undefined;
}
const visibility = resolveRequestVisibility(program, operation.operation, verb);
const examples = resolveOperationExamples(program, operation, {
parameterExamplesStrategy: options.parameterExamplesStrategy,
});
const oai3Operation: OpenAPI3Operation = {
operationId: operationIdResolver.resolve(operation.operation),
summary: getSummary(program, operation.operation),
description: getDoc(program, operation.operation),
parameters: getEndpointParameters(parameters.properties, visibility, examples),
responses: getResponses(operation, operation.responses, examples),
};
const currentTags = getAllTags(program, op);
if (currentTags) {
oai3Operation.tags = currentTags;
for (const tag of currentTags) {
// Add to root tags if not already there
tagsUsedInOperations.add(tag);
}
}
applyExternalDocs(op, oai3Operation);
// Set up basic endpoint fields
if (parameters.body) {
oai3Operation.requestBody = getRequestBody(
parameters.body && [parameters.body],
visibility,
examples,
);
}
const authReference = serviceAuth.operationsAuth.get(operation.operation);
if (authReference) {
oai3Operation.security = getEndpointSecurity(authReference);
}
if (isOperationDeprecated(operation)) {
oai3Operation.deprecated = true;
}
attachExtensions(program, op, oai3Operation);
return { operation: oai3Operation, path: fullPath, verb };
}
function getSharedResponses(
operation: SharedHttpOperation,
examples: OperationExamples,
): Record<string, Refable<OpenAPI3Response>> {
const responseMap = new Map<string, HttpOperationResponse[]>();
for (const op of operation.operations) {
for (const response of op.responses) {
const statusCodes = diagnostics.pipe(
getOpenAPI3StatusCodes(program, response.statusCodes, op.operation),
);
for (const statusCode of statusCodes) {
if (responseMap.has(statusCode)) {
responseMap.get(statusCode)!.push(response);
} else {
responseMap.set(statusCode, [response]);
}
}
}
}
const result: Record<string, Refable<OpenAPI3Response>> = {};
for (const [statusCode, statusCodeResponses] of responseMap) {
const dedupeResponses = deduplicateCommonResponses(statusCodeResponses);
result[statusCode] = getResponseForStatusCode(
operation,
statusCode,
dedupeResponses,
examples,
);
}
return result;
}
function getResponses(
operation: HttpOperation,
responses: HttpOperationResponse[],
examples: OperationExamples,
): Record<string, Refable<OpenAPI3Response>> {
const responseMap = new Map<string, HttpOperationResponse[]>();
// Group responses by status code first. When named unions are expanded into individual
// response variants, multiple variants may map to the same status code. We need to collect
// all variants for each status code before processing to properly merge content types and
// select the appropriate description.
for (const response of responses) {
for (const statusCode of diagnostics.pipe(
getOpenAPI3StatusCodes(program, response.statusCodes, response.type),