-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
static.js
848 lines (780 loc) · 32.2 KB
/
static.js
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
"use strict";
module.exports = static_target;
var UglifyJS = require("uglify-js"),
espree = require("espree"),
escodegen = require("escodegen"),
estraverse = require("estraverse"),
protobuf = require("protobufjs");
var Type = protobuf.Type,
Service = protobuf.Service,
Enum = protobuf.Enum,
Namespace = protobuf.Namespace,
util = protobuf.util;
var out = [];
var indent = 0;
var config = {};
static_target.description = "Static code without reflection (non-functional on its own)";
function static_target(root, options, callback) {
config = options;
try {
var aliases = [];
if (config.decode)
aliases.push("Reader");
if (config.encode)
aliases.push("Writer");
aliases.push("util");
if (aliases.length) {
if (config.comments)
push("// Common aliases");
push((config.es6 ? "const " : "var ") + aliases.map(function(name) { return "$" + name + " = $protobuf." + name; }).join(", ") + ";");
push("");
}
if (config.comments) {
if (root.comment) {
pushComment("@fileoverview " + root.comment);
push("");
}
push("// Exported root namespace");
}
var rootProp = util.safeProp(config.root || "default");
push((config.es6 ? "const" : "var") + " $root = $protobuf.roots" + rootProp + " || ($protobuf.roots" + rootProp + " = {});");
buildNamespace(null, root);
return callback(null, out.join("\n"));
} catch (err) {
return callback(err);
} finally {
out = [];
indent = 0;
config = {};
}
}
function push(line) {
if (line === "")
return out.push("");
var ind = "";
for (var i = 0; i < indent; ++i)
ind += " ";
return out.push(ind + line);
}
function pushComment(lines) {
if (!config.comments)
return;
var split = [];
for (var i = 0; i < lines.length; ++i)
if (lines[i] != null && lines[i].substring(0, 8) !== "@exclude")
Array.prototype.push.apply(split, lines[i].split(/\r?\n/g));
push("/**");
split.forEach(function(line) {
if (line === null)
return;
push(" * " + line.replace(/\*\//g, "* /"));
});
push(" */");
}
function exportName(object, asInterface) {
if (asInterface) {
if (object.__interfaceName)
return object.__interfaceName;
} else if (object.__exportName)
return object.__exportName;
var parts = object.fullName.substring(1).split("."),
i = 0;
while (i < parts.length)
parts[i] = escapeName(parts[i++]);
if (asInterface)
parts[i - 1] = "I" + parts[i - 1];
return object[asInterface ? "__interfaceName" : "__exportName"] = parts.join(".");
}
function escapeName(name) {
if (!name)
return "$root";
return util.isReserved(name) ? name + "_" : name;
}
function aOrAn(name) {
return ((/^[hH](?:ou|on|ei)/.test(name) || /^[aeiouAEIOU][a-z]/.test(name)) && !/^us/i.test(name)
? "an "
: "a ") + name;
}
function buildNamespace(ref, ns) {
if (!ns)
return;
if (ns instanceof Service && !config.service)
return;
if (ns.name !== "") {
push("");
if (!ref && config.es6)
push("export const " + escapeName(ns.name) + " = " + escapeName(ref) + "." + escapeName(ns.name) + " = (() => {");
else
push(escapeName(ref) + "." + escapeName(ns.name) + " = (function() {");
++indent;
}
if (ns instanceof Type) {
buildType(undefined, ns);
} else if (ns instanceof Service)
buildService(undefined, ns);
else if (ns.name !== "") {
push("");
pushComment([
ns.comment || "Namespace " + ns.name + ".",
ns.parent instanceof protobuf.Root ? "@exports " + escapeName(ns.name) : "@memberof " + exportName(ns.parent),
"@namespace"
]);
push((config.es6 ? "const" : "var") + " " + escapeName(ns.name) + " = {};");
}
ns.nestedArray.forEach(function(nested) {
if (nested instanceof Enum)
buildEnum(ns.name, nested);
else if (nested instanceof Namespace)
buildNamespace(ns.name, nested);
});
if (ns.name !== "") {
push("");
push("return " + escapeName(ns.name) + ";");
--indent;
push("})();");
}
}
var reduceableBlockStatements = {
IfStatement: true,
ForStatement: true,
WhileStatement: true
};
var shortVars = {
"r": "reader",
"w": "writer",
"m": "message",
"t": "tag",
"l": "length",
"c": "end", "c2": "end2",
"k": "key",
"ks": "keys", "ks2": "keys2",
"e": "error",
"f": "impl",
"o": "options",
"d": "object",
"n": "long",
"p": "properties"
};
function beautifyCode(code) {
// Add semicolons
code = UglifyJS.minify(code, {
compress: false,
mangle: false,
output: { beautify: true }
}).code;
// Properly beautify
var ast = espree.parse(code);
estraverse.replace(ast, {
enter: function(node, parent) {
// rename short vars
if (node.type === "Identifier" && (parent.property !== node || parent.computed) && shortVars[node.name])
return {
"type": "Identifier",
"name": shortVars[node.name]
};
// replace var with let if es6
if (config.es6 && node.type === "VariableDeclaration" && node.kind === "var") {
node.kind = "let";
return undefined;
}
// remove braces around block statements with a single child
if (node.type === "BlockStatement" && reduceableBlockStatements[parent.type] && node.body.length === 1)
return node.body[0];
return undefined;
}
});
code = escodegen.generate(ast, {
format: {
newline: "\n",
quotes: "double"
}
});
// Add id, wireType comments
if (config.comments)
code = code.replace(/\.uint32\((\d+)\)/g, function($0, $1) {
var id = $1 >>> 3,
wireType = $1 & 7;
return ".uint32(/* id " + id + ", wireType " + wireType + " =*/" + $1 + ")";
});
return code;
}
var renameVars = {
"Writer": "$Writer",
"Reader": "$Reader",
"util": "$util"
};
function buildFunction(type, functionName, gen, scope) {
var code = gen.toString(functionName)
.replace(/((?!\.)types\[\d+])(\.values)/g, "$1"); // enums: use types[N] instead of reflected types[N].values
var ast = espree.parse(code);
/* eslint-disable no-extra-parens */
estraverse.replace(ast, {
enter: function(node, parent) {
// rename vars
if (
node.type === "Identifier" && renameVars[node.name]
&& (
(parent.type === "MemberExpression" && parent.object === node)
|| (parent.type === "BinaryExpression" && parent.right === node)
)
)
return {
"type": "Identifier",
"name": renameVars[node.name]
};
// replace this.ctor with the actual ctor
if (
node.type === "MemberExpression"
&& node.object.type === "ThisExpression"
&& node.property.type === "Identifier" && node.property.name === "ctor"
)
return {
"type": "Identifier",
"name": "$root" + type.fullName
};
// replace types[N] with the field's actual type
if (
node.type === "MemberExpression"
&& node.object.type === "Identifier" && node.object.name === "types"
&& node.property.type === "Literal"
)
return {
"type": "Identifier",
"name": "$root" + type.fieldsArray[node.property.value].resolvedType.fullName
};
return undefined;
}
});
/* eslint-enable no-extra-parens */
code = escodegen.generate(ast, {
format: {
newline: "\n",
quotes: "double"
}
});
if (config.beautify)
code = beautifyCode(code);
code = code.replace(/ {4}/g, "\t");
var hasScope = scope && Object.keys(scope).length,
isCtor = functionName === type.name;
if (hasScope) // remove unused scope vars
Object.keys(scope).forEach(function(key) {
if (!new RegExp("\\b(" + key + ")\\b", "g").test(code))
delete scope[key];
});
var lines = code.split(/\n/g);
if (isCtor) // constructor
push(lines[0]);
else if (hasScope) // enclose in an iife
push(escapeName(type.name) + "." + escapeName(functionName) + " = (function(" + Object.keys(scope).map(escapeName).join(", ") + ") { return " + lines[0]);
else
push(escapeName(type.name) + "." + escapeName(functionName) + " = " + lines[0]);
lines.slice(1, lines.length - 1).forEach(function(line) {
var prev = indent;
var i = 0;
while (line.charAt(i++) === "\t")
++indent;
push(line.trim());
indent = prev;
});
if (isCtor)
push("}");
else if (hasScope)
push("};})(" + Object.keys(scope).map(function(key) { return scope[key]; }).join(", ") + ");");
else
push("};");
}
function toJsType(field, parentIsInterface = false) {
var type;
// With null semantics, interfaces are composed from interfaces and messages from messages
// Without null semantics, child types depend on the --force-message flag
var asInterface = config["null-semantics"]
? parentIsInterface && !(field.resolvedType instanceof protobuf.Enum)
: !(field.resolvedType instanceof protobuf.Enum || config.forceMessage);
switch (field.type) {
case "double":
case "float":
case "int32":
case "uint32":
case "sint32":
case "fixed32":
case "sfixed32":
type = "number";
break;
case "int64":
case "uint64":
case "sint64":
case "fixed64":
case "sfixed64":
type = config.forceLong ? "Long" : config.forceNumber ? "number" : "number|Long";
break;
case "bool":
type = "boolean";
break;
case "string":
type = "string";
break;
case "bytes":
type = "Uint8Array";
break;
default:
if (field.resolve().resolvedType) {
type = exportName(field.resolvedType, asInterface);
}
else {
type = "*"; // should not happen
}
break;
}
if (field.map)
return "Object.<string," + type + ">";
if (field.repeated)
return "Array.<" + type + ">";
return type;
}
function syntaxForType(type) {
var syntax = null;
var namespace = type;
while (syntax === null && namespace !== null) {
if (namespace.options != null && "syntax" in namespace.options) {
syntax = namespace.options["syntax"];
}
else {
namespace = namespace.parent;
}
}
return syntax !== null ? syntax : "proto2";
}
function isExplicitPresence(field, syntax) {
// In proto3, optional fields are explicit
if (syntax === "proto3") {
return field.options != null && field.options["proto3_optional"] === true;
}
// In proto2, fields are explicitly optional if they are not part of a map, array or oneOf group
if (syntax === "proto2") {
return field.optional && !(field.partOf || field.repeated || field.map);
}
throw new Error("Unknown proto syntax: [" + syntax + "]");
}
function isImplicitPresence(field, syntax) {
// In proto3, everything not marked optional has implicit presence (including maps and repeated fields)
if (syntax === "proto3") {
return field.options == null || field.options["proto3_optional"] !== true;
}
// In proto2, nothing has implicit presence
if (syntax === "proto2") {
return false;
}
throw new Error("Unknown proto syntax: [" + syntax + "]");
}
function isOptionalOneOf(oneof, syntax) {
if (syntax === "proto2") {
return false;
}
if (oneof.fieldsArray == null || oneof.fieldsArray.length !== 1) {
return false;
}
var field = oneof.fieldsArray[0];
return field.options != null && field.options["proto3_optional"] === true;
}
function buildType(ref, type) {
var syntax = syntaxForType(type);
if (config.comments) {
var typeDef = [
"Properties of " + aOrAn(type.name) + ".",
type.parent instanceof protobuf.Root ? "@exports " + escapeName("I" + type.name) : "@memberof " + exportName(type.parent),
"@interface " + escapeName("I" + type.name)
];
type.fieldsArray.forEach(function(field) {
var prop = util.safeProp(field.name); // either .name or ["name"]
prop = prop.substring(1, prop.charAt(0) === "[" ? prop.length - 1 : prop.length);
var jsType = toJsType(field, /* parentIsInterface = */ true);
var nullable = false;
if (config["null-semantics"]) {
// With semantic nulls, only explicit optional fields and one-of members can be set to null
// Implicit fields (proto3), maps and lists can be omitted, but if specified must be non-null
// Implicit fields will take their default value when the message is constructed
if (isExplicitPresence(field, syntax) || field.partOf) {
jsType = jsType + "|null|undefined";
nullable = true;
}
else if (isImplicitPresence(field, syntax) || field.repeated || field.map) {
jsType = jsType + "|undefined";
nullable = true;
}
}
else {
// Without semantic nulls, everything is optional in proto3
// Do not allow |undefined to keep backwards compatibility
if (field.optional) {
jsType = jsType + "|null";
nullable = true;
}
}
typeDef.push("@property {" + jsType + "} " + (nullable ? "[" + prop + "]" : prop) + " " + (field.comment || type.name + " " + field.name));
});
push("");
pushComment(typeDef);
}
// constructor
push("");
pushComment([
"Constructs a new " + type.name + ".",
type.parent instanceof protobuf.Root ? "@exports " + escapeName(type.name) : "@memberof " + exportName(type.parent),
"@classdesc " + (type.comment || "Represents " + aOrAn(type.name) + "."),
config.comments ? "@implements " + escapeName("I" + type.name) : null,
"@constructor",
"@param {" + exportName(type, true) + "=} [" + (config.beautify ? "properties" : "p") + "] Properties to set"
]);
buildFunction(type, type.name, Type.generateConstructor(type));
// default values
var firstField = true;
type.fieldsArray.forEach(function(field) {
field.resolve();
var prop = util.safeProp(field.name);
if (config.comments) {
push("");
var jsType = toJsType(field, /* parentIsInterface = */ false);
if (config["null-semantics"]) {
// With semantic nulls, fields are nullable if they are explicitly optional or part of a one-of
// Maps, repeated values and fields with implicit defaults are never null after construction
// Members are never undefined, at a minimum they are initialized to null
if (isExplicitPresence(field, syntax) || field.partOf) {
jsType = jsType + "|null";
}
}
else {
// Without semantic nulls, everything is optional in proto3
// Keep |undefined for backwards compatibility
if (field.optional && !field.map && !field.repeated && (field.resolvedType instanceof Type || config["null-defaults"]) || field.partOf) {
jsType = jsType + "|null|undefined";
}
}
pushComment([
field.comment || type.name + " " + field.name + ".",
"@member {" + jsType + "} " + field.name,
"@memberof " + exportName(type),
"@instance"
]);
} else if (firstField) {
push("");
firstField = false;
}
// With semantic nulls, only explict optional fields and one-of members are null by default
// Otherwise use field.optional, which doesn't consider proto3, maps, repeated fields etc.
var nullDefault = config["null-semantics"]
? isExplicitPresence(field, syntax)
: field.optional && config["null-defaults"];
if (field.repeated)
push(escapeName(type.name) + ".prototype" + prop + " = $util.emptyArray;"); // overwritten in constructor
else if (field.map)
push(escapeName(type.name) + ".prototype" + prop + " = $util.emptyObject;"); // overwritten in constructor
else if (field.partOf || nullDefault)
push(escapeName(type.name) + ".prototype" + prop + " = null;"); // do not set default value for oneof members
else if (field.long)
push(escapeName(type.name) + ".prototype" + prop + " = $util.Long ? $util.Long.fromBits("
+ JSON.stringify(field.typeDefault.low) + ","
+ JSON.stringify(field.typeDefault.high) + ","
+ JSON.stringify(field.typeDefault.unsigned)
+ ") : " + field.typeDefault.toNumber(field.type.charAt(0) === "u") + ";");
else if (field.bytes) {
push(escapeName(type.name) + ".prototype" + prop + " = $util.newBuffer(" + JSON.stringify(Array.prototype.slice.call(field.typeDefault)) + ");");
} else
push(escapeName(type.name) + ".prototype" + prop + " = " + JSON.stringify(field.typeDefault) + ";");
});
// virtual oneof fields
var firstOneOf = true;
type.oneofsArray.forEach(function(oneof) {
if (firstOneOf) {
firstOneOf = false;
push("");
if (config.comments)
push("// OneOf field names bound to virtual getters and setters");
push((config.es6 ? "let" : "var") + " $oneOfFields;");
}
oneof.resolve();
push("");
if (isOptionalOneOf(oneof, syntax)) {
push("// Virtual OneOf for proto3 optional field");
}
else {
pushComment([
oneof.comment || type.name + " " + oneof.name + ".",
"@member {" + oneof.oneof.map(JSON.stringify).join("|") + "|undefined} " + escapeName(oneof.name),
"@memberof " + exportName(type),
"@instance"
]);
}
push("Object.defineProperty(" + escapeName(type.name) + ".prototype, " + JSON.stringify(oneof.name) +", {");
++indent;
push("get: $util.oneOfGetter($oneOfFields = [" + oneof.oneof.map(JSON.stringify).join(", ") + "]),");
push("set: $util.oneOfSetter($oneOfFields)");
--indent;
push("});");
});
if (config.create) {
push("");
pushComment([
"Creates a new " + type.name + " instance using the specified properties.",
"@function create",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type, true) + "=} [properties] Properties to set",
"@returns {" + exportName(type) + "} " + type.name + " instance"
]);
push(escapeName(type.name) + ".create = function create(properties) {");
++indent;
push("return new " + escapeName(type.name) + "(properties);");
--indent;
push("};");
}
if (config.encode) {
push("");
pushComment([
"Encodes the specified " + type.name + " message. Does not implicitly {@link " + exportName(type) + ".verify|verify} messages.",
"@function encode",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type, !config.forceMessage) + "} " + (config.beautify ? "message" : "m") + " " + type.name + " message or plain object to encode",
"@param {$protobuf.Writer} [" + (config.beautify ? "writer" : "w") + "] Writer to encode to",
"@returns {$protobuf.Writer} Writer"
]);
buildFunction(type, "encode", protobuf.encoder(type));
if (config.delimited) {
push("");
pushComment([
"Encodes the specified " + type.name + " message, length delimited. Does not implicitly {@link " + exportName(type) + ".verify|verify} messages.",
"@function encodeDelimited",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type, !config.forceMessage) + "} message " + type.name + " message or plain object to encode",
"@param {$protobuf.Writer} [writer] Writer to encode to",
"@returns {$protobuf.Writer} Writer"
]);
push(escapeName(type.name) + ".encodeDelimited = function encodeDelimited(message, writer) {");
++indent;
push("return this.encode(message, writer).ldelim();");
--indent;
push("};");
}
}
if (config.decode) {
push("");
pushComment([
"Decodes " + aOrAn(type.name) + " message from the specified reader or buffer.",
"@function decode",
"@memberof " + exportName(type),
"@static",
"@param {$protobuf.Reader|Uint8Array} " + (config.beautify ? "reader" : "r") + " Reader or buffer to decode from",
"@param {number} [" + (config.beautify ? "length" : "l") + "] Message length if known beforehand",
"@returns {" + exportName(type) + "} " + type.name,
"@throws {Error} If the payload is not a reader or valid buffer",
"@throws {$protobuf.util.ProtocolError} If required fields are missing"
]);
buildFunction(type, "decode", protobuf.decoder(type));
if (config.delimited) {
push("");
pushComment([
"Decodes " + aOrAn(type.name) + " message from the specified reader or buffer, length delimited.",
"@function decodeDelimited",
"@memberof " + exportName(type),
"@static",
"@param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from",
"@returns {" + exportName(type) + "} " + type.name,
"@throws {Error} If the payload is not a reader or valid buffer",
"@throws {$protobuf.util.ProtocolError} If required fields are missing"
]);
push(escapeName(type.name) + ".decodeDelimited = function decodeDelimited(reader) {");
++indent;
push("if (!(reader instanceof $Reader))");
++indent;
push("reader = new $Reader(reader);");
--indent;
push("return this.decode(reader, reader.uint32());");
--indent;
push("};");
}
}
if (config.verify) {
push("");
pushComment([
"Verifies " + aOrAn(type.name) + " message.",
"@function verify",
"@memberof " + exportName(type),
"@static",
"@param {Object.<string,*>} " + (config.beautify ? "message" : "m") + " Plain object to verify",
"@returns {string|null} `null` if valid, otherwise the reason why it is not"
]);
buildFunction(type, "verify", protobuf.verifier(type));
}
if (config.convert) {
push("");
pushComment([
"Creates " + aOrAn(type.name) + " message from a plain object. Also converts values to their respective internal types.",
"@function fromObject",
"@memberof " + exportName(type),
"@static",
"@param {Object.<string,*>} " + (config.beautify ? "object" : "d") + " Plain object",
"@returns {" + exportName(type) + "} " + type.name
]);
buildFunction(type, "fromObject", protobuf.converter.fromObject(type));
push("");
pushComment([
"Creates a plain object from " + aOrAn(type.name) + " message. Also converts values to other types if specified.",
"@function toObject",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type) + "} " + (config.beautify ? "message" : "m") + " " + type.name,
"@param {$protobuf.IConversionOptions} [" + (config.beautify ? "options" : "o") + "] Conversion options",
"@returns {Object.<string,*>} Plain object"
]);
buildFunction(type, "toObject", protobuf.converter.toObject(type));
push("");
pushComment([
"Converts this " + type.name + " to JSON.",
"@function toJSON",
"@memberof " + exportName(type),
"@instance",
"@returns {Object.<string,*>} JSON object"
]);
push(escapeName(type.name) + ".prototype.toJSON = function toJSON() {");
++indent;
push("return this.constructor.toObject(this, $protobuf.util.toJSONOptions);");
--indent;
push("};");
}
if (config.typeurl) {
push("");
pushComment([
"Gets the default type url for " + type.name,
"@function getTypeUrl",
"@memberof " + exportName(type),
"@static",
"@param {string} [typeUrlPrefix] your custom typeUrlPrefix(default \"type.googleapis.com\")",
"@returns {string} The default type url"
]);
push(escapeName(type.name) + ".getTypeUrl = function getTypeUrl(typeUrlPrefix) {");
++indent;
push("if (typeUrlPrefix === undefined) {");
++indent;
push("typeUrlPrefix = \"type.googleapis.com\";");
--indent;
push("}");
push("return typeUrlPrefix + \"/" + exportName(type) + "\";");
--indent;
push("};");
}
}
function buildService(ref, service) {
push("");
pushComment([
"Constructs a new " + service.name + " service.",
service.parent instanceof protobuf.Root ? "@exports " + escapeName(service.name) : "@memberof " + exportName(service.parent),
"@classdesc " + (service.comment || "Represents " + aOrAn(service.name)),
"@extends $protobuf.rpc.Service",
"@constructor",
"@param {$protobuf.RPCImpl} rpcImpl RPC implementation",
"@param {boolean} [requestDelimited=false] Whether requests are length-delimited",
"@param {boolean} [responseDelimited=false] Whether responses are length-delimited"
]);
push("function " + escapeName(service.name) + "(rpcImpl, requestDelimited, responseDelimited) {");
++indent;
push("$protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited);");
--indent;
push("}");
push("");
push("(" + escapeName(service.name) + ".prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = " + escapeName(service.name) + ";");
if (config.create) {
push("");
pushComment([
"Creates new " + service.name + " service using the specified rpc implementation.",
"@function create",
"@memberof " + exportName(service),
"@static",
"@param {$protobuf.RPCImpl} rpcImpl RPC implementation",
"@param {boolean} [requestDelimited=false] Whether requests are length-delimited",
"@param {boolean} [responseDelimited=false] Whether responses are length-delimited",
"@returns {" + escapeName(service.name) + "} RPC service. Useful where requests and/or responses are streamed."
]);
push(escapeName(service.name) + ".create = function create(rpcImpl, requestDelimited, responseDelimited) {");
++indent;
push("return new this(rpcImpl, requestDelimited, responseDelimited);");
--indent;
push("};");
}
service.methodsArray.forEach(function(method) {
method.resolve();
var lcName = protobuf.util.lcFirst(method.name),
cbName = escapeName(method.name + "Callback");
push("");
pushComment([
"Callback as used by {@link " + exportName(service) + "#" + escapeName(lcName) + "}.",
// This is a more specialized version of protobuf.rpc.ServiceCallback
"@memberof " + exportName(service),
"@typedef " + cbName,
"@type {function}",
"@param {Error|null} error Error, if any",
"@param {" + exportName(method.resolvedResponseType) + "} [response] " + method.resolvedResponseType.name
]);
push("");
pushComment([
method.comment || "Calls " + method.name + ".",
"@function " + lcName,
"@memberof " + exportName(service),
"@instance",
"@param {" + exportName(method.resolvedRequestType, !config.forceMessage) + "} request " + method.resolvedRequestType.name + " message or plain object",
"@param {" + exportName(service) + "." + cbName + "} callback Node-style callback called with the error, if any, and " + method.resolvedResponseType.name,
"@returns {undefined}",
"@variation 1"
]);
push("Object.defineProperty(" + escapeName(service.name) + ".prototype" + util.safeProp(lcName) + " = function " + escapeName(lcName) + "(request, callback) {");
++indent;
push("return this.rpcCall(" + escapeName(lcName) + ", $root." + exportName(method.resolvedRequestType) + ", $root." + exportName(method.resolvedResponseType) + ", request, callback);");
--indent;
push("}, \"name\", { value: " + JSON.stringify(method.name) + " });");
if (config.comments)
push("");
pushComment([
method.comment || "Calls " + method.name + ".",
"@function " + lcName,
"@memberof " + exportName(service),
"@instance",
"@param {" + exportName(method.resolvedRequestType, !config.forceMessage) + "} request " + method.resolvedRequestType.name + " message or plain object",
"@returns {Promise<" + exportName(method.resolvedResponseType) + ">} Promise",
"@variation 2"
]);
});
}
function buildEnum(ref, enm) {
push("");
var comment = [
enm.comment || enm.name + " enum.",
enm.parent instanceof protobuf.Root ? "@exports " + escapeName(enm.name) : "@name " + exportName(enm),
config.forceEnumString ? "@enum {string}" : "@enum {number}",
];
Object.keys(enm.values).forEach(function(key) {
var val = config.forceEnumString ? key : enm.values[key];
comment.push((config.forceEnumString ? "@property {string} " : "@property {number} ") + key + "=" + val + " " + (enm.comments[key] || key + " value"));
});
pushComment(comment);
if (!ref && config.es6)
push("export const " + escapeName(enm.name) + " = " + escapeName(ref) + "." + escapeName(enm.name) + " = (() => {");
else
push(escapeName(ref) + "." + escapeName(enm.name) + " = (function() {");
++indent;
push((config.es6 ? "const" : "var") + " valuesById = {}, values = Object.create(valuesById);");
var aliased = [];
Object.keys(enm.values).forEach(function(key) {
var valueId = enm.values[key];
var val = config.forceEnumString ? JSON.stringify(key) : valueId;
if (aliased.indexOf(valueId) > -1)
push("values[" + JSON.stringify(key) + "] = " + val + ";");
else {
push("values[valuesById[" + valueId + "] = " + JSON.stringify(key) + "] = " + val + ";");
aliased.push(valueId);
}
});
push("return values;");
--indent;
push("})();");
}