forked from pixie-io/pixie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc_generator.cc
1818 lines (1651 loc) · 60.3 KB
/
grpc_generator.cc
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 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <algorithm>
#include <iterator>
#include <set>
#include <string>
using google::protobuf::Descriptor;
using google::protobuf::EnumDescriptor;
using google::protobuf::FieldDescriptor;
using google::protobuf::FileDescriptor;
using google::protobuf::MethodDescriptor;
using google::protobuf::ServiceDescriptor;
using google::protobuf::FieldOptions;
using google::protobuf::OneofDescriptor;
using google::protobuf::compiler::CodeGenerator;
using google::protobuf::compiler::GeneratorContext;
using google::protobuf::compiler::ParseGeneratorParameter;
using google::protobuf::compiler::PluginMain;
using google::protobuf::io::Printer;
using google::protobuf::io::ZeroCopyOutputStream;
namespace grpc {
namespace web {
namespace {
using std::string;
enum Mode {
OP = 0, // first party google3 one platform services
OPJSPB = 1, // first party google3 one platform services with JSPB
GRPCWEB = 2, // client using the application/grpc-web wire format
};
enum ImportStyle {
CLOSURE = 0, // goog.require("grpc.web.*")
COMMONJS = 1, // const grpcWeb = require("grpc-web")
TYPESCRIPT = 2, // import * as grpcWeb from 'grpc-web'
};
const char GRPC_PROMISE[] = "grpc.web.promise.GrpcWebPromise";
const char* kKeyword[] = {
"abstract",
"boolean",
"break",
"byte",
"case",
"catch",
"char",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"double",
"else",
"enum",
"export",
"extends",
"false",
"final",
"finally",
"float",
"for",
"function",
"goto",
"if",
"implements",
"import",
"in",
"instanceof",
"int",
"interface",
"long",
"native",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"short",
"static",
"super",
"switch",
"synchronized",
"this",
"throw",
"throws",
"transient",
"try",
"typeof",
"var",
"void",
"volatile",
"while",
"with",
};
bool IsReserved(const string& ident) {
for (size_t i = 0; i < sizeof(kKeyword) / sizeof(kKeyword[0]); i++) {
if (ident == kKeyword[i]) {
return true;
}
}
return false;
}
string GetModeVar(const Mode mode) {
switch (mode) {
case OP:
return "OP";
case OPJSPB:
return "OPJspb";
case GRPCWEB:
return "GrpcWeb";
}
return "";
}
string GetDeserializeMethodName(const string& mode_var) {
if (mode_var == GetModeVar(Mode::OPJSPB)) {
return "deserialize";
}
return "deserializeBinary";
}
string GetSerializeMethodName(const string& mode_var) {
if (mode_var == GetModeVar(Mode::OPJSPB)) {
return "serialize";
}
return "serializeBinary";
}
std::string GetSerializeMethodReturnType(const string& mode_var) {
if (mode_var == GetModeVar(Mode::OPJSPB)) {
return "string";
}
return "!Uint8Array";
}
string LowercaseFirstLetter(string s) {
if (s.empty()) {
return s;
}
s[0] = ::tolower(s[0]);
return s;
}
string Lowercase(string s) {
if (s.empty()) {
return s;
}
for (size_t i = 0; i < s.size(); i++) {
s[i] = ::tolower(s[i]);
}
return s;
}
string UppercaseFirstLetter(string s) {
if (s.empty()) {
return s;
}
s[0] = ::toupper(s[0]);
return s;
}
string Uppercase(string s) {
if (s.empty()) {
return s;
}
for (size_t i = 0; i < s.size(); i++) {
s[i] = ::toupper(s[i]);
}
return s;
}
// The following 5 functions were copied from
// google/protobuf/src/google/protobuf/stubs/strutil.h
inline bool HasPrefixString(const string& str,
const string& prefix) {
return str.size() >= prefix.size() &&
str.compare(0, prefix.size(), prefix) == 0;
}
inline string StripPrefixString(const string& str, const string& prefix) {
if (HasPrefixString(str, prefix)) {
return str.substr(prefix.size());
} else {
return str;
}
}
inline bool HasSuffixString(const string& str,
const string& suffix) {
return str.size() >= suffix.size() &&
str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}
inline string StripSuffixString(const string& str, const string& suffix) {
if (HasSuffixString(str, suffix)) {
return str.substr(0, str.size() - suffix.size());
} else {
return str;
}
}
void ReplaceCharacters(string *s, const char *remove, char replacewith) {
const char *str_start = s->c_str();
const char *str = str_start;
for (str = strpbrk(str, remove);
str != nullptr;
str = strpbrk(str + 1, remove)) {
(*s)[str - str_start] = replacewith;
}
}
// The following function was copied from
// google/protobuf/src/google/protobuf/compiler/cpp/cpp_helpers.cc
string StripProto(const string& filename) {
if (HasSuffixString(filename, ".protodevel")) {
return StripSuffixString(filename, ".protodevel");
} else {
return StripSuffixString(filename, ".proto");
}
}
// The following 6 functions were copied from
// google/protobuf/src/google/protobuf/compiler/js/js_generator.cc
char ToLowerASCII(char c) {
if (c >= 'A' && c <= 'Z') {
return (c - 'A') + 'a';
} else {
return c;
}
}
std::vector<string> ParseLowerUnderscore(const string& input) {
std::vector<string> words;
string running = "";
for (size_t i = 0; i < input.size(); i++) {
if (input[i] == '_') {
if (!running.empty()) {
words.push_back(running);
running.clear();
}
} else {
running += ToLowerASCII(input[i]);
}
}
if (!running.empty()) {
words.push_back(running);
}
return words;
}
string ToUpperCamel(const std::vector<string>& words) {
string result;
for (size_t i = 0; i < words.size(); i++) {
string word = words[i];
if (word[0] >= 'a' && word[0] <= 'z') {
word[0] = (word[0] - 'a') + 'A';
}
result += word;
}
return result;
}
// Returns the alias we assign to the module of the given .proto filename
// when importing.
string ModuleAlias(const string& filename) {
// This scheme could technically cause problems if a file includes any 2 of:
// foo/bar_baz.proto
// foo_bar_baz.proto
// foo_bar/baz.proto
//
// We'll worry about this problem if/when we actually see it. This name isn't
// exposed to users so we can change it later if we need to.
string basename = StripProto(filename);
ReplaceCharacters(&basename, "-", '$');
ReplaceCharacters(&basename, "/", '_');
ReplaceCharacters(&basename, ".", '_');
return basename + "_pb";
}
string JSMessageType(const Descriptor *desc, const FileDescriptor *file) {
string class_name;
class_name = StripPrefixString(desc->full_name(), desc->file()->package());
if (!class_name.empty() && class_name[0] == '.') {
class_name = class_name.substr(1);
}
if (desc->file() == file) {
// [for protobuf .d.ts files only] Do not add the module prefix for local
// messages.
return class_name;
}
return ModuleAlias(desc->file()->name()) + "." + class_name;
}
string JSMessageType(const Descriptor *desc) {
return JSMessageType(desc, nullptr);
}
string JSElementType(const FieldDescriptor *desc, const FileDescriptor *file) {
switch (desc->type()) {
case FieldDescriptor::TYPE_DOUBLE:
case FieldDescriptor::TYPE_FLOAT:
case FieldDescriptor::TYPE_INT32:
case FieldDescriptor::TYPE_UINT32:
case FieldDescriptor::TYPE_SINT32:
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_SFIXED32:
return "number";
case FieldDescriptor::TYPE_INT64:
case FieldDescriptor::TYPE_UINT64:
case FieldDescriptor::TYPE_SINT64:
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_SFIXED64:
if (desc->options().jstype() == FieldOptions::JS_STRING) {
return "string";
} else {
return "number";
}
case FieldDescriptor::TYPE_BOOL:
return "boolean";
case FieldDescriptor::TYPE_STRING:
return "string";
case FieldDescriptor::TYPE_BYTES:
return "Uint8Array | string";
case FieldDescriptor::TYPE_ENUM:
if (desc->enum_type()->file() == file) {
// [for protobuf .d.ts files only] Do not add the module prefix for
// local messages.
string enum_name =
StripPrefixString(
desc->enum_type()->full_name(),
desc->enum_type()->file()->package());
return StripPrefixString(enum_name, ".");
}
return ModuleAlias(desc->enum_type()->file()->name())
+ StripPrefixString(
desc->enum_type()->full_name(),
desc->enum_type()->file()->package());
case FieldDescriptor::TYPE_MESSAGE:
return JSMessageType(desc->message_type(), file);
default:
return "{}";
}
}
string JSFieldType(const FieldDescriptor *desc, const FileDescriptor *file) {
string js_field_type = JSElementType(desc, file);
if (desc->is_map()) {
string key_type = JSFieldType(desc->message_type()->field(0), file);
string value_type = JSFieldType(desc->message_type()->field(1), file);
return "jspb.Map<" + key_type + ", " + value_type + ">";
}
if (desc->is_repeated())
{
return "Array<" + js_field_type + ">";
}
return js_field_type;
}
string AsObjectFieldType(
const FieldDescriptor *desc, const FileDescriptor *file) {
if (desc->type() != FieldDescriptor::TYPE_MESSAGE) {
return JSFieldType(desc, file);
}
if (desc->is_map()) {
const Descriptor* message = desc->message_type();
string key_type = AsObjectFieldType(message->field(0), file);
string value_type = AsObjectFieldType(message->field(1), file);
return "Array<[" + key_type + ", " + value_type + "]>";
}
string field_type = JSMessageType(desc->message_type(), file) + ".AsObject";
if (desc->is_repeated()) {
return "Array<" + field_type + ">";
}
return field_type;
}
string JSElementName(const FieldDescriptor *desc) {
return ToUpperCamel(ParseLowerUnderscore(desc->name()));
}
string JSFieldName(const FieldDescriptor *desc) {
string js_field_name = JSElementName(desc);
if (desc->is_map()) {
js_field_name += "Map";
} else if (desc->is_repeated()) {
js_field_name += "List";
}
return js_field_name;
}
// Like ToUpperCamel except the first letter is not converted.
string ToCamelCase(const std::vector<string>& words)
{
if (words.empty()) {
return "";
}
string result = words[0];
return result + ToUpperCamel(std::vector<string>(
words.begin()+1,
words.begin()+words.size()));
}
// Like JSFieldName, but with first letter not uppercased
string CamelCaseJSFieldName(const FieldDescriptor *desc)
{
string js_field_name = ToCamelCase(ParseLowerUnderscore(desc->name()));
if (desc->is_map()) {
js_field_name += "Map";
} else if (desc->is_repeated()) {
js_field_name += "List";
}
return js_field_name;
}
// Returns the name of the message with a leading dot and taking into account
// nesting, for example ".OuterMessage.InnerMessage", or returns empty if
// descriptor is null. This function does not handle namespacing, only message
// nesting.
string GetNestedMessageName(const Descriptor* descriptor) {
if (descriptor == nullptr) {
return "";
}
string result = StripPrefixString(descriptor->full_name(),
descriptor->file()->package());
// Add a leading dot if one is not already present.
if (!result.empty() && result[0] != '.') {
result = "." + result;
}
return result;
}
// Given a filename like foo/bar/baz.proto, returns the root directory
// path ../../
string GetRootPath(const string& from_filename, const string& to_filename) {
if (HasPrefixString(to_filename, "google/protobuf")) {
// Well-known types (.proto files in the google/protobuf directory) are
// assumed to come from the 'google-protobuf' npm package. We may want to
// generalize this exception later by letting others put generated code in
// their own npm packages.
return "google-protobuf/";
}
size_t slashes = std::count(from_filename.begin(), from_filename.end(), '/');
if (slashes == 0) {
return "./";
}
string result = "";
for (size_t i = 0; i < slashes; i++) {
result += "../";
}
return result;
}
// Splits path immediately following the final slash, separating it into a
// directory and file name component. Directory will contain the last
// slash, if it's not empty.
// If there is no slash in path, Split returns an empty directory and
// basename set to path.
// Output values have the property that path = directory + basename.
void PathSplit(const string& path, string* directory, string* basename) {
string::size_type last_slash = path.rfind('/');
if (last_slash == string::npos) {
if (directory) {
*directory = "";
}
if (basename) {
*basename = path;
}
} else {
if (directory) {
*directory = path.substr(0, last_slash + 1);
}
if (basename) {
*basename = path.substr(last_slash + 1);
}
}
}
// Returns the basename of a file.
string GetBasename(string filename) {
string basename;
PathSplit(filename, nullptr, &basename);
return basename;
}
// Finds all message types used in all services in the file.
std::set<const Descriptor*> GetAllMessages(const FileDescriptor* file) {
std::set<const Descriptor*> messages;
for (int s = 0; s < file->service_count(); ++s) {
const ServiceDescriptor* service = file->service(s);
for (int m = 0; m < service->method_count(); ++m) {
const MethodDescriptor *method = service->method(m);
messages.insert(method->input_type());
messages.insert(method->output_type());
}
}
return messages;
}
void PrintClosureDependencies(Printer* printer, const FileDescriptor* file) {
for (const Descriptor* message : GetAllMessages(file)) {
printer->Print(
"goog.require('proto.$full_name$');\n",
"full_name", message->full_name());
}
printer->Print("\n\n\n");
}
void PrintCommonJsMessagesDeps(Printer* printer, const FileDescriptor* file) {
std::map<string, string> vars;
for (int i = 0; i < file->dependency_count(); i++) {
const string& name = file->dependency(i)->name();
vars["alias"] = ModuleAlias(name);
vars["dep_filename"] = GetRootPath(file->name(), name) + StripProto(name);
// we need to give each cross-file import an alias
printer->Print(
vars,
"\nvar $alias$ = require('$dep_filename$_pb.js')\n");
}
string package = file->package();
vars["package_name"] = package;
if (!package.empty()) {
size_t offset = 0;
size_t dotIndex = package.find('.');
printer->Print(vars, "const proto = {};\n");
while (dotIndex != string::npos) {
vars["current_package_ns"] = package.substr(0, dotIndex);
printer->Print(vars, "proto.$current_package_ns$ = {};\n");
offset = dotIndex + 1;
dotIndex = package.find(".", offset);
}
}
// need to import the messages from our own file
vars["filename"] = GetBasename(StripProto(file->name()));
if (!package.empty()) {
printer->Print(
vars,
"proto.$package_name$ = require('./$filename$_pb.js');\n\n");
} else {
printer->Print(
vars,
"const proto = require('./$filename$_pb.js');\n\n");
}
}
void PrintES6Imports(Printer* printer, const FileDescriptor* file) {
std::map<string, string> vars;
printer->Print("import * as grpcWeb from 'grpc-web';\n\n");
std::set<string> imports;
for (const Descriptor* message : GetAllMessages(file)) {
const string& name = message->file()->name();
string dep_filename = GetRootPath(file->name(), name) + StripProto(name);
if (imports.find(dep_filename) != imports.end()) {
continue;
}
imports.insert(dep_filename);
// We need to give each cross-file import an alias.
printer->Print(
"import * as $alias$ from '$dep_filename$_pb';\n",
"alias", ModuleAlias(name),
"dep_filename", dep_filename);
}
printer->Print("\n\n");
}
void PrintTypescriptFile(Printer* printer, const FileDescriptor* file,
std::map<string, string> vars) {
PrintES6Imports(printer, file);
for (int service_index = 0; service_index < file->service_count();
++service_index) {
printer->Print("export class ");
const ServiceDescriptor* service = file->service(service_index);
vars["service_name"] = service->name();
printer->Print(vars, "$service_name$Client {\n");
printer->Indent();
printer->Print(
"client_: grpcWeb.AbstractClientBase;\n"
"hostname_: string;\n"
"credentials_: null | { [index: string]: string; };\n"
"options_: null | { [index: string]: any; };\n\n"
"constructor (hostname: string,\n"
" credentials?: null | { [index: string]: string; },\n"
" options?: null | { [index: string]: any; }) {\n");
printer->Indent();
printer->Print("if (!options) options = {};\n");
printer->Print("if (!credentials) credentials = {};\n");
if (vars["mode"] == GetModeVar(Mode::GRPCWEB)) {
printer->Print(vars, "options['format'] = '$format$';\n\n");
}
printer->Print(vars,
"this.client_ = new grpcWeb.$mode$ClientBase(options);\n"
"this.hostname_ = hostname;\n"
"this.credentials_ = credentials;\n"
"this.options_ = options;\n");
printer->Outdent();
printer->Print("}\n\n");
for (int method_index = 0; method_index < service->method_count();
++method_index) {
const MethodDescriptor* method = service->method(method_index);
vars["js_method_name"] = LowercaseFirstLetter(method->name());
vars["method_name"] = method->name();
vars["input_type"] = JSMessageType(method->input_type());
vars["output_type"] = JSMessageType(method->output_type());
vars["serialize_func_name"] = GetSerializeMethodName(vars["mode"]);
vars["deserialize_func_name"] = GetDeserializeMethodName(vars["mode"]);
if (!method->client_streaming()) {
// TODO(jennyjiang): use methodDescriptor?
printer->Print(vars,
"methodInfo$method_name$ = "
"new grpcWeb.AbstractClientBase.MethodInfo(\n");
printer->Indent();
printer->Print(vars,
"$output_type$,\n"
"(request: $input_type$) => {\n"
" return request.$serialize_func_name$();\n"
"},\n"
"$output_type$.$deserialize_func_name$\n");
printer->Outdent();
printer->Print(");\n\n");
if (method->server_streaming()) {
printer->Print(vars, "$js_method_name$(\n");
printer->Indent();
printer->Print(vars,
"request: $input_type$,\n"
"metadata?: grpcWeb.Metadata) {\n");
printer->Print(vars, "return this.client_.serverStreaming(\n");
printer->Indent();
printer->Print(
vars,
"this.hostname_ +\n"
" '/$package_dot$$service_name$/$method_name$',\n"
"request,\n"
"metadata || {},\n"
"this.methodInfo$method_name$);\n");
printer->Outdent();
printer->Outdent();
printer->Print("}\n\n");
} else {
printer->Print(vars, "$js_method_name$(\n");
printer->Indent();
printer->Print(vars,
"request: $input_type$,\n"
"metadata: grpcWeb.Metadata | null): "
"$promise$<$output_type$>;\n\n");
printer->Outdent();
printer->Print(vars, "$js_method_name$(\n");
printer->Indent();
printer->Print(vars,
"request: $input_type$,\n"
"metadata: grpcWeb.Metadata | null,\n"
"callback: (err: grpcWeb.Error,\n"
" response: $output_type$) => void): "
"grpcWeb.ClientReadableStream<$output_type$>;\n\n");
printer->Outdent();
printer->Print(vars, "$js_method_name$(\n");
printer->Indent();
printer->Print(vars,
"request: $input_type$,\n"
"metadata: grpcWeb.Metadata | null,\n"
"callback?: (err: grpcWeb.Error,\n"
" response: $output_type$) => void) {\n");
printer->Print(vars, "if (callback !== undefined) {\n");
printer->Indent();
printer->Print(vars, "return this.client_.rpcCall(\n");
printer->Indent();
printer->Print(
vars,
"this.hostname_ +\n"
" '/$package_dot$$service_name$/$method_name$',\n"
"request,\n"
"metadata || {},\n"
"this.methodInfo$method_name$,\n"
"callback);\n");
printer->Outdent();
printer->Outdent();
printer->Print(vars,
"}\n"
"return this.client_.unaryCall(\n");
printer->Print(vars,
"this.hostname_ +\n"
" '/$package_dot$$service_name$/$method_name$',\n"
"request,\n"
"metadata || {},\n"
"this.methodInfo$method_name$);\n");
printer->Outdent();
printer->Print("}\n\n");
}
}
}
printer->Outdent();
printer->Print("}\n\n");
}
}
void PrintGrpcWebDtsClientClass(Printer* printer, const FileDescriptor* file,
const string &client_type) {
std::map<string, string> vars;
vars["client_type"] = client_type;
vars["promise"] = "Promise";
for (int service_index = 0; service_index < file->service_count();
++service_index) {
printer->Print("export class ");
const ServiceDescriptor* service = file->service(service_index);
vars["service_name"] = service->name();
printer->Print(vars, "$service_name$$client_type$ {\n");
printer->Indent();
printer->Print(
"constructor (hostname: string,\n"
" credentials?: null | { [index: string]: string; },\n"
" options?: null | { [index: string]: any; });\n\n");
for (int method_index = 0; method_index < service->method_count();
++method_index) {
const MethodDescriptor* method = service->method(method_index);
vars["js_method_name"] = LowercaseFirstLetter(method->name());
vars["input_type"] = JSMessageType(method->input_type());
vars["output_type"] = JSMessageType(method->output_type());
if (!method->client_streaming()) {
if (method->server_streaming()) {
printer->Print(vars, "$js_method_name$(\n");
printer->Indent();
printer->Print(vars,
"request: $input_type$,\n"
"metadata?: grpcWeb.Metadata\n");
printer->Outdent();
printer->Print(vars,
"): grpcWeb.ClientReadableStream<$output_type$>;\n\n");
} else {
if (vars["client_type"] == "PromiseClient") {
printer->Print(vars, "$js_method_name$(\n");
printer->Indent();
printer->Print(vars,
"request: $input_type$,\n"
"metadata?: grpcWeb.Metadata\n");
printer->Outdent();
printer->Print(vars, "): $promise$<$output_type$>;\n\n");
} else {
printer->Print(vars, "$js_method_name$(\n");
printer->Indent();
printer->Print(vars,
"request: $input_type$,\n"
"metadata: grpcWeb.Metadata | undefined,\n"
"callback: (err: grpcWeb.Error,\n"
" response: $output_type$) => void\n");
printer->Outdent();
printer->Print(vars,
"): grpcWeb.ClientReadableStream<$output_type$>;");
printer->Print("\n\n");
}
}
}
}
printer->Outdent();
printer->Print("}\n\n");
}
}
void PrintGrpcWebDtsFile(Printer* printer, const FileDescriptor* file) {
PrintES6Imports(printer, file);
PrintGrpcWebDtsClientClass(printer, file, "Client");
PrintGrpcWebDtsClientClass(printer, file, "PromiseClient");
}
void PrintProtoDtsEnum(Printer *printer, const EnumDescriptor *desc)
{
std::map<string, string> vars;
vars["enum_name"] = desc->name();
printer->Print(vars, "export enum $enum_name$ { \n");
printer->Indent();
for (int i = 0; i < desc->value_count(); i++)
{
vars["value_name"] = Uppercase(desc->value(i)->name());
vars["value_number"] = std::to_string(desc->value(i)->number());
printer->Print(vars, "$value_name$ = $value_number$,\n");
}
printer->Outdent();
printer->Print("}\n");
}
void PrintProtoDtsOneofCase(Printer *printer, const OneofDescriptor *desc)
{
std::map<string, string> vars;
vars["oneof_name"] = ToUpperCamel(ParseLowerUnderscore(desc->name()));
vars["oneof_name_upper"] = Uppercase(desc->name());
printer->Print(vars, "export enum $oneof_name$Case { \n");
printer->Indent();
printer->Print(vars, "$oneof_name_upper$_NOT_SET = 0,\n");
for (int i = 0; i < desc->field_count(); i++) {
const FieldDescriptor *field = desc->field(i);
vars["field_name"] = Uppercase(field->name());
vars["field_number"] = std::to_string(field->number());
printer->Print(vars, "$field_name$ = $field_number$,\n");
}
printer->Outdent();
printer->Print("}\n");
}
void PrintProtoDtsMessage(Printer *printer, const Descriptor *desc,
const FileDescriptor *file) {
string class_name = desc->name();
std::map<string, string> vars;
vars["class_name"] = class_name;
printer->Print(vars, "export class $class_name$ extends jspb.Message {\n");
printer->Indent();
for (int i = 0; i < desc->field_count(); i++) {
const FieldDescriptor* field = desc->field(i);
vars["js_field_name"] = JSFieldName(field);
vars["js_field_type"] = JSFieldType(field, file);
if (field->type() != FieldDescriptor::TYPE_MESSAGE ||
field->is_repeated()) {
printer->Print(vars,
"get$js_field_name$(): $js_field_type$;\n");
} else {
printer->Print(vars,
"get$js_field_name$(): $js_field_type$ | undefined;\n");
}
if (field->type() == FieldDescriptor::TYPE_BYTES && !field->is_repeated()) {
printer->Print(vars,
"get$js_field_name$_asU8(): Uint8Array;\n"
"get$js_field_name$_asB64(): string;\n");
}
if (!field->is_map() && (field->type() != FieldDescriptor::TYPE_MESSAGE ||
field->is_repeated())) {
printer->Print(vars,
"set$js_field_name$(value: $js_field_type$): "
"$class_name$;\n");
} else if (!field->is_map()) {
printer->Print(vars,
"set$js_field_name$(value?: $js_field_type$): "
"$class_name$;\n");
}
if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_repeated()
&& !field->is_map()) {
printer->Print(vars, "has$js_field_name$(): boolean;\n");
}
if (field->type() == FieldDescriptor::TYPE_MESSAGE ||
field->is_repeated() || field->is_map()) {
printer->Print(vars, "clear$js_field_name$(): $class_name$;\n");
}
if (field->is_repeated() && !field->is_map()) {
vars["js_field_name"] = JSElementName(field);
vars["js_field_type"] = JSElementType(field, file);
if (field->type() != FieldDescriptor::TYPE_MESSAGE) {
printer->Print(vars,
"add$js_field_name$(value: $js_field_type$, "
"index?: number): $class_name$;\n");
} else {
printer->Print(vars,
"add$js_field_name$(value?: $js_field_type$, "
"index?: number): $js_field_type$;\n");
}
}
printer->Print("\n");
}
for (int i = 0; i < desc->oneof_decl_count(); i++) {
const OneofDescriptor* oneof = desc->oneof_decl(i);
vars["js_oneof_name"] = ToUpperCamel(ParseLowerUnderscore(oneof->name()));
printer->Print(
vars,
"get$js_oneof_name$Case(): $class_name$.$js_oneof_name$Case;\n");
printer->Print("\n");
}
printer->Print(
vars,
"serializeBinary(): Uint8Array;\n"
"toObject(includeInstance?: boolean): "
"$class_name$.AsObject;\n"
"static toObject(includeInstance: boolean, msg: $class_name$): "
"$class_name$.AsObject;\n"
"static serializeBinaryToWriter(message: $class_name$, writer: "
"jspb.BinaryWriter): void;\n"
"static deserializeBinary(bytes: Uint8Array): $class_name$;\n"
"static deserializeBinaryFromReader(message: $class_name$, reader: "
"jspb.BinaryReader): $class_name$;\n");
printer->Outdent();
printer->Print("}\n\n");
printer->Print(vars, "export namespace $class_name$ {\n");
printer->Indent();
printer->Print("export type AsObject = {\n");
printer->Indent();
for (int i = 0; i < desc->field_count(); i++) {
const FieldDescriptor* field = desc->field(i);
string js_field_name = CamelCaseJSFieldName(field);
if (IsReserved(js_field_name)) {
js_field_name = "pb_" + js_field_name;
}
vars["js_field_name"] = js_field_name;
vars["js_field_type"] = AsObjectFieldType(field, file);
if (field->type() != FieldDescriptor::TYPE_MESSAGE ||
field->is_repeated()) {
printer->Print(vars, "$js_field_name$: $js_field_type$,\n");
} else {
printer->Print(vars, "$js_field_name$?: $js_field_type$,\n");
}
}
printer->Outdent();
printer->Print("}\n");
for (int i = 0; i < desc->nested_type_count(); i++) {
if (desc->nested_type(i)->options().map_entry()) {
continue;
}
printer->Print("\n");
PrintProtoDtsMessage(printer, desc->nested_type(i), file);
}
for (int i = 0; i < desc->enum_type_count(); i++) {
printer->Print("\n");
PrintProtoDtsEnum(printer, desc->enum_type(i));
}
for (int i = 0; i < desc->oneof_decl_count(); i++) {
printer->Print("\n");
PrintProtoDtsOneofCase(printer, desc->oneof_decl(i));
}
printer->Outdent();
printer->Print("}\n\n");
}
void PrintProtoDtsFile(Printer *printer, const FileDescriptor *file)
{
printer->Print("import * as jspb from 'google-protobuf'\n\n");
for (int i = 0; i < file->dependency_count(); i++) {
const string& name = file->dependency(i)->name();
// We need to give each cross-file import an alias.
printer->Print(
"import * as $alias$ from '$dep_filename$_pb';\n",
"alias", ModuleAlias(name),
"dep_filename", GetRootPath(file->name(), name) + StripProto(name));
}
printer->Print("\n\n");