-
Notifications
You must be signed in to change notification settings - Fork 309
Expand file tree
/
Copy pathWebsocketClientGenerator.ts
More file actions
1089 lines (1011 loc) · 42.9 KB
/
WebsocketClientGenerator.ts
File metadata and controls
1089 lines (1011 loc) · 42.9 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 { CSharpFile } from "@fern-api/csharp-base";
import { ast, is, WithGeneration, Writer } from "@fern-api/csharp-codegen";
import { RelativeFilePath } from "@fern-api/fs-utils";
import { FernIr } from "@fern-fern/ir-sdk";
type Subpackage = FernIr.Subpackage;
type TypeReference = FernIr.TypeReference;
type WebSocketChannel = FernIr.WebSocketChannel;
import { SdkGeneratorContext } from "../SdkGeneratorContext.js";
/**
* Arguments for creating a WebSocket client generator.
*/
export declare namespace WebSocketClientGenerator {
interface Args {
/** The subpackage containing the WebSocket channel */
subpackage: Subpackage;
/** The SDK generator context */
context: SdkGeneratorContext;
/** The WebSocket channel definition */
websocketChannel: WebSocketChannel;
}
}
/**
* Generates C# WebSocket client classes from WebSocket channel definitions.
*
* This class creates a complete WebSocket API client that includes:
* - Connection management with configurable options
* - Event handling for incoming server messages
* - Message sending capabilities for client-to-server communication
* - Automatic JSON serialization/deserialization
* - Query parameter support for connection URLs
*
* The generated client extends from a base AsyncApi class and provides
* a strongly-typed interface for WebSocket communication.
*/
export class WebSocketClientGenerator extends WithGeneration {
/** The SDK generator context for code generation utilities */
private context: SdkGeneratorContext;
/** The subpackage containing the WebSocket channel definition */
private subpackage: Subpackage;
/** The class reference for the generated WebSocket client class */
private classReference: ast.ClassReference;
/** The WebSocket channel definition from the IR */
private websocketChannel: WebSocketChannel;
/** The class reference for the nested Options class */
private optionsClassReference: ast.ClassReference;
/** The parameter definition for the options constructor */
private optionsParameter: ast.Parameter;
/**
* Creates a safe class name for the WebSocket client from the channel name.
*
* @param websocketChannel - The WebSocket channel definition
* @returns A PascalCase class name with "Api" suffix
*/
static createWebsocketClientClassName(websocketChannel: WebSocketChannel) {
return `${websocketChannel.name.pascalCase.safeName}Api`;
}
/**
* Creates factory methods for instantiating WebSocket API clients.
*
* Generates two overloaded factory methods:
* - One that creates a client with default options
* - One that accepts custom options as a parameter
*
* @param subpackage - The subpackage containing the WebSocket channel
* @param context - The SDK generator context
* @param namespace - The namespace for the generated class
* @param websocketChannel - The WebSocket channel definition
* @returns Array of factory method definitions
*/
static createWebSocketApiFactories(
cls: ast.Class,
subpackage: Subpackage,
context: SdkGeneratorContext,
namespace: string,
websocketChannel: WebSocketChannel
): void {
const websocketApiName = WebSocketClientGenerator.createWebsocketClientClassName(websocketChannel);
const createMethodName = `Create${websocketApiName}`;
const websocketApiClassReference = context.csharp.classReference({
origin: websocketChannel,
name: websocketApiName,
namespace
});
const optionsClassReference = context.csharp.classReference({
origin: websocketApiClassReference.explicit("Options"),
enclosingType: websocketApiClassReference
});
// if the websocket channel has required options, we can't have a default constructor
// nor a factory with a default options parameter
if (!WebSocketClientGenerator.hasRequiredOptions(websocketChannel, context)) {
cls.addMethod({
name: createMethodName,
parameters: [],
access: ast.Access.Public,
return_: websocketApiClassReference,
body: context.csharp.codeblock((writer) => {
writer.write("return ");
writer.writeNodeStatement(
context.csharp.instantiateClass({
classReference: websocketApiClassReference,
arguments_: [
context.csharp.instantiateClass({
classReference: optionsClassReference,
arguments_: []
})
]
})
);
})
});
}
cls.addMethod({
name: createMethodName,
parameters: [
context.csharp.parameter({
name: "options",
type: optionsClassReference
})
],
access: ast.Access.Public,
return_: websocketApiClassReference,
body: context.csharp.codeblock((writer) => {
writer.write("return ");
writer.writeNodeStatement(
context.csharp.instantiateClass({
classReference: websocketApiClassReference,
arguments_: [context.csharp.codeblock("options")]
})
);
})
});
}
/**
* Initializes a new WebSocket client generator.
*
* @param context - The SDK generator context
* @param subpackage - The subpackage containing the WebSocket channel
* @param websocketChannel - The WebSocket channel definition to generate code for
*/
constructor({ context, subpackage, websocketChannel }: WebSocketClientGenerator.Args) {
super(context.generation);
this.context = context;
this.subpackage = subpackage;
this.websocketChannel = websocketChannel;
this.classReference = this.csharp.classReference({
origin: websocketChannel,
name: WebSocketClientGenerator.createWebsocketClientClassName(websocketChannel),
namespace: this.context.getSubpackageClassReference(subpackage).namespace
});
this.optionsClassReference = this.csharp.classReference({
origin: this.classReference.explicit("Options"),
enclosingType: this.classReference
});
this.optionsParameter = this.csharp.parameter({
name: "options",
type: this.optionsClassReference
});
const channelPath = websocketChannel.path.head;
const envs = this.settings.temporaryWebsocketEnvironments;
if (
envs &&
envs[channelPath] &&
envs[channelPath].environments &&
Object.entries(envs[channelPath].environments).length
) {
const channel = envs[channelPath];
this.environments.push(
...Object.entries(channel.environments).map(([environment, url]) => ({
url,
environment,
name: environment
.split(/\W|_/)
.filter((p) => p)
.map((p) => `${p.charAt(0).toUpperCase()}${p.slice(1)}`)
.join("")
}))
);
// get the default environment/url from the channel, or failing that the websocketChannel.baseUrl, or failing that the first environment
this.defaultEnvironment =
channel["default-environment"] ?? this.websocketChannel.baseUrl ?? this.environments[0]?.url;
// check to see if this.defaultEnvironment is either in the environments array
// or if it is a uri, and if not, then we'll default to the first environment
if (
!this.environments.find((env) => env.environment === this.defaultEnvironment) &&
!this.defaultEnvironment?.match(/^\w+:\/\//)
) {
// no, it is not - we can't use that value unless it's an uri
this.defaultEnvironment = this.environments[0]?.url;
}
if (!this.hasEnvironments) {
// if they only have one environment, resolve the url of the default environment (since we're not naming the Environments inner class)
this.defaultEnvironment =
this.environments.filter((env) => env.environment === this.defaultEnvironment)[0]?.url ??
this.environments[0]?.url;
}
}
}
/** The default environment URL for WebSocket connections */
private defaultEnvironment: string | undefined;
/** Array of available environments with their URLs and names */
private environments: Array<{
environment: string;
name: string;
url: string;
}> = [];
/**
* Determines if multiple environments are available.
*
* @returns True if there are multiple environments, false if only one (which will be used as BaseUrl)
*/
get hasEnvironments() {
// if it only has one environment, then we're just going to use that as the BaseUrl
// without the over-head of the using an Environments class.
return this.environments != null && this.environments.length > 1;
}
/**
* Creates the nested Environments class for multi-environment support.
*
* This class provides:
* - Static properties for each environment URL
* - A getBaseUrl method for environment resolution
*
* @returns The Environments class definition, or undefined if only one environment exists
*/
private createEnvironmentsClass(): ast.Class | undefined {
if (!this.hasEnvironments) {
return undefined;
}
const environmentsClass = this.csharp.class_({
origin: this.classReference.explicit("Environments"),
static_: true,
doc: this.csharp.xmlDocBlockOf({
summary: "Selectable endpoint URLs for the API client"
}),
namespace: this.classReference.namespace,
enclosingType: this.classReference,
access: ast.Access.Public
});
environmentsClass.addMethod({
access: ast.Access.Internal,
type: ast.MethodType.STATIC,
name: "getBaseUrl",
parameters: [
this.csharp.parameter({
name: "environment",
type: this.Primitive.string
})
],
return_: this.Primitive.string,
body: this.csharp.codeblock((writer) => {
writer.write("switch(environment) {");
for (const { environment, name } of this.environments) {
writer.writeLine(`case "${environment.replace(/"/g, '\\"')}":`);
if (environment !== name) {
writer.writeLine(`case "${name.replace(/"/g, '\\"')}":`);
}
writer.indent();
writer.writeTextStatement(`return ${name}`);
writer.dedent();
}
writer.writeLine(`default:`);
writer.indent();
if (this.defaultEnvironment) {
writer.writeTextStatement(
`return string.IsNullOrEmpty(environment) ? "${this.defaultEnvironment.replace(/"/g, '\\"')}" : environment`
);
} else {
writer.writeTextStatement(`return environment`);
}
writer.popScope();
})
});
for (const { name, url } of this.environments) {
environmentsClass.addField({
static_: true,
access: ast.Access.Public,
origin: environmentsClass.explicit(name),
get: true,
set: true,
type: this.Primitive.string,
initializer: this.csharp.codeblock((writer) => writer.write(`"${url}"`))
});
}
return environmentsClass;
}
/**
* Creates the Options nested class for WebSocket connection configuration.
*
* The Options class contains:
* - BaseUrl property for the WebSocket endpoint
* - Properties for each query parameter defined in the channel
*
* @returns The Options class definition
*/
private createOptionsClass(): ast.Class {
const optionsClass = this.csharp.class_({
reference: this.optionsClassReference,
doc: this.csharp.xmlDocBlockOf({ summary: "Options for the API client" }),
access: ast.Access.Public
});
this.settings.temporaryWebsocketEnvironments;
const baseUrl = `${this.defaultEnvironment ?? this.websocketChannel.baseUrl ?? ""}`;
// Add a private backing field for BaseUrl when using environments
if (this.hasEnvironments) {
optionsClass.addField({
origin: optionsClass.explicit("_baseUrl"),
access: ast.Access.Private,
type: this.Primitive.string,
initializer: this.csharp.codeblock((writer) => {
writer.write(`"${baseUrl.replace(/"/g, '\\"')}"`);
})
});
}
optionsClass.addField({
origin: optionsClass.explicit("BaseUrl"),
access: ast.Access.Public,
type: this.Primitive.string,
summary: "The Websocket URL for the API connection.",
get: true,
set: true,
initializer: !this.hasEnvironments
? this.csharp.codeblock((writer) => {
writer.write(`"${baseUrl.replace(/"/g, '\\"')}"`);
})
: undefined,
accessors: this.hasEnvironments
? {
set: (writer: Writer) => {
writer.write(`_baseUrl = value`);
},
get: (writer: Writer) => {
writer.writeNode(this.classReference);
writer.write(`.Environments.getBaseUrl(_baseUrl)`);
}
}
: undefined
});
if (this.hasEnvironments) {
optionsClass.addField({
origin: optionsClass.explicit("Environment"),
access: ast.Access.Public,
type: this.Primitive.string,
summary: "The Environment for the API connection.",
get: true,
set: true,
accessors: {
set: (writer: Writer) => {
writer.write(`_baseUrl = value`);
},
get: (writer: Writer) => {
writer.write(`_baseUrl`);
}
}
});
}
for (const queryParameter of this.websocketChannel.queryParameters) {
// add to the options class
const type = this.context.csharpTypeMapper.convert({
reference: queryParameter.valueType
});
optionsClass.addField({
origin: queryParameter,
access: ast.Access.Public,
type,
summary: queryParameter.docs ?? "",
get: true,
set: true,
useRequired: !type.isOptional
});
}
for (const pathParameter of this.websocketChannel.pathParameters) {
const type = this.context.csharpTypeMapper.convert({
reference: pathParameter.valueType
});
optionsClass.addField({
origin: pathParameter,
access: ast.Access.Public,
type,
summary: pathParameter.docs ?? "",
get: true,
set: true,
useRequired: !type.isOptional
});
}
return optionsClass;
}
/**
* Determines if the WebSocket channel has required options that prevent default construction.
*
* @param websocketChannel - The WebSocket channel definition
* @param context - The SDK generator context for type mapping
* @returns True if any path or query parameters are required
*/
private static hasRequiredOptions(websocketChannel: WebSocketChannel, context: SdkGeneratorContext) {
return (
websocketChannel.pathParameters.some(
(p) => !context.csharpTypeMapper.convert({ reference: p.valueType }).isOptional
) ||
websocketChannel.queryParameters.some(
(p) => !context.csharpTypeMapper.convert({ reference: p.valueType }).isOptional
)
);
}
/**
* Creates the default constructor that initializes with default options.
*
* @returns Constructor definition with no parameters
*/
private createDefaultConstructor() {
return {
access: ast.Access.Public,
parameters: [],
body: this.csharp.codeblock((writer) => {
//
}),
doc: this.csharp.xmlDocBlockOf({ summary: "Default constructor" }),
thisConstructorCall: this.csharp.invokeMethod({
method: "this",
arguments_: [
this.csharp.codeblock((writer) => {
writer.writeNode(
this.csharp.instantiateClass({
classReference: this.optionsClassReference,
arguments_: []
})
);
})
]
})
};
}
/**
* Creates a constructor that accepts custom options.
* Initializes _options and _client fields with the WebSocket URI and message handler.
* The URI building logic is inlined directly in the constructor.
*
* @returns Constructor definition that takes an Options parameter
*/
private createConstructorWithOptions() {
return {
access: ast.Access.Public,
parameters: [this.optionsParameter],
body: this.csharp.codeblock((writer) => {
// Initialize _options
writer.writeTextStatement(`_options = ${this.optionsParameter.name}`);
// Build the URI inline (previously in CreateUri method)
const hasQueryParameters = this.websocketChannel.queryParameters.length > 0;
writer.write("var uri = ");
writer.writeNode(
this.System.UriBuilder.new({
arguments_: [this.csharp.codeblock((writer) => writer.write("_options.BaseUrl"))]
})
);
if (hasQueryParameters) {
writer.write(
`\n{\n Query = new ${this.namespaces.qualifiedCore}.QueryStringBuilder.Builder(capacity: ${this.websocketChannel.queryParameters.length})`
);
for (const queryParameter of this.websocketChannel.queryParameters) {
const isComplexType = this.isComplexType(queryParameter.valueType);
if (isComplexType) {
writer.write(
`\n .AddDeepObject("${queryParameter.name.wireValue}", _options.${queryParameter.name.name.pascalCase.safeName})`
);
} else {
writer.write(
`\n .Add("${queryParameter.name.wireValue}", _options.${queryParameter.name.name.pascalCase.safeName})`
);
}
}
writer.writeTextStatement("\n .Build()\n}");
} else {
writer.writeTextStatement("");
}
const parts: (ast.AstNode | string)[] = [];
// start with the head
if (this.websocketChannel.path.head) {
parts.push(this.websocketChannel.path.head);
}
// collect each part (parameter, then tail)
for (const each of this.websocketChannel.path.parts) {
const pp = this.websocketChannel.pathParameters.find(
(p) => p.name.originalName === each.pathParameter
);
if (pp) {
parts.push(
this.csharp.codeblock((writer) =>
writer.write(`Uri.EscapeDataString(_options.${pp.name.pascalCase.safeName})`)
)
);
}
if (each.tail) {
parts.push(each.tail);
}
}
if (parts.length) {
writer.write(`uri.Path = $"{uri.Path.TrimEnd('/')}`);
for (const part of parts) {
writer.write(`/`);
if (typeof part === "string") {
writer.write(part.replace(/^\/+/, "").replace(/\/+$/, ""));
} else {
writer.write("{", part, "}");
}
}
writer.writeTextStatement(`"`);
}
// Initialize _client with URI and OnTextMessage handler
writer.write("_client = ");
writer.writeNode(
this.csharp.instantiateClass({
classReference: this.Types.WebSocketClient,
arguments_: [this.csharp.codeblock("uri.Uri"), this.csharp.codeblock("OnTextMessage")]
})
);
writer.writeTextStatement("");
// Note: PropertyChanged event forwarding is handled by the event's add/remove accessors
}),
doc: this.csharp.xmlDocBlockOf({ summary: "Constructor with options" })
};
}
/**
* Gets the server-to-client event definitions from the WebSocket channel.
*
* Processes incoming server messages and handles:
* - Single message types
* - OneOf message types (expanded into multiple events)
*
* @returns Array of event definitions with type, event class, and name
*/
private get events() {
const result: {
type: ast.Type | ast.ClassReference;
eventType: ast.ClassReference;
name: string | undefined;
}[] = [];
for (const each of this.websocketChannel.messages) {
if (each.origin === "server" && each.body.type === "reference") {
const reference = each.body.bodyType;
const type = this.context.csharpTypeMapper.convert({
reference: each.body.bodyType
});
if (each.body.type === "reference") {
const reference = each.body.bodyType;
const type = this.context.csharpTypeMapper.convert({
reference: each.body.bodyType
});
// if the result is a oneof, we will expand it into multiple
if (is.OneOf.OneOf(type)) {
for (const oneOfType of type.generics) {
result.push({
type: oneOfType,
eventType: this.Types.WebSocketEvent(oneOfType),
name: is.ClassReference(oneOfType) ? oneOfType.name : undefined
});
}
} else {
// otherwise it's just a single type here
result.push({
type,
eventType: this.Types.WebSocketEvent(type),
name:
reference._visit({
container: () => undefined,
named: (named) => named.name.pascalCase.safeName,
primitive: (value) => undefined,
unknown: () => undefined,
_other: (value) => value.type
}) || each.displayName
});
}
}
}
}
return result;
}
/**
* Gets the client-to-server message definitions from the WebSocket channel.
*
* @returns Array of message definitions that can be sent to the server
*/
private get messages() {
return this.websocketChannel.messages
.filter((message) => message.origin === "client")
.map((each) => {
if (each.body.type === "reference") {
const bodyType = each.body.bodyType;
let type = this.context.csharpTypeMapper.convert({
reference: each.body.bodyType
});
// if the body type is just a string, this is probably a binary message...
if (bodyType.type === "primitive" && bodyType.primitive.v2?.type === "string") {
type = this.Value.binary;
}
return {
reference: each.body.bodyType,
type,
eventType: this.Types.WebSocketEvent(type),
name:
bodyType._visit({
container: () => undefined,
named: (named) => named.name.pascalCase.safeName,
primitive: () => each.type,
unknown: () => each.type,
_other: () => each.type
}) || each.displayName
};
}
return undefined;
})
.filter((each) => each !== undefined);
}
/**
* Creates the OnTextMessage method for handling incoming WebSocket messages.
*
* This method:
* - Deserializes incoming JSON messages
* - Attempts to match messages to known event types
* - Raises appropriate events when messages are successfully parsed
* - Handles unknown message types by raising exceptions
*
* @returns The OnTextMessage method definition
*/
private createOnTextMessageMethod(cls: ast.Class) {
cls.addMethod({
access: ast.Access.Private,
isAsync: true,
name: "OnTextMessage",
doc: this.csharp.xmlDocBlockOf({
summary: "Dispatches incoming WebSocket messages"
}),
parameters: [
this.csharp.parameter({
name: "stream",
type: this.System.IO.Stream
})
],
body: this.csharp.codeblock((writer) => {
// deserialize the json message
writer.write(`var json = await `);
writer.writeNode(this.System.Text.Json.JsonSerializer);
writer.write(`.DeserializeAsync<`);
writer.writeNode(this.System.Text.Json.JsonDocument);
writer.writeTextStatement(`>(stream)`);
writer.writeLine(`if(json == null)`);
writer.pushScope();
writer.writeTextStatement(
`await ExceptionOccurred.RaiseEvent(new Exception("Invalid message - Not valid JSON")).ConfigureAwait(false)`
);
writer.writeTextStatement(`return`);
writer.popScope();
// there is no empirical way to determine the correct event type from the IR
// so the only option is to try each event model until one is successful
// iterate thru the event models and try to deserialize the message to the correct event
writer.writeLine();
writer.writeLine("// deserialize the message to find the correct event");
for (const event of this.events) {
writer.pushScope();
writer.write(
`if(`,
this.Types.JsonUtils,
`.TryDeserialize(json`,
`, out `,
event.name,
`? message))`
);
writer.pushScope();
writer.writeTextStatement(`await ${event.name}.RaiseEvent(message!).ConfigureAwait(false)`);
writer.writeTextStatement(`return`);
writer.popScope();
writer.popScope();
writer.writeLine();
}
// if no event was found, raise an exception
writer.writeTextStatement(
`await ExceptionOccurred.RaiseEvent(new Exception($"Unknown message: {json.ToString()}")).ConfigureAwait(false)`
);
})
});
}
/**
* Creates Send methods for each client-to-server message type.
*
* Each method:
* - Accepts a strongly-typed message parameter
* - Serializes the message to JSON
* - Sends it through the WebSocket connection via _client.SendInstant
*
* @returns Array of Send method definitions
*/
private createSendMessageMethods(cls: ast.Class): void {
this.messages.forEach((each) => {
cls.addMethod({
access: ast.Access.Public,
isAsync: true,
name: `Send`,
parameters: [
this.csharp.parameter({
name: "message",
type: each.type
})
],
doc: this.csharp.xmlDocBlockOf({
summary: `Sends a ${each.name} message to the server`
}),
body: this.csharp.codeblock((writer) => {
writer.writeLine(`await _client.SendInstant(`);
writer.writeNode(this.Types.JsonUtils);
writer.writeTextStatement(`.Serialize(message)).ConfigureAwait(false)`);
})
});
});
}
/**
* Creates public event fields for subscribing to server messages.
*
* Each event field:
* - Is strongly-typed to the corresponding message type
* - Allows clients to subscribe to specific message types
* - Is automatically disposed when the client is disposed
*
* @returns Array of event field definitions
*/
private createEventFields(cls: ast.Class) {
for (const each of this.events) {
cls.addField({
origin: cls.explicit(`${each.name}`),
readonly: true,
initializer: this.csharp.codeblock((writer) => writer.write(`new()`)),
access: ast.Access.Public,
doc: this.csharp.xmlDocBlockOf({
summary: `Event handler for ${each.name}. \nUse ${each.name}.Subscribe(...) to receive messages.`
}),
type: each.eventType
});
}
}
/**
* Creates the Status property that forwards to _client.Status.
* Uses expression-bodied property syntax: public ConnectionStatus Status => _client.Status;
*/
private createStatusProperty(cls: ast.Class) {
cls.addField({
origin: cls.explicit("Status"),
access: ast.Access.Public,
type: this.Types.ConnectionStatus,
summary: "Gets the current connection status of the WebSocket.",
get: true,
initializer: this.csharp.codeblock("_client.Status")
});
}
/**
* Creates the ConnectAsync method that forwards to _client.ConnectAsync.
*/
private createConnectAsyncMethod(cls: ast.Class) {
cls.addMethod({
access: ast.Access.Public,
isAsync: true,
name: "ConnectAsync",
// Note: Don't specify return_ for async void methods - the AST handles Task return type automatically
doc: this.csharp.xmlDocBlockOf({
summary: "Asynchronously establishes a WebSocket connection."
}),
body: this.csharp.codeblock((writer) => {
writer.writeTextStatement("await _client.ConnectAsync().ConfigureAwait(false)");
})
});
}
/**
* Creates the CloseAsync method that forwards to _client.CloseAsync.
*/
private createCloseAsyncMethod(cls: ast.Class) {
cls.addMethod({
access: ast.Access.Public,
isAsync: true,
name: "CloseAsync",
// Note: Don't specify return_ for async void methods - the AST handles Task return type automatically
doc: this.csharp.xmlDocBlockOf({
summary: "Asynchronously closes the WebSocket connection."
}),
body: this.csharp.codeblock((writer) => {
writer.writeTextStatement("await _client.CloseAsync().ConfigureAwait(false)");
})
});
}
/**
* Creates the DisposeEvents helper method that disposes all event subscriptions.
*/
private createDisposeEventsMethod(cls: ast.Class) {
cls.addMethod({
access: ast.Access.Private,
name: "DisposeEvents",
doc: this.csharp.xmlDocBlockOf({
summary: "Disposes of event subscriptions"
}),
body: this.csharp.codeblock((writer) => {
for (const event of this.events) {
writer.writeTextStatement(`${event.name}.Dispose()`);
}
})
});
}
/**
* Creates the DisposeAsync method for IAsyncDisposable implementation.
* Uses async ValueTask pattern with GC.SuppressFinalize.
*/
private createDisposeAsyncMethod(cls: ast.Class) {
// We use Primitive.Arbitrary to write "async ValueTask" directly as the return type.
// This avoids the AST's Task<T> wrapping that happens when isAsync: true is used.
// The result is: public async ValueTask DisposeAsync()
cls.addMethod({
access: ast.Access.Public,
name: "DisposeAsync",
return_: this.Types.Arbitrary("async ValueTask"),
doc: this.csharp.xmlDocBlockOf({
summary:
"Asynchronously disposes the WebSocket client, closing any active connections and cleaning up resources."
}),
body: this.csharp.codeblock((writer) => {
writer.writeLine("await _client.DisposeAsync();");
writer.writeLine("DisposeEvents();");
writer.writeTextStatement("GC.SuppressFinalize(this)");
})
});
}
/**
* Creates the Dispose method for IDisposable implementation.
* Includes GC.SuppressFinalize for proper disposal pattern.
*/
private createDisposeMethod(cls: ast.Class) {
cls.addMethod({
access: ast.Access.Public,
name: "Dispose",
doc: this.csharp.xmlDocBlockOf({
summary:
"Synchronously disposes the WebSocket client, closing any active connections and cleaning up resources."
}),
body: this.csharp.codeblock((writer) => {
writer.writeTextStatement("_client.Dispose()");
writer.writeTextStatement("DisposeEvents()");
writer.writeTextStatement("GC.SuppressFinalize(this)");
})
});
}
/**
* Creates the PropertyChanged event for INotifyPropertyChanged implementation.
* The event is forwarded from the internal _client instance.
*/
private createPropertyChangedEvent(cls: ast.Class) {
cls.addNamespaceReference("System.ComponentModel");
// Add the PropertyChanged event with add/remove accessors (C# event syntax)
cls.addField({
origin: cls.explicit("PropertyChanged"),
access: ast.Access.Public,
type: this.System.ComponentModel.PropertyChangedEventHandler,
summary: "Event that is raised when a property value changes.",
isEvent: true,
accessors: {
add: (writer) => {
writer.write("_client.PropertyChanged += value");
},
remove: (writer) => {
writer.write("_client.PropertyChanged -= value");
}
}
});
}
/**
* Creates event forwarders for Connected, Closed, and ExceptionOccurred from _client.
* Uses expression-bodied property syntax: public Event<Connected> Connected => _client.Connected;
*/
private createClientEventForwarders(cls: ast.Class) {
// Connected event
cls.addField({
origin: cls.explicit("Connected"),
access: ast.Access.Public,
type: this.Types.WebSocketEvent(this.Types.WebSocketConnected),
summary: "Event that is raised when the WebSocket connection is established.",
get: true,
initializer: this.csharp.codeblock("_client.Connected")
});
// Closed event
cls.addField({
origin: cls.explicit("Closed"),
access: ast.Access.Public,
type: this.Types.WebSocketEvent(this.Types.WebSocketClosed),
summary: "Event that is raised when the WebSocket connection is closed.",
get: true,
initializer: this.csharp.codeblock("_client.Closed")
});
// ExceptionOccurred event
cls.addField({
origin: cls.explicit("ExceptionOccurred"),
access: ast.Access.Public,
type: this.Types.WebSocketEvent(this.System.Exception),
summary: "Event that is raised when an exception occurs during WebSocket operations.",
get: true,
initializer: this.csharp.codeblock("_client.ExceptionOccurred")
});
}
/**
* Creates the complete WebSocket client class.
*
* Assembles all components into a single class:
* - Constructors (default and with options)
* - Nested Options class
* - Private _options and _client fields
* - Status property forwarded from _client
* - Event fields forwarded from _client (Connected, Closed, ExceptionOccurred)
* - Send methods for outgoing messages
* - IAsyncDisposable, IDisposable, INotifyPropertyChanged implementations
*
* @returns The complete WebSocket client class definition
*/
private createWebsocketClass() {
const cls = this.csharp.class_({
reference: this.classReference,
access: ast.Access.Public,
partial: true,
doc: this.websocketChannel.docs ? { summary: this.websocketChannel.docs } : undefined,
interfaceReferences: [
this.System.IAsyncDisposable,
this.System.IDisposable,
this.System.ComponentModel.INotifyPropertyChanged
]
});
// Add private fields for options and client
cls.addField({
origin: cls.explicit("_options"),
access: ast.Access.Private,
readonly: true,
type: this.optionsClassReference
});
cls.addField({
origin: cls.explicit("_client"),
access: ast.Access.Private,