-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathgo.ts
More file actions
4141 lines (3698 loc) · 171 KB
/
go.ts
File metadata and controls
4141 lines (3698 loc) · 171 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
/**
* Go code generator for session-events and RPC types.
*/
import { execFile } from "child_process";
import fs from "fs/promises";
import type { JSONSchema7 } from "json-schema";
import path from "path";
import { fileURLToPath } from "url";
import { promisify } from "util";
import wordwrap from "wordwrap";
import {
cloneSchemaForCodegen,
collectExternalSchemaRefNames,
collectDefinitionCollections,
collectExperimentalOnlyRpcReferencedDefinitionNames,
collectReachableDefinitionNames,
collectRpcMethodReferencedDefinitionNames,
filterNodeByVisibility,
fixNullableRequiredRefsInApiSchema,
findSharedSchemaDefinitions,
getApiSchemaPath,
getNullableInner,
getEnumValueDescriptions,
getRpcSchemaTypeName,
getSessionEventsSchemaPath,
getSessionEventVariantSchemas,
getSharedSessionEventEnvelopeProperties,
hasSchemaPayload,
isIntegerSchemaBoundedToInt32,
isNodeFullyDeprecated,
isNodeFullyExperimental,
isOpaqueJson,
isRpcMethod,
isSchemaDeprecated,
isSchemaExperimental,
isSchemaInternal,
isVoidSchema,
parseExternalSchemaRef,
postProcessSchema,
propagateInternalVisibility,
refTypeName,
resolveObjectSchema,
resolveRef,
resolveSchema,
rewriteSharedDefinitionReferences,
writeGeneratedFile,
type ApiSchema,
type DefinitionCollections,
type EnumValueDescriptions,
type RpcMethod,
type SessionEventEnvelopeProperty,
} from "./utils.js";
const execFileAsync = promisify(execFile);
interface GoExternalSchemaImport {
path: string;
qualifier: string;
packageName: string;
}
const EXTERNAL_SCHEMA_GO_IMPORT: Record<string, GoExternalSchemaImport> = {
"api.schema.json": { path: "github.com/github/copilot-sdk/go/rpc", qualifier: "rpc", packageName: "rpc" },
"session-events.schema.json": { path: "github.com/github/copilot-sdk/go/rpc", qualifier: "rpc", packageName: "rpc" },
};
// ── Utilities ───────────────────────────────────────────────────────────────
// Go initialisms that should be all-caps
const goInitialisms = new Set(["id", "ui", "uri", "url", "api", "http", "https", "json", "xml", "html", "css", "sql", "ssh", "tcp", "udp", "ip", "rpc", "mime"]);
const goCommentTextWrapLength = 90;
const wrapGoCommentText = wordwrap(goCommentTextWrapLength);
function toPascalCase(s: string): string {
return s
.split(/[^A-Za-z0-9]+/)
.filter((word) => word.length > 0)
.map((w) => goInitialisms.has(w.toLowerCase()) ? w.toUpperCase() : w.charAt(0).toUpperCase() + w.slice(1))
.join("");
}
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function toGoSchemaTypeName(s: string): string {
return toPascalCase(splitGoIdentifierWords(s).join("_"));
}
function toGoFieldName(jsonName: string): string {
// Handle camelCase field names like "modelId" -> "ModelID"
return splitGoIdentifierWords(jsonName)
.map((w) => goInitialisms.has(w.toLowerCase()) ? w.toUpperCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
.join("");
}
function goRefTypeName(ref: string, definitions?: DefinitionCollections, currentPackage?: string): string {
const externalRef = parseExternalSchemaRef(ref);
if (externalRef) {
const externalImport = EXTERNAL_SCHEMA_GO_IMPORT[externalRef.schemaFile];
const typeName = toGoFieldName(externalRef.definitionName);
if (externalImport && externalImport.packageName !== currentPackage) {
return `${externalImport.qualifier}.${typeName}`;
}
return typeName;
}
return toGoFieldName(refTypeName(ref, definitions));
}
function compareGoFieldNames(left: string, right: string): number {
return left.localeCompare(right);
}
function sortByGoFieldName<T>(entries: [string, T][]): [string, T][] {
return entries.sort(([left], [right]) => compareGoFieldNames(toGoFieldName(left), toGoFieldName(right)));
}
function sortByPascalName<T>(entries: [string, T][]): [string, T][] {
return entries.sort(([left], [right]) => toPascalCase(left).localeCompare(toPascalCase(right)));
}
function compareGoTypeNames(left: string, right: string): number {
return left.localeCompare(right);
}
function compareRpcMethodsByGoName(left: RpcMethod, right: RpcMethod): number {
return clientHandlerMethodName(left.rpcMethod).localeCompare(clientHandlerMethodName(right.rpcMethod));
}
function splitGoIdentifierWords(name: string): string[] {
return name
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
.split(/[^A-Za-z0-9]+/)
.filter((word) => word.length > 0);
}
function isStringEnumDefinition(definition: JSONSchema7): definition is JSONSchema7 & { enum: string[] } {
return Array.isArray(definition.enum) && definition.enum.every((value) => typeof value === "string");
}
function pushGoComment(lines: string[], text: string, indent = "", wrap = true): void {
lines.push(...goCommentLines(text, indent, wrap));
}
function pushGoCommentForContext(lines: string[], text: string, ctx: GoCodegenCtx, indent = ""): void {
pushGoComment(lines, text, indent, ctx.wrapComments !== false);
}
function goExperimentalTypeComment(typeName: string): string {
return `Experimental: ${typeName} is part of an experimental API and may change or be removed.`;
}
function pushGoExperimentalTypeComment(lines: string[], typeName: string, ctx: GoCodegenCtx): void {
pushGoCommentForContext(lines, goExperimentalTypeComment(typeName), ctx);
}
function hasGoCommentLinesInLeadingDocBlock(source: string, typeDeclOffset: number, commentLines: string[]): boolean {
const precedingLines = source.slice(0, typeDeclOffset).split(/\r?\n/);
if (precedingLines[precedingLines.length - 1] === "") {
precedingLines.pop();
}
const docBlockLines: string[] = [];
for (let i = precedingLines.length - 1; i >= 0; i--) {
const line = precedingLines[i];
if (line.trim() === "") {
break;
}
if (!line.startsWith("//")) {
break;
}
docBlockLines.unshift(line);
}
for (let i = 0; i <= docBlockLines.length - commentLines.length; i++) {
if (commentLines.every((commentLine, offset) => docBlockLines[i + offset] === commentLine)) {
return true;
}
}
return false;
}
function pushGoExperimentalEventComment(lines: string[], constName: string, indent = ""): void {
pushGoComment(lines, `Experimental: ${constName} identifies an experimental event that may change or be removed.`, indent);
}
function pushGoExperimentalApiComment(lines: string[], name: string, indent = ""): void {
pushGoComment(lines, `Experimental: ${name} contains experimental APIs that may change or be removed.`, indent);
}
function pushGoExperimentalSubApiComment(lines: string[], name: string, indent = ""): void {
pushGoComment(lines, `Experimental: ${name} returns experimental APIs that may change or be removed.`, indent);
}
function pushGoExperimentalMethodComment(lines: string[], methodName: string, indent = ""): void {
pushGoComment(lines, `Experimental: ${methodName} is an experimental API and may change or be removed in future versions.`, indent);
}
function pushGoInternalPropertyComment(lines: string[], goName: string, ctx: GoCodegenCtx, indent = "\t"): void {
pushGoCommentForContext(lines, `Internal: ${goName} is part of the SDK's internal API surface and is not intended for external use.`, ctx, indent);
}
function pushGoExperimentalPropertyComment(lines: string[], goName: string, ctx: GoCodegenCtx, indent = "\t"): void {
pushGoCommentForContext(lines, `Experimental: ${goName} is part of an experimental API and may change or be removed.`, ctx, indent);
}
/**
* Emit `Deprecated:` / `Experimental:` / `Internal:` doc comments above a Go
* struct field. Centralises the per-field marker logic shared between the
* regular struct emitter and the discriminated-union variant emitters.
*/
function pushGoFieldMarkers(lines: string[], prop: JSONSchema7, goName: string, ctx: GoCodegenCtx, indent = "\t"): void {
if (isSchemaDeprecated(prop)) {
pushGoCommentForContext(lines, `Deprecated: ${goName} is deprecated.`, ctx, indent);
}
if (isSchemaExperimental(prop)) {
pushGoExperimentalPropertyComment(lines, goName, ctx, indent);
}
if (isSchemaInternal(prop)) {
pushGoInternalPropertyComment(lines, goName, ctx, indent);
}
}
function lowerFirst(value: string): string {
if (value.length === 0) return value;
return value.charAt(0).toLowerCase() + value.slice(1);
}
function goMethodDocSummary(methodName: string, method: RpcMethod, fallbackVerb = "calls"): string {
const description = method.description?.trim();
if (!description) return `${methodName} ${fallbackVerb} ${method.rpcMethod}.`;
if (description.startsWith(methodName)) return description;
return `${methodName} ${lowerFirst(description)}`;
}
function goRpcResultDescription(method: RpcMethod, resultSchema: JSONSchema7 | undefined): string | undefined {
if (isVoidSchema(resultSchema)) return undefined;
return method.result?.description ?? resultSchema?.description;
}
function goRpcParamsDescription(method: RpcMethod, effectiveParams: JSONSchema7 | undefined): string | undefined {
return method.params?.description ?? effectiveParams?.description;
}
function pushGoRpcMethodComment(
lines: string[],
methodName: string,
method: RpcMethod,
resultSchema: JSONSchema7 | undefined,
paramsDescription?: string,
indent = "",
fallbackVerb = "calls"
): void {
const paragraphs = [goMethodDocSummary(methodName, method, fallbackVerb), `RPC method: ${method.rpcMethod}.`];
if (paramsDescription) {
paragraphs.push(`Parameters: ${paramsDescription}`);
}
const resultDescription = goRpcResultDescription(method, resultSchema);
if (resultDescription) {
paragraphs.push(`Returns: ${resultDescription}`);
}
pushGoComment(lines, paragraphs.join("\n\n"), indent);
}
function goCommentLines(text: string, indent = "", wrap = true): string[] {
const prefix = `${indent}//`;
const lines: string[] = [];
for (const paragraph of text.split(/\r?\n/)) {
const trimmed = paragraph.trim();
if (trimmed.length === 0) {
lines.push(prefix);
continue;
}
const commentLines = wrap
? wrapGoCommentText(trimmed).split("\n").map((wrappedLine: string) => wrappedLine.trim())
: [trimmed];
for (const line of commentLines) {
lines.push(`${prefix} ${line}`);
}
}
return lines;
}
function wrapGeneratedGoComments(code: string): string {
return code
.split(/\r?\n/)
.flatMap((line) => {
const match = /^(\s*)\/\/\s?(.*)$/.exec(line);
if (!match) return [line];
const [, indent, text] = match;
if (text.length <= goCommentTextWrapLength) return [line];
return goCommentLines(text, indent);
})
.join("\n");
}
interface GoExtractedField {
name: string;
type: string;
}
/**
* Extract a mapping from (structName, jsonFieldName) to generated Go field
* metadata so wrapper code can reference emitted field names and nil behavior.
*/
function extractFields(generatedTypeCode: string): Map<string, Map<string, GoExtractedField>> {
const result = new Map<string, Map<string, GoExtractedField>>();
const structRe = /^type\s+(\w+)\s+struct\s*\{([^}]*)\}/gm;
let sm;
while ((sm = structRe.exec(generatedTypeCode)) !== null) {
const [, structName, body] = sm;
const fields = new Map<string, GoExtractedField>();
const fieldRe = /^\s+(\w+)\s+([^\s`]+)\s+`json:"([^",]+)/gm;
let fm;
while ((fm = fieldRe.exec(body)) !== null) {
fields.set(fm[3], { name: fm[1], type: fm[2] });
}
result.set(structName, fields);
}
return result;
}
function goTypeIsPointer(goType: string | undefined): boolean {
return goType?.startsWith("*") ?? false;
}
function goTypeIsSlice(goType: string | undefined): boolean {
return goType?.startsWith("[]") ?? false;
}
function goTypeIsMap(goType: string | undefined): boolean {
return goType?.startsWith("map[") ?? false;
}
function goTypeIsNilable(goType: string | undefined, ctx?: GoCodegenCtx): boolean {
if (!goType) return false;
if (goTypeIsPointer(goType) || goTypeIsSlice(goType) || goTypeIsMap(goType)) return true;
return ctx ? goDiscriminatedUnionInfoForType(goType, ctx) !== undefined : false;
}
function goOptionalFieldNeedsDereference(goType: string | undefined): boolean {
return goType === undefined || goTypeIsPointer(goType);
}
function goTypeWithOptionalPointer(goType: string, ctx?: GoCodegenCtx): string {
return goTypeIsNilable(goType, ctx) ? goType : `*${goType}`;
}
async function formatGoFile(filePath: string): Promise<void> {
try {
await execFileAsync("go", ["fmt", filePath]);
console.log(` ✓ Formatted with go fmt`);
} catch {
// go fmt not available, skip
}
}
function collectRpcMethods(node: Record<string, unknown>): RpcMethod[] {
const results: RpcMethod[] = [];
for (const [, value] of sortByPascalName(Object.entries(node))) {
if (isRpcMethod(value)) {
results.push(value);
} else if (typeof value === "object" && value !== null) {
results.push(...collectRpcMethods(value as Record<string, unknown>));
}
}
return results;
}
let rpcDefinitions: DefinitionCollections = { definitions: {}, $defs: {} };
let rpcSessionEventTopLevelNames: { types: Set<string>; consts: Set<string> } = {
types: new Set(),
consts: new Set(),
};
function withRootTitle(schema: JSONSchema7, title: string): JSONSchema7 {
return { ...schema, title };
}
function goRequestFallbackName(method: RpcMethod): string {
return toPascalCase(method.rpcMethod) + "Request";
}
function schemaSourceForNamedDefinition(
schema: JSONSchema7 | null | undefined,
resolvedSchema: JSONSchema7 | undefined
): JSONSchema7 {
if (schema?.$ref && resolvedSchema) {
return resolvedSchema;
}
// When a method wrapper is named the same as the referenced schema inside an
// anyOf/oneOf, store the resolved object shape so the definition map does not
// create a self-referential alias.
if ((schema?.anyOf || schema?.oneOf) && resolvedSchema?.properties) {
return resolvedSchema;
}
return schema ?? resolvedSchema ?? { type: "object" };
}
function isNamedGoObjectSchema(schema: JSONSchema7 | undefined): schema is JSONSchema7 {
return !!schema && schema.type === "object" && (schema.properties !== undefined || schema.additionalProperties === false);
}
function getMethodResultSchema(method: RpcMethod): JSONSchema7 | undefined {
return resolveSchema(method.result, rpcDefinitions) ?? method.result ?? undefined;
}
function getMethodParamsSchema(method: RpcMethod): JSONSchema7 | undefined {
return (
resolveObjectSchema(method.params, rpcDefinitions) ??
resolveSchema(method.params, rpcDefinitions) ??
method.params ??
undefined
);
}
function goResultTypeName(method: RpcMethod): string {
return getRpcSchemaTypeName(getMethodResultSchema(method), toPascalCase(method.rpcMethod) + "Result");
}
function goNullableResultTypeName(method: RpcMethod, innerSchema: JSONSchema7): string {
if (innerSchema.$ref) {
const refName = innerSchema.$ref.split("/").pop();
if (refName) return toPascalCase(refName);
}
return getRpcSchemaTypeName(innerSchema, toPascalCase(method.rpcMethod) + "Result");
}
function goParamsTypeName(method: RpcMethod): string {
const fallback = goRequestFallbackName(method);
if (method.rpcMethod.startsWith("session.") && method.params?.$ref) {
return fallback;
}
return getRpcSchemaTypeName(getMethodParamsSchema(method), fallback);
}
// ── Session Events (custom codegen — per-event-type data structs) ───────────
interface GoEventVariant {
typeName: string;
dataClassName: string;
dataSchema: JSONSchema7;
dataDescription?: string;
eventExperimental: boolean;
dataExperimental: boolean;
}
interface GoEventEnvelopeProperty extends SessionEventEnvelopeProperty {
fieldName: string;
typeName: string;
jsonTag: string;
description?: string;
}
interface GoDiscriminatedUnionInfo {
typeName: string;
unmarshalFuncName: string;
}
type GoDiscriminatorValue = string | boolean;
type GoDiscriminatorValueKind = "string" | "boolean";
interface GoDiscriminatedUnionVariant {
schema: JSONSchema7;
typeName: string;
discriminatorValues: GoDiscriminatorValue[];
}
interface GoDiscriminatorInfo {
property: string;
valueKind: GoDiscriminatorValueKind;
mapping: Map<GoDiscriminatorValue, GoDiscriminatedUnionVariant[]>;
variants: GoDiscriminatedUnionVariant[];
}
interface GoRequiredFieldDiscriminatorInfo {
variants: GoDiscriminatedUnionVariant[];
}
interface GoPrimitiveUnionVariant {
typeName: string;
goType: string;
}
interface GoUntaggedUnionVariant {
typeName: string;
goType: string;
jsonKind: string;
typeDefinition?: string;
returnExpr: string;
}
type GoUnionPlan =
| { kind: "discriminated"; typeName: string; schema: JSONSchema7; description?: string; discriminator: GoDiscriminatorInfo }
| { kind: "requiredFieldDiscriminated"; typeName: string; schema: JSONSchema7; description?: string; discriminator: GoRequiredFieldDiscriminatorInfo }
| { kind: "primitive"; typeName: string; schema: JSONSchema7; description?: string; variants: GoPrimitiveUnionVariant[] }
| { kind: "flattenedObject"; typeName: string; schema: JSONSchema7; description?: string; variants: JSONSchema7[] }
| { kind: "untagged"; typeName: string; schema: JSONSchema7; description?: string; variants: GoUntaggedUnionVariant[] }
| { kind: "wrapper"; typeName: string; schema: JSONSchema7; description?: string };
interface GoCodegenCtx {
structs: string[];
encoding: string[];
enums: string[];
enumsByName: Map<string, string>; // enumName → enumName (dedup by type name, not values)
discriminatedUnions: Map<string, GoDiscriminatedUnionInfo>;
generatedNames: Set<string>;
definitions?: DefinitionCollections;
wrapComments?: boolean;
discriminatedUnionRawVariantSuffix?: string;
skipDefinitionTypeNames?: Set<string>;
encodingBlocks?: Set<string>;
packageName?: string;
}
function extractGoEventVariants(schema: JSONSchema7): GoEventVariant[] {
const definitionCollections = collectDefinitionCollections(schema as Record<string, unknown>);
return getSessionEventVariantSchemas(schema, definitionCollections)
.map((variant) => {
const typeSchema = variant.properties!.type as JSONSchema7;
const typeName = typeSchema?.const as string;
if (!typeName) throw new Error("Variant must have type.const");
const dataSchema =
resolveObjectSchema(variant.properties!.data as JSONSchema7, definitionCollections) ??
resolveSchema(variant.properties!.data as JSONSchema7, definitionCollections) ??
((variant.properties!.data as JSONSchema7) || {});
return {
typeName,
dataClassName: `${toPascalCase(typeName)}Data`,
dataSchema,
dataDescription: dataSchema.description,
eventExperimental: isSchemaExperimental(variant),
dataExperimental: isSchemaExperimental(dataSchema),
};
});
}
function getGoSharedEventEnvelopeProperties(schema: JSONSchema7, ctx: GoCodegenCtx): GoEventEnvelopeProperty[] {
return getSharedSessionEventEnvelopeProperties(schema, ctx.definitions)
.map((property) => {
const { name, schema, required } = property;
const typeName = resolveGoPropertyType(schema, "SessionEvent", name, required && !getNullableInner(schema), ctx);
const omit = required ? "" : ",omitempty";
return {
name,
schema,
required,
fieldName: toGoFieldName(name),
typeName,
jsonTag: `json:"${name}${omit}"`,
description: schema.description,
};
});
}
function emitGoEnvelopeStructField(property: GoEventEnvelopeProperty, includeComment: boolean, wrapComments = true): string[] {
const lines: string[] = [];
if (includeComment && property.description) {
pushGoComment(lines, property.description, "\t", wrapComments);
}
lines.push(`\t${property.fieldName} ${property.typeName} \`${property.jsonTag}\``);
return lines;
}
function sortedGoEventEnvelopeProperties(properties: GoEventEnvelopeProperty[]): GoEventEnvelopeProperty[] {
return [...properties].sort((left, right) => compareGoFieldNames(left.fieldName, right.fieldName));
}
interface GoDiscriminatorValues {
kind: GoDiscriminatorValueKind;
values: GoDiscriminatorValue[];
}
function goDiscriminatorValues(schema: JSONSchema7, ctx: GoCodegenCtx): GoDiscriminatorValues | undefined {
const stringValues = goStringEnumValues(schema, ctx);
if (stringValues) return { kind: "string", values: stringValues };
const booleanValues = goBooleanDiscriminatorValues(schema, ctx);
if (booleanValues) return { kind: "boolean", values: booleanValues };
return undefined;
}
/**
* Find a literal-valued discriminator property shared by all anyOf variants.
*/
function findGoDiscriminator(
variants: JSONSchema7[],
ctx: GoCodegenCtx,
unionTypeName: string
): GoDiscriminatorInfo | null {
if (variants.length === 0) return null;
const firstVariant = resolveGoUnionMember(variants[0], ctx.definitions);
if (!firstVariant.properties) return null;
for (const [propName, propSchema] of Object.entries(firstVariant.properties)) {
if (typeof propSchema !== "object") continue;
const firstDiscriminatorValues = goDiscriminatorValues(propSchema as JSONSchema7, ctx);
if (!firstDiscriminatorValues || firstDiscriminatorValues.values.length === 0) continue;
const mapping = new Map<GoDiscriminatorValue, GoDiscriminatedUnionVariant[]>();
const unionVariants: GoDiscriminatedUnionVariant[] = [];
let valid = true;
for (const variantSource of variants) {
const variant = resolveGoUnionMember(variantSource, ctx.definitions);
if (!variant.properties) { valid = false; break; }
if (!(variant.required || []).includes(propName)) { valid = false; break; }
const vp = variant.properties[propName];
if (typeof vp !== "object") { valid = false; break; }
const discriminatorValues = goDiscriminatorValues(vp as JSONSchema7, ctx);
if (!discriminatorValues || discriminatorValues.values.length === 0 || discriminatorValues.kind !== firstDiscriminatorValues.kind) { valid = false; break; }
const dedupedValues = [...new Set(discriminatorValues.values)];
if (discriminatorValues.kind === "boolean" && dedupedValues.length > 1) { valid = false; break; }
const unionVariant = {
schema: variant,
typeName: goDiscriminatedUnionVariantTypeName(unionTypeName, dedupedValues[0], variantSource, variant, ctx),
discriminatorValues: dedupedValues,
};
unionVariants.push(unionVariant);
for (const discriminatorValue of dedupedValues) {
const existing = mapping.get(discriminatorValue) ?? [];
existing.push(unionVariant);
mapping.set(discriminatorValue, existing);
}
}
if (valid && mapping.size > 0 && unionVariants.length === variants.length) {
return { property: propName, valueKind: firstDiscriminatorValues.kind, mapping, variants: unionVariants };
}
}
return null;
}
function findGoRequiredFieldDiscriminator(
variants: JSONSchema7[],
ctx: GoCodegenCtx,
unionTypeName: string
): GoRequiredFieldDiscriminatorInfo | null {
if (variants.length === 0) return null;
const objectVariants = variants.map((variantSource) => ({
source: variantSource,
schema: goObjectUnionMemberSchema(variantSource, ctx),
}));
if (objectVariants.some((variant) => variant.schema === undefined)) return null;
const requiredSets = objectVariants.map((variant) => new Set(variant.schema!.required || []));
const propertySets = objectVariants.map((variant) => new Set(Object.keys(variant.schema!.properties || {})));
const unionVariants: GoDiscriminatedUnionVariant[] = [];
const seenTypeNames = new Set<string>();
for (const [index, variant] of objectVariants.entries()) {
const required = requiredSets[index];
if (required.size === 0) return null;
const uniqueRequired = [...required]
.filter((propName) => !propertySets.some((peerProperties, peerIndex) => peerIndex !== index && peerProperties.has(propName)))
.sort(compareGoFieldNames);
if (uniqueRequired.length === 0) return null;
const typeName = goDiscriminatedUnionVariantTypeName(unionTypeName, uniqueRequired[0], variant.source, variant.schema!, ctx);
if (seenTypeNames.has(typeName)) return null;
seenTypeNames.add(typeName);
unionVariants.push({
schema: variant.schema!,
typeName,
discriminatorValues: uniqueRequired,
});
}
return { variants: unionVariants };
}
/**
* Get or create a Go enum type, deduplicating by type name (not by value set).
* Two enums with the same values but different names are distinct types.
*/
function getOrCreateGoEnum(
enumName: string,
values: string[],
ctx: GoCodegenCtx,
description?: string,
enumValueDescriptions?: EnumValueDescriptions,
deprecated?: boolean,
experimental?: boolean
): string {
const existing = ctx.enumsByName.get(enumName);
if (existing) return existing;
const lines: string[] = [];
if (description) {
pushGoCommentForContext(lines, description, ctx);
}
if (experimental) {
pushGoExperimentalTypeComment(lines, enumName, ctx);
}
if (deprecated) {
pushGoCommentForContext(lines, `Deprecated: ${enumName} is deprecated and will be removed in a future version.`, ctx);
}
lines.push(`type ${enumName} string`);
lines.push(``);
lines.push(`const (`);
const consts = values
.map((value) => ({ value, constSuffix: goEnumConstSuffix(value) }))
.sort((left, right) => `${enumName}${left.constSuffix}`.localeCompare(`${enumName}${right.constSuffix}`));
const usedConstNames = new Map<string, string>();
for (const { value, constSuffix } of consts) {
const constName = `${enumName}${constSuffix}`;
const existingValue = usedConstNames.get(constName);
if (existingValue !== undefined) {
throw new Error(
`Generated Go enum const identifier "${constName}" is not unique for values "${existingValue}" and "${value}". Add an explicit naming rule instead of stabilizing an arbitrary public const name.`
);
}
usedConstNames.set(constName, value);
const valueDescription = enumValueDescriptions?.[value];
if (valueDescription) {
pushGoCommentForContext(lines, valueDescription, ctx, "\t");
}
lines.push(`\t${constName} ${enumName} = "${value}"`);
}
lines.push(`)`);
ctx.enumsByName.set(enumName, enumName);
ctx.enums.push(lines.join("\n"));
return enumName;
}
function goEnumConstSuffix(value: string): string {
const suffix = splitGoIdentifierWords(value)
.map((word) =>
goInitialisms.has(word.toLowerCase())
? word.toUpperCase()
: word.charAt(0).toUpperCase() + word.slice(1)
)
.join("");
return suffix || "Value";
}
function goDiscriminatedUnionVariantTypeName(
unionTypeName: string,
discriminatorValue: GoDiscriminatorValue,
variantSource: JSONSchema7,
variant: JSONSchema7,
ctx: GoCodegenCtx
): string {
if (variantSource.$ref && typeof variantSource.$ref === "string") {
return goDefinitionName(refTypeName(variantSource.$ref, ctx.definitions));
}
const definitionRef = goDefinitionRefForEquivalentSchema(variant, ctx);
if (definitionRef) {
return goDefinitionName(refTypeName(definitionRef, ctx.definitions));
}
return `${unionTypeName}${goDiscriminatorConstSuffix(discriminatorValue)}`;
}
function goDiscriminatorConstSuffix(value: GoDiscriminatorValue): string {
return typeof value === "boolean" ? (value ? "True" : "False") : goEnumConstSuffix(value);
}
function compareGoDiscriminatorValues(left: GoDiscriminatorValue, right: GoDiscriminatorValue): number {
if (typeof left === "boolean" && typeof right === "boolean") {
return Number(left) - Number(right);
}
return String(left).localeCompare(String(right));
}
function goDiscriminatorValueExpr(value: GoDiscriminatorValue, enumName: string | undefined): string {
if (typeof value === "boolean") return value ? "true" : "false";
if (!enumName) throw new Error(`Missing enum name for string discriminator value ${value}`);
return `${enumName}${goEnumConstSuffix(value)}`;
}
function schemaForConstValue(value: unknown): JSONSchema7 {
if (value === null) return { type: "null" };
if (Array.isArray(value)) return { type: "array", items: {} };
switch (typeof value) {
case "boolean":
return { type: "boolean" };
case "number":
return { type: Number.isInteger(value) ? "integer" : "number" };
case "string":
return { type: "string" };
case "object":
return { type: "object", additionalProperties: true };
default:
return {};
}
}
/**
* Resolve a JSON Schema property to a Go type string.
* Emits nested struct/enum definitions into ctx as a side effect.
*/
function resolveGoPropertyType(
propSchema: JSONSchema7,
parentTypeName: string,
jsonPropName: string,
isRequired: boolean,
ctx: GoCodegenCtx
): string {
const nestedName = parentTypeName + toGoFieldName(jsonPropName);
// Handle $ref — resolve the reference and generate the referenced type
if (propSchema.$ref && typeof propSchema.$ref === "string") {
const typeName = goRefTypeName(propSchema.$ref, ctx.definitions, ctx.packageName);
const resolved = resolveRef(propSchema.$ref, ctx.definitions);
if (resolved) {
if (resolved.enum) {
if ((resolved.enum as unknown[]).every((value) => typeof value === "string")) {
const enumType = getOrCreateGoEnum(typeName, resolved.enum as string[], ctx, resolved.description, getEnumValueDescriptions(resolved), isSchemaDeprecated(resolved), isSchemaExperimental(resolved));
return isRequired ? enumType : `*${enumType}`;
}
if (resolved.enum.length === 1) {
return resolveGoPropertyType(schemaForConstValue(resolved.enum[0]), parentTypeName, jsonPropName, isRequired, ctx);
}
return "any";
}
if (isNamedGoObjectSchema(resolved)) {
emitGoStruct(typeName, resolved, ctx);
return isRequired ? typeName : `*${typeName}`;
}
const resolvedUnion = resolved as JSONSchema7;
if (resolvedUnion.anyOf || resolvedUnion.oneOf) {
emitGoRpcDefinition(refTypeName(propSchema.$ref, ctx.definitions), resolved, ctx);
if (goDiscriminatedUnionInfoForType(typeName, ctx)) {
return typeName;
}
return isRequired ? typeName : `*${typeName}`;
}
return resolveGoPropertyType(resolved, parentTypeName, jsonPropName, isRequired, ctx);
}
// Fallback: use the type name directly
return isRequired ? typeName : `*${typeName}`;
}
// Handle anyOf
if (propSchema.anyOf) {
const nullableInnerSchema = getNullableInner(propSchema);
if (nullableInnerSchema) {
// anyOf [T, null/{not:{}}] → nullable T
const innerType = resolveGoPropertyType(nullableInnerSchema, parentTypeName, jsonPropName, true, ctx);
// Pointer-wrap if not already a pointer, slice, or map
return goTypeWithOptionalPointer(innerType, ctx);
}
const nonNull = (propSchema.anyOf as JSONSchema7[]).filter((s) => s.type !== "null");
const hasNull = (propSchema.anyOf as JSONSchema7[]).some((s) => s.type === "null");
if (nonNull.length === 1) {
// anyOf [T, null] → nullable T
const innerType = resolveGoPropertyType(nonNull[0], parentTypeName, jsonPropName, true, ctx);
if (isRequired && !hasNull) return innerType;
return goTypeWithOptionalPointer(innerType, ctx);
}
if (nonNull.length > 1) {
const unionName = (propSchema.title as string) || nestedName;
const plan = planGoUnion(unionName, propSchema, ctx);
if (plan) {
emitGoUnionPlan(plan, ctx);
return goUnionPlanPropertyType(plan, isRequired, hasNull);
}
// Non-discriminated multi-type union → any
return "any";
}
}
// Handle enum
if (propSchema.enum && Array.isArray(propSchema.enum)) {
if ((propSchema.enum as unknown[]).every((value) => typeof value === "string")) {
const enumType = getOrCreateGoEnum((propSchema.title as string) || nestedName, propSchema.enum as string[], ctx, propSchema.description, getEnumValueDescriptions(propSchema), isSchemaDeprecated(propSchema), isSchemaExperimental(propSchema));
return isRequired ? enumType : `*${enumType}`;
}
if (propSchema.enum.length === 1) {
return resolveGoPropertyType(schemaForConstValue(propSchema.enum[0]), parentTypeName, jsonPropName, isRequired, ctx);
}
return "any";
}
// Handle const values. String consts stay enum-like to preserve generated names for
// discriminators; other const values use their underlying JSON type.
if (propSchema.const !== undefined) {
if (typeof propSchema.const !== "string") {
return resolveGoPropertyType(schemaForConstValue(propSchema.const), parentTypeName, jsonPropName, isRequired, ctx);
}
const enumType = getOrCreateGoEnum((propSchema.title as string) || nestedName, [propSchema.const], ctx, propSchema.description, getEnumValueDescriptions(propSchema), isSchemaDeprecated(propSchema), isSchemaExperimental(propSchema));
return isRequired ? enumType : `*${enumType}`;
}
const type = propSchema.type;
const format = propSchema.format;
// Handle type arrays like ["string", "null"]
if (Array.isArray(type)) {
const nonNullTypes = (type as string[]).filter((t) => t !== "null");
if (nonNullTypes.length === 1) {
const inner = resolveGoPropertyType(
{ ...propSchema, type: nonNullTypes[0] as JSONSchema7["type"] },
parentTypeName,
jsonPropName,
true,
ctx
);
return goTypeWithOptionalPointer(inner, ctx);
}
}
// Simple types
if (type === "string") {
if (format === "date-time") {
return isRequired ? "time.Time" : "*time.Time";
}
return isRequired ? "string" : "*string";
}
if (type === "number") return isRequired ? "float64" : "*float64";
if (type === "integer") {
const integerType = isIntegerSchemaBoundedToInt32(propSchema) ? "int32" : "int64";
return isRequired ? integerType : `*${integerType}`;
}
if (type === "boolean") return isRequired ? "bool" : "*bool";
// Array type
if (type === "array") {
const items = propSchema.items as JSONSchema7 | undefined;
if (items) {
if (items.anyOf) {
const itemTypeName = (items.title as string) || (nestedName + "Item");
const plan = planGoUnion(itemTypeName, items, ctx);
if (plan) {
emitGoUnionPlan(plan, ctx);
return `[]${goUnionPlanPropertyType(plan, true, false)}`;
}
}
const itemType = resolveGoPropertyType(items, parentTypeName, jsonPropName + "Item", true, ctx);
return `[]${itemType}`;
}
return "[]any";
}
// Object type
if (type === "object" || (propSchema.properties && !type)) {
if (propSchema.properties && Object.keys(propSchema.properties).length > 0) {
const structName = (propSchema.title as string) || nestedName;
emitGoStruct(structName, propSchema, ctx);
return isRequired ? structName : `*${structName}`;
}
if (propSchema.additionalProperties) {
if (
typeof propSchema.additionalProperties === "object" &&
Object.keys(propSchema.additionalProperties as Record<string, unknown>).length > 0
) {
const ap = propSchema.additionalProperties as JSONSchema7;
if (ap.type === "object" && ap.properties) {
const valueName = (ap.title as string) || `${nestedName}Value`;
emitGoStruct(valueName, ap, ctx);
return `map[string]${valueName}`;
}
let valueType = resolveGoPropertyType(ap, parentTypeName, jsonPropName + "Value", true, ctx);
const resolvedValueType = ap.$ref ? resolveRef(ap.$ref, ctx.definitions) : undefined;
if (resolvedValueType?.anyOf || resolvedValueType?.oneOf) {
const unionMembers = goNonNullUnionMembers(resolvedValueType)
.map((member) => resolveGoUnionMember(member, ctx.definitions));
if (!canFlattenGoObjectUnion(unionMembers, ctx) && !goTypeIsNilable(valueType, ctx)) {
valueType = `*${valueType}`;
}
}
return `map[string]${valueType}`;
}
return "map[string]any";
}
// Empty object or untyped
return "any";
}
return "any";
}
interface GoStructField {
propName: string;
goName: string;
goType: string;
jsonTag: string;
}
interface GoDiscriminatedUnionField {
kind: "single" | "slice" | "map";
unionInfo: GoDiscriminatedUnionInfo;
}
function goUnexportedFunctionName(prefix: string, typeName: string): string {