forked from protobufjs/protobuf.js
/
protobuf-light.js
4275 lines (3838 loc) · 173 KB
/
protobuf-light.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
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 2013 Daniel Wirtz <dcode@dcode.io>
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
http://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.
*/
/**
* @license protobuf.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
* Released under the Apache License, Version 2.0
* see: https://github.com/dcodeIO/protobuf.js for details
*/
(function(global, factory) {
/* AMD */ if (typeof define === 'function' && define["amd"])
define(["bytebuffer"], factory);
/* CommonJS */ else if (typeof require === "function" && typeof module === "object" && module && module["exports"])
module["exports"] = factory(require("bytebuffer"), true);
/* Global */ else
(global["dcodeIO"] = global["dcodeIO"] || {})["ProtoBuf"] = factory(global["dcodeIO"]["ByteBuffer"]);
})(this, function(ByteBuffer, isCommonJS) {
"use strict";
/**
* The ProtoBuf namespace.
* @exports ProtoBuf
* @namespace
* @expose
*/
var ProtoBuf = {};
/**
* @type {!function(new: ByteBuffer, ...[*])}
* @expose
*/
ProtoBuf.ByteBuffer = ByteBuffer;
/**
* @type {?function(new: Long, ...[*])}
* @expose
*/
ProtoBuf.Long = ByteBuffer.Long || null;
/**
* ProtoBuf.js version.
* @type {string}
* @const
* @expose
*/
ProtoBuf.VERSION = "5.0.3";
/**
* Wire types.
* @type {Object.<string,number>}
* @const
* @expose
*/
ProtoBuf.WIRE_TYPES = {};
/**
* Varint wire type.
* @type {number}
* @expose
*/
ProtoBuf.WIRE_TYPES.VARINT = 0;
/**
* Fixed 64 bits wire type.
* @type {number}
* @const
* @expose
*/
ProtoBuf.WIRE_TYPES.BITS64 = 1;
/**
* Length delimited wire type.
* @type {number}
* @const
* @expose
*/
ProtoBuf.WIRE_TYPES.LDELIM = 2;
/**
* Start group wire type.
* @type {number}
* @const
* @expose
*/
ProtoBuf.WIRE_TYPES.STARTGROUP = 3;
/**
* End group wire type.
* @type {number}
* @const
* @expose
*/
ProtoBuf.WIRE_TYPES.ENDGROUP = 4;
/**
* Fixed 32 bits wire type.
* @type {number}
* @const
* @expose
*/
ProtoBuf.WIRE_TYPES.BITS32 = 5;
/**
* Packable wire types.
* @type {!Array.<number>}
* @const
* @expose
*/
ProtoBuf.PACKABLE_WIRE_TYPES = [
ProtoBuf.WIRE_TYPES.VARINT,
ProtoBuf.WIRE_TYPES.BITS64,
ProtoBuf.WIRE_TYPES.BITS32
];
/**
* Types.
* @dict
* @type {!Object.<string,{name: string, wireType: number, defaultValue: *}>}
* @const
* @expose
*/
ProtoBuf.TYPES = {
// According to the protobuf spec.
"int32": {
name: "int32",
wireType: ProtoBuf.WIRE_TYPES.VARINT,
defaultValue: 0
},
"uint32": {
name: "uint32",
wireType: ProtoBuf.WIRE_TYPES.VARINT,
defaultValue: 0
},
"sint32": {
name: "sint32",
wireType: ProtoBuf.WIRE_TYPES.VARINT,
defaultValue: 0
},
"int64": {
name: "int64",
wireType: ProtoBuf.WIRE_TYPES.VARINT,
defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
},
"uint64": {
name: "uint64",
wireType: ProtoBuf.WIRE_TYPES.VARINT,
defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
},
"sint64": {
name: "sint64",
wireType: ProtoBuf.WIRE_TYPES.VARINT,
defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
},
"bool": {
name: "bool",
wireType: ProtoBuf.WIRE_TYPES.VARINT,
defaultValue: false
},
"double": {
name: "double",
wireType: ProtoBuf.WIRE_TYPES.BITS64,
defaultValue: 0
},
"string": {
name: "string",
wireType: ProtoBuf.WIRE_TYPES.LDELIM,
defaultValue: ""
},
"bytes": {
name: "bytes",
wireType: ProtoBuf.WIRE_TYPES.LDELIM,
defaultValue: null // overridden in the code, must be a unique instance
},
"fixed32": {
name: "fixed32",
wireType: ProtoBuf.WIRE_TYPES.BITS32,
defaultValue: 0
},
"sfixed32": {
name: "sfixed32",
wireType: ProtoBuf.WIRE_TYPES.BITS32,
defaultValue: 0
},
"fixed64": {
name: "fixed64",
wireType: ProtoBuf.WIRE_TYPES.BITS64,
defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
},
"sfixed64": {
name: "sfixed64",
wireType: ProtoBuf.WIRE_TYPES.BITS64,
defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
},
"float": {
name: "float",
wireType: ProtoBuf.WIRE_TYPES.BITS32,
defaultValue: 0
},
"enum": {
name: "enum",
wireType: ProtoBuf.WIRE_TYPES.VARINT,
defaultValue: 0
},
"message": {
name: "message",
wireType: ProtoBuf.WIRE_TYPES.LDELIM,
defaultValue: null
},
"group": {
name: "group",
wireType: ProtoBuf.WIRE_TYPES.STARTGROUP,
defaultValue: null
}
};
/**
* Valid map key types.
* @type {!Array.<!Object.<string,{name: string, wireType: number, defaultValue: *}>>}
* @const
* @expose
*/
ProtoBuf.MAP_KEY_TYPES = [
ProtoBuf.TYPES["int32"],
ProtoBuf.TYPES["sint32"],
ProtoBuf.TYPES["sfixed32"],
ProtoBuf.TYPES["uint32"],
ProtoBuf.TYPES["fixed32"],
ProtoBuf.TYPES["int64"],
ProtoBuf.TYPES["sint64"],
ProtoBuf.TYPES["sfixed64"],
ProtoBuf.TYPES["uint64"],
ProtoBuf.TYPES["fixed64"],
ProtoBuf.TYPES["bool"],
ProtoBuf.TYPES["string"],
ProtoBuf.TYPES["bytes"]
];
/**
* Minimum field id.
* @type {number}
* @const
* @expose
*/
ProtoBuf.ID_MIN = 1;
/**
* Maximum field id.
* @type {number}
* @const
* @expose
*/
ProtoBuf.ID_MAX = 0x1FFFFFFF;
/**
* If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`.
* Must be set prior to parsing.
* @type {boolean}
* @expose
*/
ProtoBuf.convertFieldsToCamelCase = false;
/**
* By default, messages are populated with (setX, set_x) accessors for each field. This can be disabled by
* setting this to `false` prior to building messages.
* @type {boolean}
* @expose
*/
ProtoBuf.populateAccessors = true;
/**
* By default, messages are populated with default values if a field is not present on the wire. To disable
* this behavior, set this setting to `false`.
* @type {boolean}
* @expose
*/
ProtoBuf.populateDefaults = true;
/**
* @alias ProtoBuf.Util
* @expose
*/
ProtoBuf.Util = (function() {
"use strict";
/**
* ProtoBuf utilities.
* @exports ProtoBuf.Util
* @namespace
*/
var Util = {};
/**
* Flag if running in node or not.
* @type {boolean}
* @const
* @expose
*/
Util.IS_NODE = !!(
typeof process === 'object' && process+'' === '[object process]' && !process['browser']
);
/**
* Constructs a XMLHttpRequest object.
* @return {XMLHttpRequest}
* @throws {Error} If XMLHttpRequest is not supported
* @expose
*/
Util.XHR = function() {
// No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
var XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
/** @type {?XMLHttpRequest} */
var xhr = null;
for (var i=0;i<XMLHttpFactories.length;i++) {
try { xhr = XMLHttpFactories[i](); }
catch (e) { continue; }
break;
}
if (!xhr)
throw Error("XMLHttpRequest is not supported");
return xhr;
};
/**
* Fetches a resource.
* @param {string} path Resource path
* @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
* be fetched synchronously. If the request failed, contents will be null.
* @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
* @expose
*/
Util.fetch = function(path, callback) {
if (callback && typeof callback != 'function')
callback = null;
if (Util.IS_NODE) {
var fs = require("fs");
if (callback) {
fs.readFile(path, function(err, data) {
if (err)
callback(null);
else
callback(""+data);
});
} else
try {
return fs.readFileSync(path);
} catch (e) {
return null;
}
} else {
var xhr = Util.XHR();
xhr.open('GET', path, callback ? true : false);
// xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
xhr.setRequestHeader('Accept', 'text/plain');
if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
if (callback) {
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
callback(xhr.responseText);
else
callback(null);
};
if (xhr.readyState == 4)
return;
xhr.send(null);
} else {
xhr.send(null);
if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
return xhr.responseText;
return null;
}
}
};
/**
* Converts a string to camel case.
* @param {string} str
* @returns {string}
* @expose
*/
Util.toCamelCase = function(str) {
return str.replace(/_([a-zA-Z])/g, function ($0, $1) {
return $1.toUpperCase();
});
};
return Util;
})();
/**
* Language expressions.
* @type {!Object.<string,!RegExp>}
* @expose
*/
ProtoBuf.Lang = {
// Characters always ending a statement
DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g,
// Field rules
RULE: /^(?:required|optional|repeated|map)$/,
// Field types
TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,
// Names
NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/,
// Type definitions
TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/,
// Type references
TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,
// Fully qualified type references
FQTYPEREF: /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/,
// All numbers
NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,
// Decimal numbers
NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/,
// Hexadecimal numbers
NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/,
// Octal numbers
NUMBER_OCT: /^0[0-7]+$/,
// Floating point numbers
NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,
// Booleans
BOOL: /^(?:true|false)$/i,
// Id numbers
ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
// Negative id numbers (enum values)
NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
// Whitespaces
WHITESPACE: /\s/,
// All strings
STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,
// Double quoted strings
STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
// Single quoted strings
STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g
};
/**
* @alias ProtoBuf.Reflect
* @expose
*/
ProtoBuf.Reflect = (function(ProtoBuf) {
"use strict";
/**
* Reflection types.
* @exports ProtoBuf.Reflect
* @namespace
*/
var Reflect = {};
/**
* Constructs a Reflect base class.
* @exports ProtoBuf.Reflect.T
* @constructor
* @abstract
* @param {!ProtoBuf.Builder} builder Builder reference
* @param {?ProtoBuf.Reflect.T} parent Parent object
* @param {string} name Object name
*/
var T = function(builder, parent, name) {
/**
* Builder reference.
* @type {!ProtoBuf.Builder}
* @expose
*/
this.builder = builder;
/**
* Parent object.
* @type {?ProtoBuf.Reflect.T}
* @expose
*/
this.parent = parent;
/**
* Object name in namespace.
* @type {string}
* @expose
*/
this.name = name;
/**
* Fully qualified class name
* @type {string}
* @expose
*/
this.className;
};
/**
* @alias ProtoBuf.Reflect.T.prototype
* @inner
*/
var TPrototype = T.prototype;
/**
* Returns the fully qualified name of this object.
* @returns {string} Fully qualified name as of ".PATH.TO.THIS"
* @expose
*/
TPrototype.fqn = function() {
var name = this.name,
ptr = this;
do {
ptr = ptr.parent;
if (ptr == null)
break;
name = ptr.name+"."+name;
} while (true);
return name;
};
/**
* Returns a string representation of this Reflect object (its fully qualified name).
* @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
* @return String representation
* @expose
*/
TPrototype.toString = function(includeClass) {
return (includeClass ? this.className + " " : "") + this.fqn();
};
/**
* Builds this type.
* @throws {Error} If this type cannot be built directly
* @expose
*/
TPrototype.build = function() {
throw Error(this.toString(true)+" cannot be built directly");
};
/**
* @alias ProtoBuf.Reflect.T
* @expose
*/
Reflect.T = T;
/**
* Constructs a new Namespace.
* @exports ProtoBuf.Reflect.Namespace
* @param {!ProtoBuf.Builder} builder Builder reference
* @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent
* @param {string} name Namespace name
* @param {Object.<string,*>=} options Namespace options
* @param {string?} syntax The syntax level of this definition (e.g., proto3)
* @constructor
* @extends ProtoBuf.Reflect.T
*/
var Namespace = function(builder, parent, name, options, syntax) {
T.call(this, builder, parent, name);
/**
* @override
*/
this.className = "Namespace";
/**
* Children inside the namespace.
* @type {!Array.<ProtoBuf.Reflect.T>}
*/
this.children = [];
/**
* Options.
* @type {!Object.<string, *>}
*/
this.options = options || {};
/**
* Syntax level (e.g., proto2 or proto3).
* @type {!string}
*/
this.syntax = syntax || "proto2";
};
/**
* @alias ProtoBuf.Reflect.Namespace.prototype
* @inner
*/
var NamespacePrototype = Namespace.prototype = Object.create(T.prototype);
/**
* Returns an array of the namespace's children.
* @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
* @return {Array.<ProtoBuf.Reflect.T>}
* @expose
*/
NamespacePrototype.getChildren = function(type) {
type = type || null;
if (type == null)
return this.children.slice();
var children = [];
for (var i=0, k=this.children.length; i<k; ++i)
if (this.children[i] instanceof type)
children.push(this.children[i]);
return children;
};
/**
* Adds a child to the namespace.
* @param {ProtoBuf.Reflect.T} child Child
* @throws {Error} If the child cannot be added (duplicate)
* @expose
*/
NamespacePrototype.addChild = function(child) {
var other;
if (other = this.getChild(child.name)) {
// Try to revert camelcase transformation on collision
if (other instanceof Message.Field && other.name !== other.originalName && this.getChild(other.originalName) === null)
other.name = other.originalName; // Revert previous first (effectively keeps both originals)
else if (child instanceof Message.Field && child.name !== child.originalName && this.getChild(child.originalName) === null)
child.name = child.originalName;
else
throw Error("Duplicate name in namespace "+this.toString(true)+": "+child.name);
}
this.children.push(child);
};
/**
* Gets a child by its name or id.
* @param {string|number} nameOrId Child name or id
* @return {?ProtoBuf.Reflect.T} The child or null if not found
* @expose
*/
NamespacePrototype.getChild = function(nameOrId) {
var key = typeof nameOrId === 'number' ? 'id' : 'name';
for (var i=0, k=this.children.length; i<k; ++i)
if (this.children[i][key] === nameOrId)
return this.children[i];
return null;
};
/**
* Resolves a reflect object inside of this namespace.
* @param {string|!Array.<string>} qn Qualified name to resolve
* @param {boolean=} excludeNonNamespace Excludes non-namespace types, defaults to `false`
* @return {?ProtoBuf.Reflect.Namespace} The resolved type or null if not found
* @expose
*/
NamespacePrototype.resolve = function(qn, excludeNonNamespace) {
var part = typeof qn === 'string' ? qn.split(".") : qn,
ptr = this,
i = 0;
if (part[i] === "") { // Fully qualified name, e.g. ".My.Message'
while (ptr.parent !== null)
ptr = ptr.parent;
i++;
}
var child;
do {
do {
if (!(ptr instanceof Reflect.Namespace)) {
ptr = null;
break;
}
child = ptr.getChild(part[i]);
if (!child || !(child instanceof Reflect.T) || (excludeNonNamespace && !(child instanceof Reflect.Namespace))) {
ptr = null;
break;
}
ptr = child; i++;
} while (i < part.length);
if (ptr != null)
break; // Found
// Else search the parent
if (this.parent !== null)
return this.parent.resolve(qn, excludeNonNamespace);
} while (ptr != null);
return ptr;
};
/**
* Determines the shortest qualified name of the specified type, if any, relative to this namespace.
* @param {!ProtoBuf.Reflect.T} t Reflection type
* @returns {string} The shortest qualified name or, if there is none, the fqn
* @expose
*/
NamespacePrototype.qn = function(t) {
var part = [], ptr = t;
do {
part.unshift(ptr.name);
ptr = ptr.parent;
} while (ptr !== null);
for (var len=1; len <= part.length; len++) {
var qn = part.slice(part.length-len);
if (t === this.resolve(qn, t instanceof Reflect.Namespace))
return qn.join(".");
}
return t.fqn();
};
/**
* Builds the namespace and returns the runtime counterpart.
* @return {Object.<string,Function|Object>} Runtime namespace
* @expose
*/
NamespacePrototype.build = function() {
/** @dict */
var ns = {};
var children = this.children;
for (var i=0, k=children.length, child; i<k; ++i) {
child = children[i];
if (child instanceof Namespace)
ns[child.name] = child.build();
}
if (Object.defineProperty)
Object.defineProperty(ns, "$options", { "value": this.buildOpt() });
return ns;
};
/**
* Builds the namespace's '$options' property.
* @return {Object.<string,*>}
*/
NamespacePrototype.buildOpt = function() {
var opt = {},
keys = Object.keys(this.options);
for (var i=0, k=keys.length; i<k; ++i) {
var key = keys[i],
val = this.options[keys[i]];
// TODO: Options are not resolved, yet.
// if (val instanceof Namespace) {
// opt[key] = val.build();
// } else {
opt[key] = val;
// }
}
return opt;
};
/**
* Gets the value assigned to the option with the specified name.
* @param {string=} name Returns the option value if specified, otherwise all options are returned.
* @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
*/
NamespacePrototype.getOption = function(name) {
if (typeof name === 'undefined')
return this.options;
return typeof this.options[name] !== 'undefined' ? this.options[name] : null;
};
/**
* @alias ProtoBuf.Reflect.Namespace
* @expose
*/
Reflect.Namespace = Namespace;
/**
* Constructs a new Element implementation that checks and converts values for a
* particular field type, as appropriate.
*
* An Element represents a single value: either the value of a singular field,
* or a value contained in one entry of a repeated field or map field. This
* class does not implement these higher-level concepts; it only encapsulates
* the low-level typechecking and conversion.
*
* @exports ProtoBuf.Reflect.Element
* @param {{name: string, wireType: number}} type Resolved data type
* @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant
* (e.g. submessage field).
* @param {boolean} isMapKey Is this element a Map key? The value will be
* converted to string form if so.
* @param {string} syntax Syntax level of defining message type, e.g.,
* proto2 or proto3.
* @param {string} name Name of the field containing this element (for error
* messages)
* @constructor
*/
var Element = function(type, resolvedType, isMapKey, syntax, name) {
/**
* Element type, as a string (e.g., int32).
* @type {{name: string, wireType: number}}
*/
this.type = type;
/**
* Element type reference to submessage or enum definition, if needed.
* @type {ProtoBuf.Reflect.T|null}
*/
this.resolvedType = resolvedType;
/**
* Element is a map key.
* @type {boolean}
*/
this.isMapKey = isMapKey;
/**
* Syntax level of defining message type, e.g., proto2 or proto3.
* @type {string}
*/
this.syntax = syntax;
/**
* Name of the field containing this element (for error messages)
* @type {string}
*/
this.name = name;
if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0)
throw Error("Invalid map key type: " + type.name);
};
var ElementPrototype = Element.prototype;
/**
* Obtains a (new) default value for the specified type.
* @param type {string|{name: string, wireType: number}} Field type
* @returns {*} Default value
* @inner
*/
function mkDefault(type) {
if (typeof type === 'string')
type = ProtoBuf.TYPES[type];
if (typeof type.defaultValue === 'undefined')
throw Error("default value for type "+type.name+" is not supported");
if (type == ProtoBuf.TYPES["bytes"])
return new ByteBuffer(0);
return type.defaultValue;
}
/**
* Returns the default value for this field in proto3.
* @function
* @param type {string|{name: string, wireType: number}} the field type
* @returns {*} Default value
*/
Element.defaultFieldValue = mkDefault;
/**
* Makes a Long from a value.
* @param {{low: number, high: number, unsigned: boolean}|string|number} value Value
* @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for
* strings and numbers
* @returns {!Long}
* @throws {Error} If the value cannot be converted to a Long
* @inner
*/
function mkLong(value, unsigned) {
if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean'
&& value.low === value.low && value.high === value.high)
return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned);
if (typeof value === 'string')
return ProtoBuf.Long.fromString(value, unsigned || false, 10);
if (typeof value === 'number')
return ProtoBuf.Long.fromNumber(value, unsigned || false);
throw Error("not convertible to Long");
}
ElementPrototype.toString = function() {
return (this.name || '') + (this.isMapKey ? 'map' : 'value') + ' element';
}
/**
* Checks if the given value can be set for an element of this type (singular
* field or one element of a repeated field or map).
* @param {*} value Value to check
* @return {*} Verified, maybe adjusted, value
* @throws {Error} If the value cannot be verified for this element slot
* @expose
*/
ElementPrototype.verifyValue = function(value) {
var self = this;
function fail(val, msg) {
throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
}
switch (this.type) {
// Signed 32bit
case ProtoBuf.TYPES["int32"]:
case ProtoBuf.TYPES["sint32"]:
case ProtoBuf.TYPES["sfixed32"]:
// Account for !NaN: value === value
if (typeof value !== 'number' || (value === value && value % 1 !== 0))
fail(typeof value, "not an integer");
return value > 4294967295 ? value | 0 : value;
// Unsigned 32bit
case ProtoBuf.TYPES["uint32"]:
case ProtoBuf.TYPES["fixed32"]:
if (typeof value !== 'number' || (value === value && value % 1 !== 0))
fail(typeof value, "not an integer");
return value < 0 ? value >>> 0 : value;
// Signed 64bit
case ProtoBuf.TYPES["int64"]:
case ProtoBuf.TYPES["sint64"]:
case ProtoBuf.TYPES["sfixed64"]: {
if (ProtoBuf.Long)
try {
return mkLong(value, false);
} catch (e) {
fail(typeof value, e.message);
}
else
fail(typeof value, "requires Long.js");
}
// Unsigned 64bit
case ProtoBuf.TYPES["uint64"]:
case ProtoBuf.TYPES["fixed64"]: {
if (ProtoBuf.Long)
try {
return mkLong(value, true);
} catch (e) {
fail(typeof value, e.message);
}
else
fail(typeof value, "requires Long.js");
}
// Bool
case ProtoBuf.TYPES["bool"]:
if (typeof value !== 'boolean')
fail(typeof value, "not a boolean");
return value;
// Float
case ProtoBuf.TYPES["float"]:
case ProtoBuf.TYPES["double"]:
if (typeof value !== 'number')
fail(typeof value, "not a number");
return value;
// Length-delimited string
case ProtoBuf.TYPES["string"]:
if (typeof value !== 'string' && !(value && value instanceof String))
fail(typeof value, "not a string");
return ""+value; // Convert String object to string
// Length-delimited bytes
case ProtoBuf.TYPES["bytes"]:
if (ByteBuffer.isByteBuffer(value))
return value;
return ByteBuffer.wrap(value, "base64");
// Constant enum value
case ProtoBuf.TYPES["enum"]: {
var values = this.resolvedType.getChildren(ProtoBuf.Reflect.Enum.Value);
for (i=0; i<values.length; i++)
if (values[i].name == value)
return values[i].id;
else if (values[i].id == value)
return values[i].id;
if (this.syntax === 'proto3') {
// proto3: just make sure it's an integer.
if (typeof value !== 'number' || (value === value && value % 1 !== 0))
fail(typeof value, "not an integer");
if (value > 4294967295 || value < 0)
fail(typeof value, "not in range for uint32")
return value;
} else {
// proto2 requires enum values to be valid.
fail(value, "not a valid enum value");
}
}
// Embedded message
case ProtoBuf.TYPES["group"]:
case ProtoBuf.TYPES["message"]: {
if (!value || typeof value !== 'object')