protobuf-light.js 173 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275
  1. /*
  2. Copyright 2013 Daniel Wirtz <dcode@dcode.io>
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. /**
  14. * @license protobuf.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
  15. * Released under the Apache License, Version 2.0
  16. * see: https://github.com/dcodeIO/protobuf.js for details
  17. */
  18. (function(global, factory) {
  19. /* AMD */ if (typeof define === 'function' && define["amd"])
  20. define(["bytebuffer"], factory);
  21. /* CommonJS */ else if (typeof require === "function" && typeof module === "object" && module && module["exports"])
  22. module["exports"] = factory(require("bytebuffer"), true);
  23. /* Global */ else
  24. (global["dcodeIO"] = global["dcodeIO"] || {})["ProtoBuf"] = factory(global["dcodeIO"]["ByteBuffer"]);
  25. })(this, function(ByteBuffer, isCommonJS) {
  26. "use strict";
  27. /**
  28. * The ProtoBuf namespace.
  29. * @exports ProtoBuf
  30. * @namespace
  31. * @expose
  32. */
  33. var ProtoBuf = {};
  34. /**
  35. * @type {!function(new: ByteBuffer, ...[*])}
  36. * @expose
  37. */
  38. ProtoBuf.ByteBuffer = ByteBuffer;
  39. /**
  40. * @type {?function(new: Long, ...[*])}
  41. * @expose
  42. */
  43. ProtoBuf.Long = ByteBuffer.Long || null;
  44. /**
  45. * ProtoBuf.js version.
  46. * @type {string}
  47. * @const
  48. * @expose
  49. */
  50. ProtoBuf.VERSION = "5.0.3";
  51. /**
  52. * Wire types.
  53. * @type {Object.<string,number>}
  54. * @const
  55. * @expose
  56. */
  57. ProtoBuf.WIRE_TYPES = {};
  58. /**
  59. * Varint wire type.
  60. * @type {number}
  61. * @expose
  62. */
  63. ProtoBuf.WIRE_TYPES.VARINT = 0;
  64. /**
  65. * Fixed 64 bits wire type.
  66. * @type {number}
  67. * @const
  68. * @expose
  69. */
  70. ProtoBuf.WIRE_TYPES.BITS64 = 1;
  71. /**
  72. * Length delimited wire type.
  73. * @type {number}
  74. * @const
  75. * @expose
  76. */
  77. ProtoBuf.WIRE_TYPES.LDELIM = 2;
  78. /**
  79. * Start group wire type.
  80. * @type {number}
  81. * @const
  82. * @expose
  83. */
  84. ProtoBuf.WIRE_TYPES.STARTGROUP = 3;
  85. /**
  86. * End group wire type.
  87. * @type {number}
  88. * @const
  89. * @expose
  90. */
  91. ProtoBuf.WIRE_TYPES.ENDGROUP = 4;
  92. /**
  93. * Fixed 32 bits wire type.
  94. * @type {number}
  95. * @const
  96. * @expose
  97. */
  98. ProtoBuf.WIRE_TYPES.BITS32 = 5;
  99. /**
  100. * Packable wire types.
  101. * @type {!Array.<number>}
  102. * @const
  103. * @expose
  104. */
  105. ProtoBuf.PACKABLE_WIRE_TYPES = [
  106. ProtoBuf.WIRE_TYPES.VARINT,
  107. ProtoBuf.WIRE_TYPES.BITS64,
  108. ProtoBuf.WIRE_TYPES.BITS32
  109. ];
  110. /**
  111. * Types.
  112. * @dict
  113. * @type {!Object.<string,{name: string, wireType: number, defaultValue: *}>}
  114. * @const
  115. * @expose
  116. */
  117. ProtoBuf.TYPES = {
  118. // According to the protobuf spec.
  119. "int32": {
  120. name: "int32",
  121. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  122. defaultValue: 0
  123. },
  124. "uint32": {
  125. name: "uint32",
  126. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  127. defaultValue: 0
  128. },
  129. "sint32": {
  130. name: "sint32",
  131. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  132. defaultValue: 0
  133. },
  134. "int64": {
  135. name: "int64",
  136. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  137. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
  138. },
  139. "uint64": {
  140. name: "uint64",
  141. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  142. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
  143. },
  144. "sint64": {
  145. name: "sint64",
  146. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  147. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
  148. },
  149. "bool": {
  150. name: "bool",
  151. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  152. defaultValue: false
  153. },
  154. "double": {
  155. name: "double",
  156. wireType: ProtoBuf.WIRE_TYPES.BITS64,
  157. defaultValue: 0
  158. },
  159. "string": {
  160. name: "string",
  161. wireType: ProtoBuf.WIRE_TYPES.LDELIM,
  162. defaultValue: ""
  163. },
  164. "bytes": {
  165. name: "bytes",
  166. wireType: ProtoBuf.WIRE_TYPES.LDELIM,
  167. defaultValue: null // overridden in the code, must be a unique instance
  168. },
  169. "fixed32": {
  170. name: "fixed32",
  171. wireType: ProtoBuf.WIRE_TYPES.BITS32,
  172. defaultValue: 0
  173. },
  174. "sfixed32": {
  175. name: "sfixed32",
  176. wireType: ProtoBuf.WIRE_TYPES.BITS32,
  177. defaultValue: 0
  178. },
  179. "fixed64": {
  180. name: "fixed64",
  181. wireType: ProtoBuf.WIRE_TYPES.BITS64,
  182. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
  183. },
  184. "sfixed64": {
  185. name: "sfixed64",
  186. wireType: ProtoBuf.WIRE_TYPES.BITS64,
  187. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
  188. },
  189. "float": {
  190. name: "float",
  191. wireType: ProtoBuf.WIRE_TYPES.BITS32,
  192. defaultValue: 0
  193. },
  194. "enum": {
  195. name: "enum",
  196. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  197. defaultValue: 0
  198. },
  199. "message": {
  200. name: "message",
  201. wireType: ProtoBuf.WIRE_TYPES.LDELIM,
  202. defaultValue: null
  203. },
  204. "group": {
  205. name: "group",
  206. wireType: ProtoBuf.WIRE_TYPES.STARTGROUP,
  207. defaultValue: null
  208. }
  209. };
  210. /**
  211. * Valid map key types.
  212. * @type {!Array.<!Object.<string,{name: string, wireType: number, defaultValue: *}>>}
  213. * @const
  214. * @expose
  215. */
  216. ProtoBuf.MAP_KEY_TYPES = [
  217. ProtoBuf.TYPES["int32"],
  218. ProtoBuf.TYPES["sint32"],
  219. ProtoBuf.TYPES["sfixed32"],
  220. ProtoBuf.TYPES["uint32"],
  221. ProtoBuf.TYPES["fixed32"],
  222. ProtoBuf.TYPES["int64"],
  223. ProtoBuf.TYPES["sint64"],
  224. ProtoBuf.TYPES["sfixed64"],
  225. ProtoBuf.TYPES["uint64"],
  226. ProtoBuf.TYPES["fixed64"],
  227. ProtoBuf.TYPES["bool"],
  228. ProtoBuf.TYPES["string"],
  229. ProtoBuf.TYPES["bytes"]
  230. ];
  231. /**
  232. * Minimum field id.
  233. * @type {number}
  234. * @const
  235. * @expose
  236. */
  237. ProtoBuf.ID_MIN = 1;
  238. /**
  239. * Maximum field id.
  240. * @type {number}
  241. * @const
  242. * @expose
  243. */
  244. ProtoBuf.ID_MAX = 0x1FFFFFFF;
  245. /**
  246. * If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`.
  247. * Must be set prior to parsing.
  248. * @type {boolean}
  249. * @expose
  250. */
  251. ProtoBuf.convertFieldsToCamelCase = false;
  252. /**
  253. * By default, messages are populated with (setX, set_x) accessors for each field. This can be disabled by
  254. * setting this to `false` prior to building messages.
  255. * @type {boolean}
  256. * @expose
  257. */
  258. ProtoBuf.populateAccessors = true;
  259. /**
  260. * By default, messages are populated with default values if a field is not present on the wire. To disable
  261. * this behavior, set this setting to `false`.
  262. * @type {boolean}
  263. * @expose
  264. */
  265. ProtoBuf.populateDefaults = true;
  266. /**
  267. * @alias ProtoBuf.Util
  268. * @expose
  269. */
  270. ProtoBuf.Util = (function() {
  271. "use strict";
  272. /**
  273. * ProtoBuf utilities.
  274. * @exports ProtoBuf.Util
  275. * @namespace
  276. */
  277. var Util = {};
  278. /**
  279. * Flag if running in node or not.
  280. * @type {boolean}
  281. * @const
  282. * @expose
  283. */
  284. Util.IS_NODE = !!(
  285. typeof process === 'object' && process+'' === '[object process]' && !process['browser']
  286. );
  287. /**
  288. * Constructs a XMLHttpRequest object.
  289. * @return {XMLHttpRequest}
  290. * @throws {Error} If XMLHttpRequest is not supported
  291. * @expose
  292. */
  293. Util.XHR = function() {
  294. // No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
  295. var XMLHttpFactories = [
  296. function () {return new XMLHttpRequest()},
  297. function () {return new ActiveXObject("Msxml2.XMLHTTP")},
  298. function () {return new ActiveXObject("Msxml3.XMLHTTP")},
  299. function () {return new ActiveXObject("Microsoft.XMLHTTP")}
  300. ];
  301. /** @type {?XMLHttpRequest} */
  302. var xhr = null;
  303. for (var i=0;i<XMLHttpFactories.length;i++) {
  304. try { xhr = XMLHttpFactories[i](); }
  305. catch (e) { continue; }
  306. break;
  307. }
  308. if (!xhr)
  309. throw Error("XMLHttpRequest is not supported");
  310. return xhr;
  311. };
  312. /**
  313. * Fetches a resource.
  314. * @param {string} path Resource path
  315. * @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
  316. * be fetched synchronously. If the request failed, contents will be null.
  317. * @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
  318. * @expose
  319. */
  320. Util.fetch = function(path, callback) {
  321. if (callback && typeof callback != 'function')
  322. callback = null;
  323. if (Util.IS_NODE) {
  324. var fs = require("fs");
  325. if (callback) {
  326. fs.readFile(path, function(err, data) {
  327. if (err)
  328. callback(null);
  329. else
  330. callback(""+data);
  331. });
  332. } else
  333. try {
  334. return fs.readFileSync(path);
  335. } catch (e) {
  336. return null;
  337. }
  338. } else {
  339. var xhr = Util.XHR();
  340. xhr.open('GET', path, callback ? true : false);
  341. // xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
  342. xhr.setRequestHeader('Accept', 'text/plain');
  343. if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
  344. if (callback) {
  345. xhr.onreadystatechange = function() {
  346. if (xhr.readyState != 4) return;
  347. if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
  348. callback(xhr.responseText);
  349. else
  350. callback(null);
  351. };
  352. if (xhr.readyState == 4)
  353. return;
  354. xhr.send(null);
  355. } else {
  356. xhr.send(null);
  357. if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
  358. return xhr.responseText;
  359. return null;
  360. }
  361. }
  362. };
  363. /**
  364. * Converts a string to camel case.
  365. * @param {string} str
  366. * @returns {string}
  367. * @expose
  368. */
  369. Util.toCamelCase = function(str) {
  370. return str.replace(/_([a-zA-Z])/g, function ($0, $1) {
  371. return $1.toUpperCase();
  372. });
  373. };
  374. return Util;
  375. })();
  376. /**
  377. * Language expressions.
  378. * @type {!Object.<string,!RegExp>}
  379. * @expose
  380. */
  381. ProtoBuf.Lang = {
  382. // Characters always ending a statement
  383. DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g,
  384. // Field rules
  385. RULE: /^(?:required|optional|repeated|map)$/,
  386. // Field types
  387. TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,
  388. // Names
  389. NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/,
  390. // Type definitions
  391. TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/,
  392. // Type references
  393. TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,
  394. // Fully qualified type references
  395. FQTYPEREF: /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/,
  396. // All numbers
  397. NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,
  398. // Decimal numbers
  399. NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/,
  400. // Hexadecimal numbers
  401. NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/,
  402. // Octal numbers
  403. NUMBER_OCT: /^0[0-7]+$/,
  404. // Floating point numbers
  405. NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,
  406. // Booleans
  407. BOOL: /^(?:true|false)$/i,
  408. // Id numbers
  409. ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
  410. // Negative id numbers (enum values)
  411. NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
  412. // Whitespaces
  413. WHITESPACE: /\s/,
  414. // All strings
  415. STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,
  416. // Double quoted strings
  417. STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
  418. // Single quoted strings
  419. STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g
  420. };
  421. /**
  422. * @alias ProtoBuf.Reflect
  423. * @expose
  424. */
  425. ProtoBuf.Reflect = (function(ProtoBuf) {
  426. "use strict";
  427. /**
  428. * Reflection types.
  429. * @exports ProtoBuf.Reflect
  430. * @namespace
  431. */
  432. var Reflect = {};
  433. /**
  434. * Constructs a Reflect base class.
  435. * @exports ProtoBuf.Reflect.T
  436. * @constructor
  437. * @abstract
  438. * @param {!ProtoBuf.Builder} builder Builder reference
  439. * @param {?ProtoBuf.Reflect.T} parent Parent object
  440. * @param {string} name Object name
  441. */
  442. var T = function(builder, parent, name) {
  443. /**
  444. * Builder reference.
  445. * @type {!ProtoBuf.Builder}
  446. * @expose
  447. */
  448. this.builder = builder;
  449. /**
  450. * Parent object.
  451. * @type {?ProtoBuf.Reflect.T}
  452. * @expose
  453. */
  454. this.parent = parent;
  455. /**
  456. * Object name in namespace.
  457. * @type {string}
  458. * @expose
  459. */
  460. this.name = name;
  461. /**
  462. * Fully qualified class name
  463. * @type {string}
  464. * @expose
  465. */
  466. this.className;
  467. };
  468. /**
  469. * @alias ProtoBuf.Reflect.T.prototype
  470. * @inner
  471. */
  472. var TPrototype = T.prototype;
  473. /**
  474. * Returns the fully qualified name of this object.
  475. * @returns {string} Fully qualified name as of ".PATH.TO.THIS"
  476. * @expose
  477. */
  478. TPrototype.fqn = function() {
  479. var name = this.name,
  480. ptr = this;
  481. do {
  482. ptr = ptr.parent;
  483. if (ptr == null)
  484. break;
  485. name = ptr.name+"."+name;
  486. } while (true);
  487. return name;
  488. };
  489. /**
  490. * Returns a string representation of this Reflect object (its fully qualified name).
  491. * @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
  492. * @return String representation
  493. * @expose
  494. */
  495. TPrototype.toString = function(includeClass) {
  496. return (includeClass ? this.className + " " : "") + this.fqn();
  497. };
  498. /**
  499. * Builds this type.
  500. * @throws {Error} If this type cannot be built directly
  501. * @expose
  502. */
  503. TPrototype.build = function() {
  504. throw Error(this.toString(true)+" cannot be built directly");
  505. };
  506. /**
  507. * @alias ProtoBuf.Reflect.T
  508. * @expose
  509. */
  510. Reflect.T = T;
  511. /**
  512. * Constructs a new Namespace.
  513. * @exports ProtoBuf.Reflect.Namespace
  514. * @param {!ProtoBuf.Builder} builder Builder reference
  515. * @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent
  516. * @param {string} name Namespace name
  517. * @param {Object.<string,*>=} options Namespace options
  518. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  519. * @constructor
  520. * @extends ProtoBuf.Reflect.T
  521. */
  522. var Namespace = function(builder, parent, name, options, syntax) {
  523. T.call(this, builder, parent, name);
  524. /**
  525. * @override
  526. */
  527. this.className = "Namespace";
  528. /**
  529. * Children inside the namespace.
  530. * @type {!Array.<ProtoBuf.Reflect.T>}
  531. */
  532. this.children = [];
  533. /**
  534. * Options.
  535. * @type {!Object.<string, *>}
  536. */
  537. this.options = options || {};
  538. /**
  539. * Syntax level (e.g., proto2 or proto3).
  540. * @type {!string}
  541. */
  542. this.syntax = syntax || "proto2";
  543. };
  544. /**
  545. * @alias ProtoBuf.Reflect.Namespace.prototype
  546. * @inner
  547. */
  548. var NamespacePrototype = Namespace.prototype = Object.create(T.prototype);
  549. /**
  550. * Returns an array of the namespace's children.
  551. * @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
  552. * @return {Array.<ProtoBuf.Reflect.T>}
  553. * @expose
  554. */
  555. NamespacePrototype.getChildren = function(type) {
  556. type = type || null;
  557. if (type == null)
  558. return this.children.slice();
  559. var children = [];
  560. for (var i=0, k=this.children.length; i<k; ++i)
  561. if (this.children[i] instanceof type)
  562. children.push(this.children[i]);
  563. return children;
  564. };
  565. /**
  566. * Adds a child to the namespace.
  567. * @param {ProtoBuf.Reflect.T} child Child
  568. * @throws {Error} If the child cannot be added (duplicate)
  569. * @expose
  570. */
  571. NamespacePrototype.addChild = function(child) {
  572. var other;
  573. if (other = this.getChild(child.name)) {
  574. // Try to revert camelcase transformation on collision
  575. if (other instanceof Message.Field && other.name !== other.originalName && this.getChild(other.originalName) === null)
  576. other.name = other.originalName; // Revert previous first (effectively keeps both originals)
  577. else if (child instanceof Message.Field && child.name !== child.originalName && this.getChild(child.originalName) === null)
  578. child.name = child.originalName;
  579. else
  580. throw Error("Duplicate name in namespace "+this.toString(true)+": "+child.name);
  581. }
  582. this.children.push(child);
  583. };
  584. /**
  585. * Gets a child by its name or id.
  586. * @param {string|number} nameOrId Child name or id
  587. * @return {?ProtoBuf.Reflect.T} The child or null if not found
  588. * @expose
  589. */
  590. NamespacePrototype.getChild = function(nameOrId) {
  591. var key = typeof nameOrId === 'number' ? 'id' : 'name';
  592. for (var i=0, k=this.children.length; i<k; ++i)
  593. if (this.children[i][key] === nameOrId)
  594. return this.children[i];
  595. return null;
  596. };
  597. /**
  598. * Resolves a reflect object inside of this namespace.
  599. * @param {string|!Array.<string>} qn Qualified name to resolve
  600. * @param {boolean=} excludeNonNamespace Excludes non-namespace types, defaults to `false`
  601. * @return {?ProtoBuf.Reflect.Namespace} The resolved type or null if not found
  602. * @expose
  603. */
  604. NamespacePrototype.resolve = function(qn, excludeNonNamespace) {
  605. var part = typeof qn === 'string' ? qn.split(".") : qn,
  606. ptr = this,
  607. i = 0;
  608. if (part[i] === "") { // Fully qualified name, e.g. ".My.Message'
  609. while (ptr.parent !== null)
  610. ptr = ptr.parent;
  611. i++;
  612. }
  613. var child;
  614. do {
  615. do {
  616. if (!(ptr instanceof Reflect.Namespace)) {
  617. ptr = null;
  618. break;
  619. }
  620. child = ptr.getChild(part[i]);
  621. if (!child || !(child instanceof Reflect.T) || (excludeNonNamespace && !(child instanceof Reflect.Namespace))) {
  622. ptr = null;
  623. break;
  624. }
  625. ptr = child; i++;
  626. } while (i < part.length);
  627. if (ptr != null)
  628. break; // Found
  629. // Else search the parent
  630. if (this.parent !== null)
  631. return this.parent.resolve(qn, excludeNonNamespace);
  632. } while (ptr != null);
  633. return ptr;
  634. };
  635. /**
  636. * Determines the shortest qualified name of the specified type, if any, relative to this namespace.
  637. * @param {!ProtoBuf.Reflect.T} t Reflection type
  638. * @returns {string} The shortest qualified name or, if there is none, the fqn
  639. * @expose
  640. */
  641. NamespacePrototype.qn = function(t) {
  642. var part = [], ptr = t;
  643. do {
  644. part.unshift(ptr.name);
  645. ptr = ptr.parent;
  646. } while (ptr !== null);
  647. for (var len=1; len <= part.length; len++) {
  648. var qn = part.slice(part.length-len);
  649. if (t === this.resolve(qn, t instanceof Reflect.Namespace))
  650. return qn.join(".");
  651. }
  652. return t.fqn();
  653. };
  654. /**
  655. * Builds the namespace and returns the runtime counterpart.
  656. * @return {Object.<string,Function|Object>} Runtime namespace
  657. * @expose
  658. */
  659. NamespacePrototype.build = function() {
  660. /** @dict */
  661. var ns = {};
  662. var children = this.children;
  663. for (var i=0, k=children.length, child; i<k; ++i) {
  664. child = children[i];
  665. if (child instanceof Namespace)
  666. ns[child.name] = child.build();
  667. }
  668. if (Object.defineProperty)
  669. Object.defineProperty(ns, "$options", { "value": this.buildOpt() });
  670. return ns;
  671. };
  672. /**
  673. * Builds the namespace's '$options' property.
  674. * @return {Object.<string,*>}
  675. */
  676. NamespacePrototype.buildOpt = function() {
  677. var opt = {},
  678. keys = Object.keys(this.options);
  679. for (var i=0, k=keys.length; i<k; ++i) {
  680. var key = keys[i],
  681. val = this.options[keys[i]];
  682. // TODO: Options are not resolved, yet.
  683. // if (val instanceof Namespace) {
  684. // opt[key] = val.build();
  685. // } else {
  686. opt[key] = val;
  687. // }
  688. }
  689. return opt;
  690. };
  691. /**
  692. * Gets the value assigned to the option with the specified name.
  693. * @param {string=} name Returns the option value if specified, otherwise all options are returned.
  694. * @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
  695. */
  696. NamespacePrototype.getOption = function(name) {
  697. if (typeof name === 'undefined')
  698. return this.options;
  699. return typeof this.options[name] !== 'undefined' ? this.options[name] : null;
  700. };
  701. /**
  702. * @alias ProtoBuf.Reflect.Namespace
  703. * @expose
  704. */
  705. Reflect.Namespace = Namespace;
  706. /**
  707. * Constructs a new Element implementation that checks and converts values for a
  708. * particular field type, as appropriate.
  709. *
  710. * An Element represents a single value: either the value of a singular field,
  711. * or a value contained in one entry of a repeated field or map field. This
  712. * class does not implement these higher-level concepts; it only encapsulates
  713. * the low-level typechecking and conversion.
  714. *
  715. * @exports ProtoBuf.Reflect.Element
  716. * @param {{name: string, wireType: number}} type Resolved data type
  717. * @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant
  718. * (e.g. submessage field).
  719. * @param {boolean} isMapKey Is this element a Map key? The value will be
  720. * converted to string form if so.
  721. * @param {string} syntax Syntax level of defining message type, e.g.,
  722. * proto2 or proto3.
  723. * @param {string} name Name of the field containing this element (for error
  724. * messages)
  725. * @constructor
  726. */
  727. var Element = function(type, resolvedType, isMapKey, syntax, name) {
  728. /**
  729. * Element type, as a string (e.g., int32).
  730. * @type {{name: string, wireType: number}}
  731. */
  732. this.type = type;
  733. /**
  734. * Element type reference to submessage or enum definition, if needed.
  735. * @type {ProtoBuf.Reflect.T|null}
  736. */
  737. this.resolvedType = resolvedType;
  738. /**
  739. * Element is a map key.
  740. * @type {boolean}
  741. */
  742. this.isMapKey = isMapKey;
  743. /**
  744. * Syntax level of defining message type, e.g., proto2 or proto3.
  745. * @type {string}
  746. */
  747. this.syntax = syntax;
  748. /**
  749. * Name of the field containing this element (for error messages)
  750. * @type {string}
  751. */
  752. this.name = name;
  753. if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0)
  754. throw Error("Invalid map key type: " + type.name);
  755. };
  756. var ElementPrototype = Element.prototype;
  757. /**
  758. * Obtains a (new) default value for the specified type.
  759. * @param type {string|{name: string, wireType: number}} Field type
  760. * @returns {*} Default value
  761. * @inner
  762. */
  763. function mkDefault(type) {
  764. if (typeof type === 'string')
  765. type = ProtoBuf.TYPES[type];
  766. if (typeof type.defaultValue === 'undefined')
  767. throw Error("default value for type "+type.name+" is not supported");
  768. if (type == ProtoBuf.TYPES["bytes"])
  769. return new ByteBuffer(0);
  770. return type.defaultValue;
  771. }
  772. /**
  773. * Returns the default value for this field in proto3.
  774. * @function
  775. * @param type {string|{name: string, wireType: number}} the field type
  776. * @returns {*} Default value
  777. */
  778. Element.defaultFieldValue = mkDefault;
  779. /**
  780. * Makes a Long from a value.
  781. * @param {{low: number, high: number, unsigned: boolean}|string|number} value Value
  782. * @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for
  783. * strings and numbers
  784. * @returns {!Long}
  785. * @throws {Error} If the value cannot be converted to a Long
  786. * @inner
  787. */
  788. function mkLong(value, unsigned) {
  789. if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean'
  790. && value.low === value.low && value.high === value.high)
  791. return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned);
  792. if (typeof value === 'string')
  793. return ProtoBuf.Long.fromString(value, unsigned || false, 10);
  794. if (typeof value === 'number')
  795. return ProtoBuf.Long.fromNumber(value, unsigned || false);
  796. throw Error("not convertible to Long");
  797. }
  798. ElementPrototype.toString = function() {
  799. return (this.name || '') + (this.isMapKey ? 'map' : 'value') + ' element';
  800. }
  801. /**
  802. * Checks if the given value can be set for an element of this type (singular
  803. * field or one element of a repeated field or map).
  804. * @param {*} value Value to check
  805. * @return {*} Verified, maybe adjusted, value
  806. * @throws {Error} If the value cannot be verified for this element slot
  807. * @expose
  808. */
  809. ElementPrototype.verifyValue = function(value) {
  810. var self = this;
  811. function fail(val, msg) {
  812. throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
  813. }
  814. switch (this.type) {
  815. // Signed 32bit
  816. case ProtoBuf.TYPES["int32"]:
  817. case ProtoBuf.TYPES["sint32"]:
  818. case ProtoBuf.TYPES["sfixed32"]:
  819. // Account for !NaN: value === value
  820. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  821. fail(typeof value, "not an integer");
  822. return value > 4294967295 ? value | 0 : value;
  823. // Unsigned 32bit
  824. case ProtoBuf.TYPES["uint32"]:
  825. case ProtoBuf.TYPES["fixed32"]:
  826. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  827. fail(typeof value, "not an integer");
  828. return value < 0 ? value >>> 0 : value;
  829. // Signed 64bit
  830. case ProtoBuf.TYPES["int64"]:
  831. case ProtoBuf.TYPES["sint64"]:
  832. case ProtoBuf.TYPES["sfixed64"]: {
  833. if (ProtoBuf.Long)
  834. try {
  835. return mkLong(value, false);
  836. } catch (e) {
  837. fail(typeof value, e.message);
  838. }
  839. else
  840. fail(typeof value, "requires Long.js");
  841. }
  842. // Unsigned 64bit
  843. case ProtoBuf.TYPES["uint64"]:
  844. case ProtoBuf.TYPES["fixed64"]: {
  845. if (ProtoBuf.Long)
  846. try {
  847. return mkLong(value, true);
  848. } catch (e) {
  849. fail(typeof value, e.message);
  850. }
  851. else
  852. fail(typeof value, "requires Long.js");
  853. }
  854. // Bool
  855. case ProtoBuf.TYPES["bool"]:
  856. if (typeof value !== 'boolean')
  857. fail(typeof value, "not a boolean");
  858. return value;
  859. // Float
  860. case ProtoBuf.TYPES["float"]:
  861. case ProtoBuf.TYPES["double"]:
  862. if (typeof value !== 'number')
  863. fail(typeof value, "not a number");
  864. return value;
  865. // Length-delimited string
  866. case ProtoBuf.TYPES["string"]:
  867. if (typeof value !== 'string' && !(value && value instanceof String))
  868. fail(typeof value, "not a string");
  869. return ""+value; // Convert String object to string
  870. // Length-delimited bytes
  871. case ProtoBuf.TYPES["bytes"]:
  872. if (ByteBuffer.isByteBuffer(value))
  873. return value;
  874. return ByteBuffer.wrap(value, "base64");
  875. // Constant enum value
  876. case ProtoBuf.TYPES["enum"]: {
  877. var values = this.resolvedType.getChildren(ProtoBuf.Reflect.Enum.Value);
  878. for (i=0; i<values.length; i++)
  879. if (values[i].name == value)
  880. return values[i].id;
  881. else if (values[i].id == value)
  882. return values[i].id;
  883. if (this.syntax === 'proto3') {
  884. // proto3: just make sure it's an integer.
  885. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  886. fail(typeof value, "not an integer");
  887. if (value > 4294967295 || value < 0)
  888. fail(typeof value, "not in range for uint32")
  889. return value;
  890. } else {
  891. // proto2 requires enum values to be valid.
  892. fail(value, "not a valid enum value");
  893. }
  894. }
  895. // Embedded message
  896. case ProtoBuf.TYPES["group"]:
  897. case ProtoBuf.TYPES["message"]: {
  898. if (!value || typeof value !== 'object')
  899. fail(typeof value, "object expected");
  900. if (value instanceof this.resolvedType.clazz)
  901. return value;
  902. if (value instanceof ProtoBuf.Builder.Message) {
  903. // Mismatched type: Convert to object (see: https://github.com/dcodeIO/ProtoBuf.js/issues/180)
  904. var obj = {};
  905. for (var i in value)
  906. if (value.hasOwnProperty(i))
  907. obj[i] = value[i];
  908. value = obj;
  909. }
  910. // Else let's try to construct one from a key-value object
  911. return new (this.resolvedType.clazz)(value); // May throw for a hundred of reasons
  912. }
  913. }
  914. // We should never end here
  915. throw Error("[INTERNAL] Illegal value for "+this.toString(true)+": "+value+" (undefined type "+this.type+")");
  916. };
  917. /**
  918. * Calculates the byte length of an element on the wire.
  919. * @param {number} id Field number
  920. * @param {*} value Field value
  921. * @returns {number} Byte length
  922. * @throws {Error} If the value cannot be calculated
  923. * @expose
  924. */
  925. ElementPrototype.calculateLength = function(id, value) {
  926. if (value === null) return 0; // Nothing to encode
  927. // Tag has already been written
  928. var n;
  929. switch (this.type) {
  930. case ProtoBuf.TYPES["int32"]:
  931. return value < 0 ? ByteBuffer.calculateVarint64(value) : ByteBuffer.calculateVarint32(value);
  932. case ProtoBuf.TYPES["uint32"]:
  933. return ByteBuffer.calculateVarint32(value);
  934. case ProtoBuf.TYPES["sint32"]:
  935. return ByteBuffer.calculateVarint32(ByteBuffer.zigZagEncode32(value));
  936. case ProtoBuf.TYPES["fixed32"]:
  937. case ProtoBuf.TYPES["sfixed32"]:
  938. case ProtoBuf.TYPES["float"]:
  939. return 4;
  940. case ProtoBuf.TYPES["int64"]:
  941. case ProtoBuf.TYPES["uint64"]:
  942. return ByteBuffer.calculateVarint64(value);
  943. case ProtoBuf.TYPES["sint64"]:
  944. return ByteBuffer.calculateVarint64(ByteBuffer.zigZagEncode64(value));
  945. case ProtoBuf.TYPES["fixed64"]:
  946. case ProtoBuf.TYPES["sfixed64"]:
  947. return 8;
  948. case ProtoBuf.TYPES["bool"]:
  949. return 1;
  950. case ProtoBuf.TYPES["enum"]:
  951. return ByteBuffer.calculateVarint32(value);
  952. case ProtoBuf.TYPES["double"]:
  953. return 8;
  954. case ProtoBuf.TYPES["string"]:
  955. n = ByteBuffer.calculateUTF8Bytes(value);
  956. return ByteBuffer.calculateVarint32(n) + n;
  957. case ProtoBuf.TYPES["bytes"]:
  958. if (value.remaining() < 0)
  959. throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
  960. return ByteBuffer.calculateVarint32(value.remaining()) + value.remaining();
  961. case ProtoBuf.TYPES["message"]:
  962. n = this.resolvedType.calculate(value);
  963. return ByteBuffer.calculateVarint32(n) + n;
  964. case ProtoBuf.TYPES["group"]:
  965. n = this.resolvedType.calculate(value);
  966. return n + ByteBuffer.calculateVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
  967. }
  968. // We should never end here
  969. throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
  970. };
  971. /**
  972. * Encodes a value to the specified buffer. Does not encode the key.
  973. * @param {number} id Field number
  974. * @param {*} value Field value
  975. * @param {ByteBuffer} buffer ByteBuffer to encode to
  976. * @return {ByteBuffer} The ByteBuffer for chaining
  977. * @throws {Error} If the value cannot be encoded
  978. * @expose
  979. */
  980. ElementPrototype.encodeValue = function(id, value, buffer) {
  981. if (value === null) return buffer; // Nothing to encode
  982. // Tag has already been written
  983. switch (this.type) {
  984. // 32bit signed varint
  985. case ProtoBuf.TYPES["int32"]:
  986. // "If you use int32 or int64 as the type for a negative number, the resulting varint is always ten bytes
  987. // long – it is, effectively, treated like a very large unsigned integer." (see #122)
  988. if (value < 0)
  989. buffer.writeVarint64(value);
  990. else
  991. buffer.writeVarint32(value);
  992. break;
  993. // 32bit unsigned varint
  994. case ProtoBuf.TYPES["uint32"]:
  995. buffer.writeVarint32(value);
  996. break;
  997. // 32bit varint zig-zag
  998. case ProtoBuf.TYPES["sint32"]:
  999. buffer.writeVarint32ZigZag(value);
  1000. break;
  1001. // Fixed unsigned 32bit
  1002. case ProtoBuf.TYPES["fixed32"]:
  1003. buffer.writeUint32(value);
  1004. break;
  1005. // Fixed signed 32bit
  1006. case ProtoBuf.TYPES["sfixed32"]:
  1007. buffer.writeInt32(value);
  1008. break;
  1009. // 64bit varint as-is
  1010. case ProtoBuf.TYPES["int64"]:
  1011. case ProtoBuf.TYPES["uint64"]:
  1012. buffer.writeVarint64(value); // throws
  1013. break;
  1014. // 64bit varint zig-zag
  1015. case ProtoBuf.TYPES["sint64"]:
  1016. buffer.writeVarint64ZigZag(value); // throws
  1017. break;
  1018. // Fixed unsigned 64bit
  1019. case ProtoBuf.TYPES["fixed64"]:
  1020. buffer.writeUint64(value); // throws
  1021. break;
  1022. // Fixed signed 64bit
  1023. case ProtoBuf.TYPES["sfixed64"]:
  1024. buffer.writeInt64(value); // throws
  1025. break;
  1026. // Bool
  1027. case ProtoBuf.TYPES["bool"]:
  1028. if (typeof value === 'string')
  1029. buffer.writeVarint32(value.toLowerCase() === 'false' ? 0 : !!value);
  1030. else
  1031. buffer.writeVarint32(value ? 1 : 0);
  1032. break;
  1033. // Constant enum value
  1034. case ProtoBuf.TYPES["enum"]:
  1035. buffer.writeVarint32(value);
  1036. break;
  1037. // 32bit float
  1038. case ProtoBuf.TYPES["float"]:
  1039. buffer.writeFloat32(value);
  1040. break;
  1041. // 64bit float
  1042. case ProtoBuf.TYPES["double"]:
  1043. buffer.writeFloat64(value);
  1044. break;
  1045. // Length-delimited string
  1046. case ProtoBuf.TYPES["string"]:
  1047. buffer.writeVString(value);
  1048. break;
  1049. // Length-delimited bytes
  1050. case ProtoBuf.TYPES["bytes"]:
  1051. if (value.remaining() < 0)
  1052. throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
  1053. var prevOffset = value.offset;
  1054. buffer.writeVarint32(value.remaining());
  1055. buffer.append(value);
  1056. value.offset = prevOffset;
  1057. break;
  1058. // Embedded message
  1059. case ProtoBuf.TYPES["message"]:
  1060. var bb = new ByteBuffer().LE();
  1061. this.resolvedType.encode(value, bb);
  1062. buffer.writeVarint32(bb.offset);
  1063. buffer.append(bb.flip());
  1064. break;
  1065. // Legacy group
  1066. case ProtoBuf.TYPES["group"]:
  1067. this.resolvedType.encode(value, buffer);
  1068. buffer.writeVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
  1069. break;
  1070. default:
  1071. // We should never end here
  1072. throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
  1073. }
  1074. return buffer;
  1075. };
  1076. /**
  1077. * Decode one element value from the specified buffer.
  1078. * @param {ByteBuffer} buffer ByteBuffer to decode from
  1079. * @param {number} wireType The field wire type
  1080. * @param {number} id The field number
  1081. * @return {*} Decoded value
  1082. * @throws {Error} If the field cannot be decoded
  1083. * @expose
  1084. */
  1085. ElementPrototype.decode = function(buffer, wireType, id) {
  1086. if (wireType != this.type.wireType)
  1087. throw Error("Unexpected wire type for element");
  1088. var value, nBytes;
  1089. switch (this.type) {
  1090. // 32bit signed varint
  1091. case ProtoBuf.TYPES["int32"]:
  1092. return buffer.readVarint32() | 0;
  1093. // 32bit unsigned varint
  1094. case ProtoBuf.TYPES["uint32"]:
  1095. return buffer.readVarint32() >>> 0;
  1096. // 32bit signed varint zig-zag
  1097. case ProtoBuf.TYPES["sint32"]:
  1098. return buffer.readVarint32ZigZag() | 0;
  1099. // Fixed 32bit unsigned
  1100. case ProtoBuf.TYPES["fixed32"]:
  1101. return buffer.readUint32() >>> 0;
  1102. case ProtoBuf.TYPES["sfixed32"]:
  1103. return buffer.readInt32() | 0;
  1104. // 64bit signed varint
  1105. case ProtoBuf.TYPES["int64"]:
  1106. return buffer.readVarint64();
  1107. // 64bit unsigned varint
  1108. case ProtoBuf.TYPES["uint64"]:
  1109. return buffer.readVarint64().toUnsigned();
  1110. // 64bit signed varint zig-zag
  1111. case ProtoBuf.TYPES["sint64"]:
  1112. return buffer.readVarint64ZigZag();
  1113. // Fixed 64bit unsigned
  1114. case ProtoBuf.TYPES["fixed64"]:
  1115. return buffer.readUint64();
  1116. // Fixed 64bit signed
  1117. case ProtoBuf.TYPES["sfixed64"]:
  1118. return buffer.readInt64();
  1119. // Bool varint
  1120. case ProtoBuf.TYPES["bool"]:
  1121. return !!buffer.readVarint32();
  1122. // Constant enum value (varint)
  1123. case ProtoBuf.TYPES["enum"]:
  1124. // The following Builder.Message#set will already throw
  1125. return buffer.readVarint32();
  1126. // 32bit float
  1127. case ProtoBuf.TYPES["float"]:
  1128. return buffer.readFloat();
  1129. // 64bit float
  1130. case ProtoBuf.TYPES["double"]:
  1131. return buffer.readDouble();
  1132. // Length-delimited string
  1133. case ProtoBuf.TYPES["string"]:
  1134. return buffer.readVString();
  1135. // Length-delimited bytes
  1136. case ProtoBuf.TYPES["bytes"]: {
  1137. nBytes = buffer.readVarint32();
  1138. if (buffer.remaining() < nBytes)
  1139. throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
  1140. value = buffer.clone(); // Offset already set
  1141. value.limit = value.offset+nBytes;
  1142. buffer.offset += nBytes;
  1143. return value;
  1144. }
  1145. // Length-delimited embedded message
  1146. case ProtoBuf.TYPES["message"]: {
  1147. nBytes = buffer.readVarint32();
  1148. return this.resolvedType.decode(buffer, nBytes);
  1149. }
  1150. // Legacy group
  1151. case ProtoBuf.TYPES["group"]:
  1152. return this.resolvedType.decode(buffer, -1, id);
  1153. }
  1154. // We should never end here
  1155. throw Error("[INTERNAL] Illegal decode type");
  1156. };
  1157. /**
  1158. * Converts a value from a string to the canonical element type.
  1159. *
  1160. * Legal only when isMapKey is true.
  1161. *
  1162. * @param {string} str The string value
  1163. * @returns {*} The value
  1164. */
  1165. ElementPrototype.valueFromString = function(str) {
  1166. if (!this.isMapKey) {
  1167. throw Error("valueFromString() called on non-map-key element");
  1168. }
  1169. switch (this.type) {
  1170. case ProtoBuf.TYPES["int32"]:
  1171. case ProtoBuf.TYPES["sint32"]:
  1172. case ProtoBuf.TYPES["sfixed32"]:
  1173. case ProtoBuf.TYPES["uint32"]:
  1174. case ProtoBuf.TYPES["fixed32"]:
  1175. return this.verifyValue(parseInt(str));
  1176. case ProtoBuf.TYPES["int64"]:
  1177. case ProtoBuf.TYPES["sint64"]:
  1178. case ProtoBuf.TYPES["sfixed64"]:
  1179. case ProtoBuf.TYPES["uint64"]:
  1180. case ProtoBuf.TYPES["fixed64"]:
  1181. // Long-based fields support conversions from string already.
  1182. return this.verifyValue(str);
  1183. case ProtoBuf.TYPES["bool"]:
  1184. return str === "true";
  1185. case ProtoBuf.TYPES["string"]:
  1186. return this.verifyValue(str);
  1187. case ProtoBuf.TYPES["bytes"]:
  1188. return ByteBuffer.fromBinary(str);
  1189. }
  1190. };
  1191. /**
  1192. * Converts a value from the canonical element type to a string.
  1193. *
  1194. * It should be the case that `valueFromString(valueToString(val))` returns
  1195. * a value equivalent to `verifyValue(val)` for every legal value of `val`
  1196. * according to this element type.
  1197. *
  1198. * This may be used when the element must be stored or used as a string,
  1199. * e.g., as a map key on an Object.
  1200. *
  1201. * Legal only when isMapKey is true.
  1202. *
  1203. * @param {*} val The value
  1204. * @returns {string} The string form of the value.
  1205. */
  1206. ElementPrototype.valueToString = function(value) {
  1207. if (!this.isMapKey) {
  1208. throw Error("valueToString() called on non-map-key element");
  1209. }
  1210. if (this.type === ProtoBuf.TYPES["bytes"]) {
  1211. return value.toString("binary");
  1212. } else {
  1213. return value.toString();
  1214. }
  1215. };
  1216. /**
  1217. * @alias ProtoBuf.Reflect.Element
  1218. * @expose
  1219. */
  1220. Reflect.Element = Element;
  1221. /**
  1222. * Constructs a new Message.
  1223. * @exports ProtoBuf.Reflect.Message
  1224. * @param {!ProtoBuf.Builder} builder Builder reference
  1225. * @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace
  1226. * @param {string} name Message name
  1227. * @param {Object.<string,*>=} options Message options
  1228. * @param {boolean=} isGroup `true` if this is a legacy group
  1229. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  1230. * @constructor
  1231. * @extends ProtoBuf.Reflect.Namespace
  1232. */
  1233. var Message = function(builder, parent, name, options, isGroup, syntax) {
  1234. Namespace.call(this, builder, parent, name, options, syntax);
  1235. /**
  1236. * @override
  1237. */
  1238. this.className = "Message";
  1239. /**
  1240. * Extensions range.
  1241. * @type {!Array.<number>|undefined}
  1242. * @expose
  1243. */
  1244. this.extensions = undefined;
  1245. /**
  1246. * Runtime message class.
  1247. * @type {?function(new:ProtoBuf.Builder.Message)}
  1248. * @expose
  1249. */
  1250. this.clazz = null;
  1251. /**
  1252. * Whether this is a legacy group or not.
  1253. * @type {boolean}
  1254. * @expose
  1255. */
  1256. this.isGroup = !!isGroup;
  1257. // The following cached collections are used to efficiently iterate over or look up fields when decoding.
  1258. /**
  1259. * Cached fields.
  1260. * @type {?Array.<!ProtoBuf.Reflect.Message.Field>}
  1261. * @private
  1262. */
  1263. this._fields = null;
  1264. /**
  1265. * Cached fields by id.
  1266. * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>}
  1267. * @private
  1268. */
  1269. this._fieldsById = null;
  1270. /**
  1271. * Cached fields by name.
  1272. * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>}
  1273. * @private
  1274. */
  1275. this._fieldsByName = null;
  1276. };
  1277. /**
  1278. * @alias ProtoBuf.Reflect.Message.prototype
  1279. * @inner
  1280. */
  1281. var MessagePrototype = Message.prototype = Object.create(Namespace.prototype);
  1282. /**
  1283. * Builds the message and returns the runtime counterpart, which is a fully functional class.
  1284. * @see ProtoBuf.Builder.Message
  1285. * @param {boolean=} rebuild Whether to rebuild or not, defaults to false
  1286. * @return {ProtoBuf.Reflect.Message} Message class
  1287. * @throws {Error} If the message cannot be built
  1288. * @expose
  1289. */
  1290. MessagePrototype.build = function(rebuild) {
  1291. if (this.clazz && !rebuild)
  1292. return this.clazz;
  1293. // Create the runtime Message class in its own scope
  1294. var clazz = (function(ProtoBuf, T) {
  1295. var fields = T.getChildren(ProtoBuf.Reflect.Message.Field),
  1296. oneofs = T.getChildren(ProtoBuf.Reflect.Message.OneOf);
  1297. /**
  1298. * Constructs a new runtime Message.
  1299. * @name ProtoBuf.Builder.Message
  1300. * @class Barebone of all runtime messages.
  1301. * @param {!Object.<string,*>|string} values Preset values
  1302. * @param {...string} var_args
  1303. * @constructor
  1304. * @throws {Error} If the message cannot be created
  1305. */
  1306. var Message = function(values, var_args) {
  1307. ProtoBuf.Builder.Message.call(this);
  1308. // Create virtual oneof properties
  1309. for (var i=0, k=oneofs.length; i<k; ++i)
  1310. this[oneofs[i].name] = null;
  1311. // Create fields and set default values
  1312. for (i=0, k=fields.length; i<k; ++i) {
  1313. var field = fields[i];
  1314. this[field.name] =
  1315. field.repeated ? [] :
  1316. (field.map ? new ProtoBuf.Map(field) : null);
  1317. if ((field.required || T.syntax === 'proto3') &&
  1318. field.defaultValue !== null)
  1319. this[field.name] = field.defaultValue;
  1320. }
  1321. if (arguments.length > 0) {
  1322. var value;
  1323. // Set field values from a values object
  1324. if (arguments.length === 1 && values !== null && typeof values === 'object' &&
  1325. /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) &&
  1326. /* not a repeated field */ !Array.isArray(values) &&
  1327. /* not a Map */ !(values instanceof ProtoBuf.Map) &&
  1328. /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) &&
  1329. /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) &&
  1330. /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
  1331. this.$set(values);
  1332. } else // Set field values from arguments, in declaration order
  1333. for (i=0, k=arguments.length; i<k; ++i)
  1334. if (typeof (value = arguments[i]) !== 'undefined')
  1335. this.$set(fields[i].name, value); // May throw
  1336. }
  1337. };
  1338. /**
  1339. * @alias ProtoBuf.Builder.Message.prototype
  1340. * @inner
  1341. */
  1342. var MessagePrototype = Message.prototype = Object.create(ProtoBuf.Builder.Message.prototype);
  1343. /**
  1344. * Adds a value to a repeated field.
  1345. * @name ProtoBuf.Builder.Message#add
  1346. * @function
  1347. * @param {string} key Field name
  1348. * @param {*} value Value to add
  1349. * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
  1350. * @returns {!ProtoBuf.Builder.Message} this
  1351. * @throws {Error} If the value cannot be added
  1352. * @expose
  1353. */
  1354. MessagePrototype.add = function(key, value, noAssert) {
  1355. var field = T._fieldsByName[key];
  1356. if (!noAssert) {
  1357. if (!field)
  1358. throw Error(this+"#"+key+" is undefined");
  1359. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  1360. throw Error(this+"#"+key+" is not a field: "+field.toString(true)); // May throw if it's an enum or embedded message
  1361. if (!field.repeated)
  1362. throw Error(this+"#"+key+" is not a repeated field");
  1363. value = field.verifyValue(value, true);
  1364. }
  1365. if (this[key] === null)
  1366. this[key] = [];
  1367. this[key].push(value);
  1368. return this;
  1369. };
  1370. /**
  1371. * Adds a value to a repeated field. This is an alias for {@link ProtoBuf.Builder.Message#add}.
  1372. * @name ProtoBuf.Builder.Message#$add
  1373. * @function
  1374. * @param {string} key Field name
  1375. * @param {*} value Value to add
  1376. * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
  1377. * @returns {!ProtoBuf.Builder.Message} this
  1378. * @throws {Error} If the value cannot be added
  1379. * @expose
  1380. */
  1381. MessagePrototype.$add = MessagePrototype.add;
  1382. /**
  1383. * Sets a field's value.
  1384. * @name ProtoBuf.Builder.Message#set
  1385. * @function
  1386. * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
  1387. * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
  1388. * @param {boolean=} noAssert Whether to not assert for an actual field / proper value type, defaults to `false`
  1389. * @returns {!ProtoBuf.Builder.Message} this
  1390. * @throws {Error} If the value cannot be set
  1391. * @expose
  1392. */
  1393. MessagePrototype.set = function(keyOrObj, value, noAssert) {
  1394. if (keyOrObj && typeof keyOrObj === 'object') {
  1395. noAssert = value;
  1396. for (var ikey in keyOrObj) {
  1397. // Check if virtual oneof field - don't set these
  1398. if (keyOrObj.hasOwnProperty(ikey) && typeof (value = keyOrObj[ikey]) !== 'undefined' && T._oneofsByName[ikey] === undefined)
  1399. this.$set(ikey, value, noAssert);
  1400. }
  1401. return this;
  1402. }
  1403. var field = T._fieldsByName[keyOrObj];
  1404. if (!noAssert) {
  1405. if (!field)
  1406. throw Error(this+"#"+keyOrObj+" is not a field: undefined");
  1407. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  1408. throw Error(this+"#"+keyOrObj+" is not a field: "+field.toString(true));
  1409. this[field.name] = (value = field.verifyValue(value)); // May throw
  1410. } else
  1411. this[keyOrObj] = value;
  1412. if (field && field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
  1413. var currentField = this[field.oneof.name]; // Virtual field references currently set field
  1414. if (value !== null) {
  1415. if (currentField !== null && currentField !== field.name)
  1416. this[currentField] = null; // Clear currently set field
  1417. this[field.oneof.name] = field.name; // Point virtual field at this field
  1418. } else if (/* value === null && */currentField === keyOrObj)
  1419. this[field.oneof.name] = null; // Clear virtual field (current field explicitly cleared)
  1420. }
  1421. return this;
  1422. };
  1423. /**
  1424. * Sets a field's value. This is an alias for [@link ProtoBuf.Builder.Message#set}.
  1425. * @name ProtoBuf.Builder.Message#$set
  1426. * @function
  1427. * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
  1428. * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
  1429. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  1430. * @throws {Error} If the value cannot be set
  1431. * @expose
  1432. */
  1433. MessagePrototype.$set = MessagePrototype.set;
  1434. /**
  1435. * Gets a field's value.
  1436. * @name ProtoBuf.Builder.Message#get
  1437. * @function
  1438. * @param {string} key Key
  1439. * @param {boolean=} noAssert Whether to not assert for an actual field, defaults to `false`
  1440. * @return {*} Value
  1441. * @throws {Error} If there is no such field
  1442. * @expose
  1443. */
  1444. MessagePrototype.get = function(key, noAssert) {
  1445. if (noAssert)
  1446. return this[key];
  1447. var field = T._fieldsByName[key];
  1448. if (!field || !(field instanceof ProtoBuf.Reflect.Message.Field))
  1449. throw Error(this+"#"+key+" is not a field: undefined");
  1450. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  1451. throw Error(this+"#"+key+" is not a field: "+field.toString(true));
  1452. return this[field.name];
  1453. };
  1454. /**
  1455. * Gets a field's value. This is an alias for {@link ProtoBuf.Builder.Message#$get}.
  1456. * @name ProtoBuf.Builder.Message#$get
  1457. * @function
  1458. * @param {string} key Key
  1459. * @return {*} Value
  1460. * @throws {Error} If there is no such field
  1461. * @expose
  1462. */
  1463. MessagePrototype.$get = MessagePrototype.get;
  1464. // Getters and setters
  1465. for (var i=0; i<fields.length; i++) {
  1466. var field = fields[i];
  1467. // no setters for extension fields as these are named by their fqn
  1468. if (field instanceof ProtoBuf.Reflect.Message.ExtensionField)
  1469. continue;
  1470. if (T.builder.options['populateAccessors'])
  1471. (function(field) {
  1472. // set/get[SomeValue]
  1473. var Name = field.originalName.replace(/(_[a-zA-Z])/g, function(match) {
  1474. return match.toUpperCase().replace('_','');
  1475. });
  1476. Name = Name.substring(0,1).toUpperCase() + Name.substring(1);
  1477. // set/get_[some_value] FIXME: Do we really need these?
  1478. var name = field.originalName.replace(/([A-Z])/g, function(match) {
  1479. return "_"+match;
  1480. });
  1481. /**
  1482. * The current field's unbound setter function.
  1483. * @function
  1484. * @param {*} value
  1485. * @param {boolean=} noAssert
  1486. * @returns {!ProtoBuf.Builder.Message}
  1487. * @inner
  1488. */
  1489. var setter = function(value, noAssert) {
  1490. this[field.name] = noAssert ? value : field.verifyValue(value);
  1491. return this;
  1492. };
  1493. /**
  1494. * The current field's unbound getter function.
  1495. * @function
  1496. * @returns {*}
  1497. * @inner
  1498. */
  1499. var getter = function() {
  1500. return this[field.name];
  1501. };
  1502. if (T.getChild("set"+Name) === null)
  1503. /**
  1504. * Sets a value. This method is present for each field, but only if there is no name conflict with
  1505. * another field.
  1506. * @name ProtoBuf.Builder.Message#set[SomeField]
  1507. * @function
  1508. * @param {*} value Value to set
  1509. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  1510. * @returns {!ProtoBuf.Builder.Message} this
  1511. * @abstract
  1512. * @throws {Error} If the value cannot be set
  1513. */
  1514. MessagePrototype["set"+Name] = setter;
  1515. if (T.getChild("set_"+name) === null)
  1516. /**
  1517. * Sets a value. This method is present for each field, but only if there is no name conflict with
  1518. * another field.
  1519. * @name ProtoBuf.Builder.Message#set_[some_field]
  1520. * @function
  1521. * @param {*} value Value to set
  1522. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  1523. * @returns {!ProtoBuf.Builder.Message} this
  1524. * @abstract
  1525. * @throws {Error} If the value cannot be set
  1526. */
  1527. MessagePrototype["set_"+name] = setter;
  1528. if (T.getChild("get"+Name) === null)
  1529. /**
  1530. * Gets a value. This method is present for each field, but only if there is no name conflict with
  1531. * another field.
  1532. * @name ProtoBuf.Builder.Message#get[SomeField]
  1533. * @function
  1534. * @abstract
  1535. * @return {*} The value
  1536. */
  1537. MessagePrototype["get"+Name] = getter;
  1538. if (T.getChild("get_"+name) === null)
  1539. /**
  1540. * Gets a value. This method is present for each field, but only if there is no name conflict with
  1541. * another field.
  1542. * @name ProtoBuf.Builder.Message#get_[some_field]
  1543. * @function
  1544. * @return {*} The value
  1545. * @abstract
  1546. */
  1547. MessagePrototype["get_"+name] = getter;
  1548. })(field);
  1549. }
  1550. // En-/decoding
  1551. /**
  1552. * Encodes the message.
  1553. * @name ProtoBuf.Builder.Message#$encode
  1554. * @function
  1555. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  1556. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  1557. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  1558. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  1559. * returns the encoded ByteBuffer in the `encoded` property on the error.
  1560. * @expose
  1561. * @see ProtoBuf.Builder.Message#encode64
  1562. * @see ProtoBuf.Builder.Message#encodeHex
  1563. * @see ProtoBuf.Builder.Message#encodeAB
  1564. */
  1565. MessagePrototype.encode = function(buffer, noVerify) {
  1566. if (typeof buffer === 'boolean')
  1567. noVerify = buffer,
  1568. buffer = undefined;
  1569. var isNew = false;
  1570. if (!buffer)
  1571. buffer = new ByteBuffer(),
  1572. isNew = true;
  1573. var le = buffer.littleEndian;
  1574. try {
  1575. T.encode(this, buffer.LE(), noVerify);
  1576. return (isNew ? buffer.flip() : buffer).LE(le);
  1577. } catch (e) {
  1578. buffer.LE(le);
  1579. throw(e);
  1580. }
  1581. };
  1582. /**
  1583. * Encodes a message using the specified data payload.
  1584. * @param {!Object.<string,*>} data Data payload
  1585. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  1586. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  1587. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  1588. * @expose
  1589. */
  1590. Message.encode = function(data, buffer, noVerify) {
  1591. return new Message(data).encode(buffer, noVerify);
  1592. };
  1593. /**
  1594. * Calculates the byte length of the message.
  1595. * @name ProtoBuf.Builder.Message#calculate
  1596. * @function
  1597. * @returns {number} Byte length
  1598. * @throws {Error} If the message cannot be calculated or if required fields are missing.
  1599. * @expose
  1600. */
  1601. MessagePrototype.calculate = function() {
  1602. return T.calculate(this);
  1603. };
  1604. /**
  1605. * Encodes the varint32 length-delimited message.
  1606. * @name ProtoBuf.Builder.Message#encodeDelimited
  1607. * @function
  1608. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  1609. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  1610. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  1611. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  1612. * returns the encoded ByteBuffer in the `encoded` property on the error.
  1613. * @expose
  1614. */
  1615. MessagePrototype.encodeDelimited = function(buffer, noVerify) {
  1616. var isNew = false;
  1617. if (!buffer)
  1618. buffer = new ByteBuffer(),
  1619. isNew = true;
  1620. var enc = new ByteBuffer().LE();
  1621. T.encode(this, enc, noVerify).flip();
  1622. buffer.writeVarint32(enc.remaining());
  1623. buffer.append(enc);
  1624. return isNew ? buffer.flip() : buffer;
  1625. };
  1626. /**
  1627. * Directly encodes the message to an ArrayBuffer.
  1628. * @name ProtoBuf.Builder.Message#encodeAB
  1629. * @function
  1630. * @return {ArrayBuffer} Encoded message as ArrayBuffer
  1631. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  1632. * returns the encoded ArrayBuffer in the `encoded` property on the error.
  1633. * @expose
  1634. */
  1635. MessagePrototype.encodeAB = function() {
  1636. try {
  1637. return this.encode().toArrayBuffer();
  1638. } catch (e) {
  1639. if (e["encoded"]) e["encoded"] = e["encoded"].toArrayBuffer();
  1640. throw(e);
  1641. }
  1642. };
  1643. /**
  1644. * Returns the message as an ArrayBuffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeAB}.
  1645. * @name ProtoBuf.Builder.Message#toArrayBuffer
  1646. * @function
  1647. * @return {ArrayBuffer} Encoded message as ArrayBuffer
  1648. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  1649. * returns the encoded ArrayBuffer in the `encoded` property on the error.
  1650. * @expose
  1651. */
  1652. MessagePrototype.toArrayBuffer = MessagePrototype.encodeAB;
  1653. /**
  1654. * Directly encodes the message to a node Buffer.
  1655. * @name ProtoBuf.Builder.Message#encodeNB
  1656. * @function
  1657. * @return {!Buffer}
  1658. * @throws {Error} If the message cannot be encoded, not running under node.js or if required fields are
  1659. * missing. The later still returns the encoded node Buffer in the `encoded` property on the error.
  1660. * @expose
  1661. */
  1662. MessagePrototype.encodeNB = function() {
  1663. try {
  1664. return this.encode().toBuffer();
  1665. } catch (e) {
  1666. if (e["encoded"]) e["encoded"] = e["encoded"].toBuffer();
  1667. throw(e);
  1668. }
  1669. };
  1670. /**
  1671. * Returns the message as a node Buffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeNB}.
  1672. * @name ProtoBuf.Builder.Message#toBuffer
  1673. * @function
  1674. * @return {!Buffer}
  1675. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  1676. * returns the encoded node Buffer in the `encoded` property on the error.
  1677. * @expose
  1678. */
  1679. MessagePrototype.toBuffer = MessagePrototype.encodeNB;
  1680. /**
  1681. * Directly encodes the message to a base64 encoded string.
  1682. * @name ProtoBuf.Builder.Message#encode64
  1683. * @function
  1684. * @return {string} Base64 encoded string
  1685. * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
  1686. * still returns the encoded base64 string in the `encoded` property on the error.
  1687. * @expose
  1688. */
  1689. MessagePrototype.encode64 = function() {
  1690. try {
  1691. return this.encode().toBase64();
  1692. } catch (e) {
  1693. if (e["encoded"]) e["encoded"] = e["encoded"].toBase64();
  1694. throw(e);
  1695. }
  1696. };
  1697. /**
  1698. * Returns the message as a base64 encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encode64}.
  1699. * @name ProtoBuf.Builder.Message#toBase64
  1700. * @function
  1701. * @return {string} Base64 encoded string
  1702. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  1703. * returns the encoded base64 string in the `encoded` property on the error.
  1704. * @expose
  1705. */
  1706. MessagePrototype.toBase64 = MessagePrototype.encode64;
  1707. /**
  1708. * Directly encodes the message to a hex encoded string.
  1709. * @name ProtoBuf.Builder.Message#encodeHex
  1710. * @function
  1711. * @return {string} Hex encoded string
  1712. * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
  1713. * still returns the encoded hex string in the `encoded` property on the error.
  1714. * @expose
  1715. */
  1716. MessagePrototype.encodeHex = function() {
  1717. try {
  1718. return this.encode().toHex();
  1719. } catch (e) {
  1720. if (e["encoded"]) e["encoded"] = e["encoded"].toHex();
  1721. throw(e);
  1722. }
  1723. };
  1724. /**
  1725. * Returns the message as a hex encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encodeHex}.
  1726. * @name ProtoBuf.Builder.Message#toHex
  1727. * @function
  1728. * @return {string} Hex encoded string
  1729. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  1730. * returns the encoded hex string in the `encoded` property on the error.
  1731. * @expose
  1732. */
  1733. MessagePrototype.toHex = MessagePrototype.encodeHex;
  1734. /**
  1735. * Clones a message object or field value to a raw object.
  1736. * @param {*} obj Object to clone
  1737. * @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise
  1738. * @param {boolean} longsAsStrings Whether to encode longs as strings
  1739. * @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field
  1740. * @returns {*} Cloned object
  1741. * @inner
  1742. */
  1743. function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) {
  1744. if (obj === null || typeof obj !== 'object') {
  1745. // Convert enum values to their respective names
  1746. if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) {
  1747. var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj);
  1748. if (name !== null)
  1749. return name;
  1750. }
  1751. // Pass-through string, number, boolean, null...
  1752. return obj;
  1753. }
  1754. // Convert ByteBuffers to raw buffer or strings
  1755. if (ByteBuffer.isByteBuffer(obj))
  1756. return binaryAsBase64 ? obj.toBase64() : obj.toBuffer();
  1757. // Convert Longs to proper objects or strings
  1758. if (ProtoBuf.Long.isLong(obj))
  1759. return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj);
  1760. var clone;
  1761. // Clone arrays
  1762. if (Array.isArray(obj)) {
  1763. clone = [];
  1764. obj.forEach(function(v, k) {
  1765. clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType);
  1766. });
  1767. return clone;
  1768. }
  1769. clone = {};
  1770. // Convert maps to objects
  1771. if (obj instanceof ProtoBuf.Map) {
  1772. var it = obj.entries();
  1773. for (var e = it.next(); !e.done; e = it.next())
  1774. clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType);
  1775. return clone;
  1776. }
  1777. // Everything else is a non-null object
  1778. var type = obj.$type,
  1779. field = undefined;
  1780. for (var i in obj)
  1781. if (obj.hasOwnProperty(i)) {
  1782. if (type && (field = type.getChild(i)))
  1783. clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType);
  1784. else
  1785. clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings);
  1786. }
  1787. return clone;
  1788. }
  1789. /**
  1790. * Returns the message's raw payload.
  1791. * @param {boolean=} binaryAsBase64 Whether to include binary data as base64 strings instead of Buffers, defaults to `false`
  1792. * @param {boolean} longsAsStrings Whether to encode longs as strings
  1793. * @returns {Object.<string,*>} Raw payload
  1794. * @expose
  1795. */
  1796. MessagePrototype.toRaw = function(binaryAsBase64, longsAsStrings) {
  1797. return cloneRaw(this, !!binaryAsBase64, !!longsAsStrings, this.$type);
  1798. };
  1799. /**
  1800. * Encodes a message to JSON.
  1801. * @returns {string} JSON string
  1802. * @expose
  1803. */
  1804. MessagePrototype.encodeJSON = function() {
  1805. return JSON.stringify(
  1806. cloneRaw(this,
  1807. /* binary-as-base64 */ true,
  1808. /* longs-as-strings */ true,
  1809. this.$type
  1810. )
  1811. );
  1812. };
  1813. /**
  1814. * Decodes a message from the specified buffer or string.
  1815. * @name ProtoBuf.Builder.Message.decode
  1816. * @function
  1817. * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
  1818. * @param {(number|string)=} length Message length. Defaults to decode all the remainig data.
  1819. * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
  1820. * @return {!ProtoBuf.Builder.Message} Decoded message
  1821. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  1822. * returns the decoded message with missing fields in the `decoded` property on the error.
  1823. * @expose
  1824. * @see ProtoBuf.Builder.Message.decode64
  1825. * @see ProtoBuf.Builder.Message.decodeHex
  1826. */
  1827. Message.decode = function(buffer, length, enc) {
  1828. if (typeof length === 'string')
  1829. enc = length,
  1830. length = -1;
  1831. if (typeof buffer === 'string')
  1832. buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
  1833. else if (!ByteBuffer.isByteBuffer(buffer))
  1834. buffer = ByteBuffer.wrap(buffer); // May throw
  1835. var le = buffer.littleEndian;
  1836. try {
  1837. var msg = T.decode(buffer.LE(), length);
  1838. buffer.LE(le);
  1839. return msg;
  1840. } catch (e) {
  1841. buffer.LE(le);
  1842. throw(e);
  1843. }
  1844. };
  1845. /**
  1846. * Decodes a varint32 length-delimited message from the specified buffer or string.
  1847. * @name ProtoBuf.Builder.Message.decodeDelimited
  1848. * @function
  1849. * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
  1850. * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
  1851. * @return {ProtoBuf.Builder.Message} Decoded message or `null` if not enough bytes are available yet
  1852. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  1853. * returns the decoded message with missing fields in the `decoded` property on the error.
  1854. * @expose
  1855. */
  1856. Message.decodeDelimited = function(buffer, enc) {
  1857. if (typeof buffer === 'string')
  1858. buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
  1859. else if (!ByteBuffer.isByteBuffer(buffer))
  1860. buffer = ByteBuffer.wrap(buffer); // May throw
  1861. if (buffer.remaining() < 1)
  1862. return null;
  1863. var off = buffer.offset,
  1864. len = buffer.readVarint32();
  1865. if (buffer.remaining() < len) {
  1866. buffer.offset = off;
  1867. return null;
  1868. }
  1869. try {
  1870. var msg = T.decode(buffer.slice(buffer.offset, buffer.offset + len).LE());
  1871. buffer.offset += len;
  1872. return msg;
  1873. } catch (err) {
  1874. buffer.offset += len;
  1875. throw err;
  1876. }
  1877. };
  1878. /**
  1879. * Decodes the message from the specified base64 encoded string.
  1880. * @name ProtoBuf.Builder.Message.decode64
  1881. * @function
  1882. * @param {string} str String to decode from
  1883. * @return {!ProtoBuf.Builder.Message} Decoded message
  1884. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  1885. * returns the decoded message with missing fields in the `decoded` property on the error.
  1886. * @expose
  1887. */
  1888. Message.decode64 = function(str) {
  1889. return Message.decode(str, "base64");
  1890. };
  1891. /**
  1892. * Decodes the message from the specified hex encoded string.
  1893. * @name ProtoBuf.Builder.Message.decodeHex
  1894. * @function
  1895. * @param {string} str String to decode from
  1896. * @return {!ProtoBuf.Builder.Message} Decoded message
  1897. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  1898. * returns the decoded message with missing fields in the `decoded` property on the error.
  1899. * @expose
  1900. */
  1901. Message.decodeHex = function(str) {
  1902. return Message.decode(str, "hex");
  1903. };
  1904. /**
  1905. * Decodes the message from a JSON string.
  1906. * @name ProtoBuf.Builder.Message.decodeJSON
  1907. * @function
  1908. * @param {string} str String to decode from
  1909. * @return {!ProtoBuf.Builder.Message} Decoded message
  1910. * @throws {Error} If the message cannot be decoded or if required fields are
  1911. * missing.
  1912. * @expose
  1913. */
  1914. Message.decodeJSON = function(str) {
  1915. return new Message(JSON.parse(str));
  1916. };
  1917. // Utility
  1918. /**
  1919. * Returns a string representation of this Message.
  1920. * @name ProtoBuf.Builder.Message#toString
  1921. * @function
  1922. * @return {string} String representation as of ".Fully.Qualified.MessageName"
  1923. * @expose
  1924. */
  1925. MessagePrototype.toString = function() {
  1926. return T.toString();
  1927. };
  1928. // Properties
  1929. /**
  1930. * Message options.
  1931. * @name ProtoBuf.Builder.Message.$options
  1932. * @type {Object.<string,*>}
  1933. * @expose
  1934. */
  1935. var $optionsS; // cc needs this
  1936. /**
  1937. * Message options.
  1938. * @name ProtoBuf.Builder.Message#$options
  1939. * @type {Object.<string,*>}
  1940. * @expose
  1941. */
  1942. var $options;
  1943. /**
  1944. * Reflection type.
  1945. * @name ProtoBuf.Builder.Message.$type
  1946. * @type {!ProtoBuf.Reflect.Message}
  1947. * @expose
  1948. */
  1949. var $typeS;
  1950. /**
  1951. * Reflection type.
  1952. * @name ProtoBuf.Builder.Message#$type
  1953. * @type {!ProtoBuf.Reflect.Message}
  1954. * @expose
  1955. */
  1956. var $type;
  1957. if (Object.defineProperty)
  1958. Object.defineProperty(Message, '$options', { "value": T.buildOpt() }),
  1959. Object.defineProperty(MessagePrototype, "$options", { "value": Message["$options"] }),
  1960. Object.defineProperty(Message, "$type", { "value": T }),
  1961. Object.defineProperty(MessagePrototype, "$type", { "value": T });
  1962. return Message;
  1963. })(ProtoBuf, this);
  1964. // Static enums and prototyped sub-messages / cached collections
  1965. this._fields = [];
  1966. this._fieldsById = {};
  1967. this._fieldsByName = {};
  1968. this._oneofsByName = {};
  1969. for (var i=0, k=this.children.length, child; i<k; i++) {
  1970. child = this.children[i];
  1971. if (child instanceof Enum || child instanceof Message || child instanceof Service) {
  1972. if (clazz.hasOwnProperty(child.name))
  1973. throw Error("Illegal reflect child of "+this.toString(true)+": "+child.toString(true)+" cannot override static property '"+child.name+"'");
  1974. clazz[child.name] = child.build();
  1975. } else if (child instanceof Message.Field)
  1976. child.build(),
  1977. this._fields.push(child),
  1978. this._fieldsById[child.id] = child,
  1979. this._fieldsByName[child.name] = child;
  1980. else if (child instanceof Message.OneOf) {
  1981. this._oneofsByName[child.name] = child;
  1982. }
  1983. else if (!(child instanceof Message.OneOf) && !(child instanceof Extension)) // Not built
  1984. throw Error("Illegal reflect child of "+this.toString(true)+": "+this.children[i].toString(true));
  1985. }
  1986. return this.clazz = clazz;
  1987. };
  1988. /**
  1989. * Encodes a runtime message's contents to the specified buffer.
  1990. * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
  1991. * @param {ByteBuffer} buffer ByteBuffer to write to
  1992. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  1993. * @return {ByteBuffer} The ByteBuffer for chaining
  1994. * @throws {Error} If required fields are missing or the message cannot be encoded for another reason
  1995. * @expose
  1996. */
  1997. MessagePrototype.encode = function(message, buffer, noVerify) {
  1998. var fieldMissing = null,
  1999. field;
  2000. for (var i=0, k=this._fields.length, val; i<k; ++i) {
  2001. field = this._fields[i];
  2002. val = message[field.name];
  2003. if (field.required && val === null) {
  2004. if (fieldMissing === null)
  2005. fieldMissing = field;
  2006. } else
  2007. field.encode(noVerify ? val : field.verifyValue(val), buffer, message);
  2008. }
  2009. if (fieldMissing !== null) {
  2010. var err = Error("Missing at least one required field for "+this.toString(true)+": "+fieldMissing);
  2011. err["encoded"] = buffer; // Still expose what we got
  2012. throw(err);
  2013. }
  2014. return buffer;
  2015. };
  2016. /**
  2017. * Calculates a runtime message's byte length.
  2018. * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
  2019. * @returns {number} Byte length
  2020. * @throws {Error} If required fields are missing or the message cannot be calculated for another reason
  2021. * @expose
  2022. */
  2023. MessagePrototype.calculate = function(message) {
  2024. for (var n=0, i=0, k=this._fields.length, field, val; i<k; ++i) {
  2025. field = this._fields[i];
  2026. val = message[field.name];
  2027. if (field.required && val === null)
  2028. throw Error("Missing at least one required field for "+this.toString(true)+": "+field);
  2029. else
  2030. n += field.calculate(val, message);
  2031. }
  2032. return n;
  2033. };
  2034. /**
  2035. * Skips all data until the end of the specified group has been reached.
  2036. * @param {number} expectedId Expected GROUPEND id
  2037. * @param {!ByteBuffer} buf ByteBuffer
  2038. * @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached
  2039. * @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch)
  2040. * @inner
  2041. */
  2042. function skipTillGroupEnd(expectedId, buf) {
  2043. var tag = buf.readVarint32(), // Throws on OOB
  2044. wireType = tag & 0x07,
  2045. id = tag >>> 3;
  2046. switch (wireType) {
  2047. case ProtoBuf.WIRE_TYPES.VARINT:
  2048. do tag = buf.readUint8();
  2049. while ((tag & 0x80) === 0x80);
  2050. break;
  2051. case ProtoBuf.WIRE_TYPES.BITS64:
  2052. buf.offset += 8;
  2053. break;
  2054. case ProtoBuf.WIRE_TYPES.LDELIM:
  2055. tag = buf.readVarint32(); // reads the varint
  2056. buf.offset += tag; // skips n bytes
  2057. break;
  2058. case ProtoBuf.WIRE_TYPES.STARTGROUP:
  2059. skipTillGroupEnd(id, buf);
  2060. break;
  2061. case ProtoBuf.WIRE_TYPES.ENDGROUP:
  2062. if (id === expectedId)
  2063. return false;
  2064. else
  2065. throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)");
  2066. case ProtoBuf.WIRE_TYPES.BITS32:
  2067. buf.offset += 4;
  2068. break;
  2069. default:
  2070. throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType);
  2071. }
  2072. return true;
  2073. }
  2074. /**
  2075. * Decodes an encoded message and returns the decoded message.
  2076. * @param {ByteBuffer} buffer ByteBuffer to decode from
  2077. * @param {number=} length Message length. Defaults to decode all remaining data.
  2078. * @param {number=} expectedGroupEndId Expected GROUPEND id if this is a legacy group
  2079. * @return {ProtoBuf.Builder.Message} Decoded message
  2080. * @throws {Error} If the message cannot be decoded
  2081. * @expose
  2082. */
  2083. MessagePrototype.decode = function(buffer, length, expectedGroupEndId) {
  2084. if (typeof length !== 'number')
  2085. length = -1;
  2086. var start = buffer.offset,
  2087. msg = new (this.clazz)(),
  2088. tag, wireType, id, field;
  2089. while (buffer.offset < start+length || (length === -1 && buffer.remaining() > 0)) {
  2090. tag = buffer.readVarint32();
  2091. wireType = tag & 0x07;
  2092. id = tag >>> 3;
  2093. if (wireType === ProtoBuf.WIRE_TYPES.ENDGROUP) {
  2094. if (id !== expectedGroupEndId)
  2095. throw Error("Illegal group end indicator for "+this.toString(true)+": "+id+" ("+(expectedGroupEndId ? expectedGroupEndId+" expected" : "not a group")+")");
  2096. break;
  2097. }
  2098. if (!(field = this._fieldsById[id])) {
  2099. // "messages created by your new code can be parsed by your old code: old binaries simply ignore the new field when parsing."
  2100. switch (wireType) {
  2101. case ProtoBuf.WIRE_TYPES.VARINT:
  2102. buffer.readVarint32();
  2103. break;
  2104. case ProtoBuf.WIRE_TYPES.BITS32:
  2105. buffer.offset += 4;
  2106. break;
  2107. case ProtoBuf.WIRE_TYPES.BITS64:
  2108. buffer.offset += 8;
  2109. break;
  2110. case ProtoBuf.WIRE_TYPES.LDELIM:
  2111. var len = buffer.readVarint32();
  2112. buffer.offset += len;
  2113. break;
  2114. case ProtoBuf.WIRE_TYPES.STARTGROUP:
  2115. while (skipTillGroupEnd(id, buffer)) {}
  2116. break;
  2117. default:
  2118. throw Error("Illegal wire type for unknown field "+id+" in "+this.toString(true)+"#decode: "+wireType);
  2119. }
  2120. continue;
  2121. }
  2122. if (field.repeated && !field.options["packed"]) {
  2123. msg[field.name].push(field.decode(wireType, buffer));
  2124. } else if (field.map) {
  2125. var keyval = field.decode(wireType, buffer);
  2126. msg[field.name].set(keyval[0], keyval[1]);
  2127. } else {
  2128. msg[field.name] = field.decode(wireType, buffer);
  2129. if (field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
  2130. var currentField = msg[field.oneof.name]; // Virtual field references currently set field
  2131. if (currentField !== null && currentField !== field.name)
  2132. msg[currentField] = null; // Clear currently set field
  2133. msg[field.oneof.name] = field.name; // Point virtual field at this field
  2134. }
  2135. }
  2136. }
  2137. // Check if all required fields are present and set default values for optional fields that are not
  2138. for (var i=0, k=this._fields.length; i<k; ++i) {
  2139. field = this._fields[i];
  2140. if (msg[field.name] === null) {
  2141. if (this.syntax === "proto3") { // Proto3 sets default values by specification
  2142. msg[field.name] = field.defaultValue;
  2143. } else if (field.required) {
  2144. var err = Error("Missing at least one required field for " + this.toString(true) + ": " + field.name);
  2145. err["decoded"] = msg; // Still expose what we got
  2146. throw(err);
  2147. } else if (ProtoBuf.populateDefaults && field.defaultValue !== null)
  2148. msg[field.name] = field.defaultValue;
  2149. }
  2150. }
  2151. return msg;
  2152. };
  2153. /**
  2154. * @alias ProtoBuf.Reflect.Message
  2155. * @expose
  2156. */
  2157. Reflect.Message = Message;
  2158. /**
  2159. * Constructs a new Message Field.
  2160. * @exports ProtoBuf.Reflect.Message.Field
  2161. * @param {!ProtoBuf.Builder} builder Builder reference
  2162. * @param {!ProtoBuf.Reflect.Message} message Message reference
  2163. * @param {string} rule Rule, one of requried, optional, repeated
  2164. * @param {string?} keytype Key data type, if any.
  2165. * @param {string} type Data type, e.g. int32
  2166. * @param {string} name Field name
  2167. * @param {number} id Unique field id
  2168. * @param {Object.<string,*>=} options Options
  2169. * @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf
  2170. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  2171. * @constructor
  2172. * @extends ProtoBuf.Reflect.T
  2173. */
  2174. var Field = function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) {
  2175. T.call(this, builder, message, name);
  2176. /**
  2177. * @override
  2178. */
  2179. this.className = "Message.Field";
  2180. /**
  2181. * Message field required flag.
  2182. * @type {boolean}
  2183. * @expose
  2184. */
  2185. this.required = rule === "required";
  2186. /**
  2187. * Message field repeated flag.
  2188. * @type {boolean}
  2189. * @expose
  2190. */
  2191. this.repeated = rule === "repeated";
  2192. /**
  2193. * Message field map flag.
  2194. * @type {boolean}
  2195. * @expose
  2196. */
  2197. this.map = rule === "map";
  2198. /**
  2199. * Message field key type. Type reference string if unresolved, protobuf
  2200. * type if resolved. Valid only if this.map === true, null otherwise.
  2201. * @type {string|{name: string, wireType: number}|null}
  2202. * @expose
  2203. */
  2204. this.keyType = keytype || null;
  2205. /**
  2206. * Message field type. Type reference string if unresolved, protobuf type if
  2207. * resolved. In a map field, this is the value type.
  2208. * @type {string|{name: string, wireType: number}}
  2209. * @expose
  2210. */
  2211. this.type = type;
  2212. /**
  2213. * Resolved type reference inside the global namespace.
  2214. * @type {ProtoBuf.Reflect.T|null}
  2215. * @expose
  2216. */
  2217. this.resolvedType = null;
  2218. /**
  2219. * Unique message field id.
  2220. * @type {number}
  2221. * @expose
  2222. */
  2223. this.id = id;
  2224. /**
  2225. * Message field options.
  2226. * @type {!Object.<string,*>}
  2227. * @dict
  2228. * @expose
  2229. */
  2230. this.options = options || {};
  2231. /**
  2232. * Default value.
  2233. * @type {*}
  2234. * @expose
  2235. */
  2236. this.defaultValue = null;
  2237. /**
  2238. * Enclosing OneOf.
  2239. * @type {?ProtoBuf.Reflect.Message.OneOf}
  2240. * @expose
  2241. */
  2242. this.oneof = oneof || null;
  2243. /**
  2244. * Syntax level of this definition (e.g., proto3).
  2245. * @type {string}
  2246. * @expose
  2247. */
  2248. this.syntax = syntax || 'proto2';
  2249. /**
  2250. * Original field name.
  2251. * @type {string}
  2252. * @expose
  2253. */
  2254. this.originalName = this.name; // Used to revert camelcase transformation on naming collisions
  2255. /**
  2256. * Element implementation. Created in build() after types are resolved.
  2257. * @type {ProtoBuf.Element}
  2258. * @expose
  2259. */
  2260. this.element = null;
  2261. /**
  2262. * Key element implementation, for map fields. Created in build() after
  2263. * types are resolved.
  2264. * @type {ProtoBuf.Element}
  2265. * @expose
  2266. */
  2267. this.keyElement = null;
  2268. // Convert field names to camel case notation if the override is set
  2269. if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField))
  2270. this.name = ProtoBuf.Util.toCamelCase(this.name);
  2271. };
  2272. /**
  2273. * @alias ProtoBuf.Reflect.Message.Field.prototype
  2274. * @inner
  2275. */
  2276. var FieldPrototype = Field.prototype = Object.create(T.prototype);
  2277. /**
  2278. * Builds the field.
  2279. * @override
  2280. * @expose
  2281. */
  2282. FieldPrototype.build = function() {
  2283. this.element = new Element(this.type, this.resolvedType, false, this.syntax, this.name);
  2284. if (this.map)
  2285. this.keyElement = new Element(this.keyType, undefined, true, this.syntax, this.name);
  2286. // In proto3, fields do not have field presence, and every field is set to
  2287. // its type's default value ("", 0, 0.0, or false).
  2288. if (this.syntax === 'proto3' && !this.repeated && !this.map)
  2289. this.defaultValue = Element.defaultFieldValue(this.type);
  2290. // Otherwise, default values are present when explicitly specified
  2291. else if (typeof this.options['default'] !== 'undefined')
  2292. this.defaultValue = this.verifyValue(this.options['default']);
  2293. };
  2294. /**
  2295. * Checks if the given value can be set for this field.
  2296. * @param {*} value Value to check
  2297. * @param {boolean=} skipRepeated Whether to skip the repeated value check or not. Defaults to false.
  2298. * @return {*} Verified, maybe adjusted, value
  2299. * @throws {Error} If the value cannot be set for this field
  2300. * @expose
  2301. */
  2302. FieldPrototype.verifyValue = function(value, skipRepeated) {
  2303. skipRepeated = skipRepeated || false;
  2304. var self = this;
  2305. function fail(val, msg) {
  2306. throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
  2307. }
  2308. if (value === null) { // NULL values for optional fields
  2309. if (this.required)
  2310. fail(typeof value, "required");
  2311. if (this.syntax === 'proto3' && this.type !== ProtoBuf.TYPES["message"])
  2312. fail(typeof value, "proto3 field without field presence cannot be null");
  2313. return null;
  2314. }
  2315. var i;
  2316. if (this.repeated && !skipRepeated) { // Repeated values as arrays
  2317. if (!Array.isArray(value))
  2318. value = [value];
  2319. var res = [];
  2320. for (i=0; i<value.length; i++)
  2321. res.push(this.element.verifyValue(value[i]));
  2322. return res;
  2323. }
  2324. if (this.map && !skipRepeated) { // Map values as objects
  2325. if (!(value instanceof ProtoBuf.Map)) {
  2326. // If not already a Map, attempt to convert.
  2327. if (!(value instanceof Object)) {
  2328. fail(typeof value,
  2329. "expected ProtoBuf.Map or raw object for map field");
  2330. }
  2331. return new ProtoBuf.Map(this, value);
  2332. } else {
  2333. return value;
  2334. }
  2335. }
  2336. // All non-repeated fields expect no array
  2337. if (!this.repeated && Array.isArray(value))
  2338. fail(typeof value, "no array expected");
  2339. return this.element.verifyValue(value);
  2340. };
  2341. /**
  2342. * Determines whether the field will have a presence on the wire given its
  2343. * value.
  2344. * @param {*} value Verified field value
  2345. * @param {!ProtoBuf.Builder.Message} message Runtime message
  2346. * @return {boolean} Whether the field will be present on the wire
  2347. */
  2348. FieldPrototype.hasWirePresence = function(value, message) {
  2349. if (this.syntax !== 'proto3')
  2350. return (value !== null);
  2351. if (this.oneof && message[this.oneof.name] === this.name)
  2352. return true;
  2353. switch (this.type) {
  2354. case ProtoBuf.TYPES["int32"]:
  2355. case ProtoBuf.TYPES["sint32"]:
  2356. case ProtoBuf.TYPES["sfixed32"]:
  2357. case ProtoBuf.TYPES["uint32"]:
  2358. case ProtoBuf.TYPES["fixed32"]:
  2359. return value !== 0;
  2360. case ProtoBuf.TYPES["int64"]:
  2361. case ProtoBuf.TYPES["sint64"]:
  2362. case ProtoBuf.TYPES["sfixed64"]:
  2363. case ProtoBuf.TYPES["uint64"]:
  2364. case ProtoBuf.TYPES["fixed64"]:
  2365. return value.low !== 0 || value.high !== 0;
  2366. case ProtoBuf.TYPES["bool"]:
  2367. return value;
  2368. case ProtoBuf.TYPES["float"]:
  2369. case ProtoBuf.TYPES["double"]:
  2370. return value !== 0.0;
  2371. case ProtoBuf.TYPES["string"]:
  2372. return value.length > 0;
  2373. case ProtoBuf.TYPES["bytes"]:
  2374. return value.remaining() > 0;
  2375. case ProtoBuf.TYPES["enum"]:
  2376. return value !== 0;
  2377. case ProtoBuf.TYPES["message"]:
  2378. return value !== null;
  2379. default:
  2380. return true;
  2381. }
  2382. };
  2383. /**
  2384. * Encodes the specified field value to the specified buffer.
  2385. * @param {*} value Verified field value
  2386. * @param {ByteBuffer} buffer ByteBuffer to encode to
  2387. * @param {!ProtoBuf.Builder.Message} message Runtime message
  2388. * @return {ByteBuffer} The ByteBuffer for chaining
  2389. * @throws {Error} If the field cannot be encoded
  2390. * @expose
  2391. */
  2392. FieldPrototype.encode = function(value, buffer, message) {
  2393. if (this.type === null || typeof this.type !== 'object')
  2394. throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
  2395. if (value === null || (this.repeated && value.length == 0))
  2396. return buffer; // Optional omitted
  2397. try {
  2398. if (this.repeated) {
  2399. var i;
  2400. // "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire
  2401. // types) can be declared 'packed'."
  2402. if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  2403. // "All of the elements of the field are packed into a single key-value pair with wire type 2
  2404. // (length-delimited). Each element is encoded the same way it would be normally, except without a
  2405. // tag preceding it."
  2406. buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  2407. buffer.ensureCapacity(buffer.offset += 1); // We do not know the length yet, so let's assume a varint of length 1
  2408. var start = buffer.offset; // Remember where the contents begin
  2409. for (i=0; i<value.length; i++)
  2410. this.element.encodeValue(this.id, value[i], buffer);
  2411. var len = buffer.offset-start,
  2412. varintLen = ByteBuffer.calculateVarint32(len);
  2413. if (varintLen > 1) { // We need to move the contents
  2414. var contents = buffer.slice(start, buffer.offset);
  2415. start += varintLen-1;
  2416. buffer.offset = start;
  2417. buffer.append(contents);
  2418. }
  2419. buffer.writeVarint32(len, start-varintLen);
  2420. } else {
  2421. // "If your message definition has repeated elements (without the [packed=true] option), the encoded
  2422. // message has zero or more key-value pairs with the same tag number"
  2423. for (i=0; i<value.length; i++)
  2424. buffer.writeVarint32((this.id << 3) | this.type.wireType),
  2425. this.element.encodeValue(this.id, value[i], buffer);
  2426. }
  2427. } else if (this.map) {
  2428. // Write out each map entry as a submessage.
  2429. value.forEach(function(val, key, m) {
  2430. // Compute the length of the submessage (key, val) pair.
  2431. var length =
  2432. ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
  2433. this.keyElement.calculateLength(1, key) +
  2434. ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
  2435. this.element.calculateLength(2, val);
  2436. // Submessage with wire type of length-delimited.
  2437. buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  2438. buffer.writeVarint32(length);
  2439. // Write out the key and val.
  2440. buffer.writeVarint32((1 << 3) | this.keyType.wireType);
  2441. this.keyElement.encodeValue(1, key, buffer);
  2442. buffer.writeVarint32((2 << 3) | this.type.wireType);
  2443. this.element.encodeValue(2, val, buffer);
  2444. }, this);
  2445. } else {
  2446. if (this.hasWirePresence(value, message)) {
  2447. buffer.writeVarint32((this.id << 3) | this.type.wireType);
  2448. this.element.encodeValue(this.id, value, buffer);
  2449. }
  2450. }
  2451. } catch (e) {
  2452. throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
  2453. }
  2454. return buffer;
  2455. };
  2456. /**
  2457. * Calculates the length of this field's value on the network level.
  2458. * @param {*} value Field value
  2459. * @param {!ProtoBuf.Builder.Message} message Runtime message
  2460. * @returns {number} Byte length
  2461. * @expose
  2462. */
  2463. FieldPrototype.calculate = function(value, message) {
  2464. value = this.verifyValue(value); // May throw
  2465. if (this.type === null || typeof this.type !== 'object')
  2466. throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
  2467. if (value === null || (this.repeated && value.length == 0))
  2468. return 0; // Optional omitted
  2469. var n = 0;
  2470. try {
  2471. if (this.repeated) {
  2472. var i, ni;
  2473. if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  2474. n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  2475. ni = 0;
  2476. for (i=0; i<value.length; i++)
  2477. ni += this.element.calculateLength(this.id, value[i]);
  2478. n += ByteBuffer.calculateVarint32(ni);
  2479. n += ni;
  2480. } else {
  2481. for (i=0; i<value.length; i++)
  2482. n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType),
  2483. n += this.element.calculateLength(this.id, value[i]);
  2484. }
  2485. } else if (this.map) {
  2486. // Each map entry becomes a submessage.
  2487. value.forEach(function(val, key, m) {
  2488. // Compute the length of the submessage (key, val) pair.
  2489. var length =
  2490. ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
  2491. this.keyElement.calculateLength(1, key) +
  2492. ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
  2493. this.element.calculateLength(2, val);
  2494. n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  2495. n += ByteBuffer.calculateVarint32(length);
  2496. n += length;
  2497. }, this);
  2498. } else {
  2499. if (this.hasWirePresence(value, message)) {
  2500. n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType);
  2501. n += this.element.calculateLength(this.id, value);
  2502. }
  2503. }
  2504. } catch (e) {
  2505. throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
  2506. }
  2507. return n;
  2508. };
  2509. /**
  2510. * Decode the field value from the specified buffer.
  2511. * @param {number} wireType Leading wire type
  2512. * @param {ByteBuffer} buffer ByteBuffer to decode from
  2513. * @param {boolean=} skipRepeated Whether to skip the repeated check or not. Defaults to false.
  2514. * @return {*} Decoded value: array for packed repeated fields, [key, value] for
  2515. * map fields, or an individual value otherwise.
  2516. * @throws {Error} If the field cannot be decoded
  2517. * @expose
  2518. */
  2519. FieldPrototype.decode = function(wireType, buffer, skipRepeated) {
  2520. var value, nBytes;
  2521. // We expect wireType to match the underlying type's wireType unless we see
  2522. // a packed repeated field, or unless this is a map field.
  2523. var wireTypeOK =
  2524. (!this.map && wireType == this.type.wireType) ||
  2525. (!skipRepeated && this.repeated && this.options["packed"] &&
  2526. wireType == ProtoBuf.WIRE_TYPES.LDELIM) ||
  2527. (this.map && wireType == ProtoBuf.WIRE_TYPES.LDELIM);
  2528. if (!wireTypeOK)
  2529. throw Error("Illegal wire type for field "+this.toString(true)+": "+wireType+" ("+this.type.wireType+" expected)");
  2530. // Handle packed repeated fields.
  2531. if (wireType == ProtoBuf.WIRE_TYPES.LDELIM && this.repeated && this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  2532. if (!skipRepeated) {
  2533. nBytes = buffer.readVarint32();
  2534. nBytes = buffer.offset + nBytes; // Limit
  2535. var values = [];
  2536. while (buffer.offset < nBytes)
  2537. values.push(this.decode(this.type.wireType, buffer, true));
  2538. return values;
  2539. }
  2540. // Read the next value otherwise...
  2541. }
  2542. // Handle maps.
  2543. if (this.map) {
  2544. // Read one (key, value) submessage, and return [key, value]
  2545. var key = Element.defaultFieldValue(this.keyType);
  2546. value = Element.defaultFieldValue(this.type);
  2547. // Read the length
  2548. nBytes = buffer.readVarint32();
  2549. if (buffer.remaining() < nBytes)
  2550. throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
  2551. // Get a sub-buffer of this key/value submessage
  2552. var msgbuf = buffer.clone();
  2553. msgbuf.limit = msgbuf.offset + nBytes;
  2554. buffer.offset += nBytes;
  2555. while (msgbuf.remaining() > 0) {
  2556. var tag = msgbuf.readVarint32();
  2557. wireType = tag & 0x07;
  2558. var id = tag >>> 3;
  2559. if (id === 1) {
  2560. key = this.keyElement.decode(msgbuf, wireType, id);
  2561. } else if (id === 2) {
  2562. value = this.element.decode(msgbuf, wireType, id);
  2563. } else {
  2564. throw Error("Unexpected tag in map field key/value submessage");
  2565. }
  2566. }
  2567. return [key, value];
  2568. }
  2569. // Handle singular and non-packed repeated field values.
  2570. return this.element.decode(buffer, wireType, this.id);
  2571. };
  2572. /**
  2573. * @alias ProtoBuf.Reflect.Message.Field
  2574. * @expose
  2575. */
  2576. Reflect.Message.Field = Field;
  2577. /**
  2578. * Constructs a new Message ExtensionField.
  2579. * @exports ProtoBuf.Reflect.Message.ExtensionField
  2580. * @param {!ProtoBuf.Builder} builder Builder reference
  2581. * @param {!ProtoBuf.Reflect.Message} message Message reference
  2582. * @param {string} rule Rule, one of requried, optional, repeated
  2583. * @param {string} type Data type, e.g. int32
  2584. * @param {string} name Field name
  2585. * @param {number} id Unique field id
  2586. * @param {!Object.<string,*>=} options Options
  2587. * @constructor
  2588. * @extends ProtoBuf.Reflect.Message.Field
  2589. */
  2590. var ExtensionField = function(builder, message, rule, type, name, id, options) {
  2591. Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options);
  2592. /**
  2593. * Extension reference.
  2594. * @type {!ProtoBuf.Reflect.Extension}
  2595. * @expose
  2596. */
  2597. this.extension;
  2598. };
  2599. // Extends Field
  2600. ExtensionField.prototype = Object.create(Field.prototype);
  2601. /**
  2602. * @alias ProtoBuf.Reflect.Message.ExtensionField
  2603. * @expose
  2604. */
  2605. Reflect.Message.ExtensionField = ExtensionField;
  2606. /**
  2607. * Constructs a new Message OneOf.
  2608. * @exports ProtoBuf.Reflect.Message.OneOf
  2609. * @param {!ProtoBuf.Builder} builder Builder reference
  2610. * @param {!ProtoBuf.Reflect.Message} message Message reference
  2611. * @param {string} name OneOf name
  2612. * @constructor
  2613. * @extends ProtoBuf.Reflect.T
  2614. */
  2615. var OneOf = function(builder, message, name) {
  2616. T.call(this, builder, message, name);
  2617. /**
  2618. * Enclosed fields.
  2619. * @type {!Array.<!ProtoBuf.Reflect.Message.Field>}
  2620. * @expose
  2621. */
  2622. this.fields = [];
  2623. };
  2624. /**
  2625. * @alias ProtoBuf.Reflect.Message.OneOf
  2626. * @expose
  2627. */
  2628. Reflect.Message.OneOf = OneOf;
  2629. /**
  2630. * Constructs a new Enum.
  2631. * @exports ProtoBuf.Reflect.Enum
  2632. * @param {!ProtoBuf.Builder} builder Builder reference
  2633. * @param {!ProtoBuf.Reflect.T} parent Parent Reflect object
  2634. * @param {string} name Enum name
  2635. * @param {Object.<string,*>=} options Enum options
  2636. * @param {string?} syntax The syntax level (e.g., proto3)
  2637. * @constructor
  2638. * @extends ProtoBuf.Reflect.Namespace
  2639. */
  2640. var Enum = function(builder, parent, name, options, syntax) {
  2641. Namespace.call(this, builder, parent, name, options, syntax);
  2642. /**
  2643. * @override
  2644. */
  2645. this.className = "Enum";
  2646. /**
  2647. * Runtime enum object.
  2648. * @type {Object.<string,number>|null}
  2649. * @expose
  2650. */
  2651. this.object = null;
  2652. };
  2653. /**
  2654. * Gets the string name of an enum value.
  2655. * @param {!ProtoBuf.Builder.Enum} enm Runtime enum
  2656. * @param {number} value Enum value
  2657. * @returns {?string} Name or `null` if not present
  2658. * @expose
  2659. */
  2660. Enum.getName = function(enm, value) {
  2661. var keys = Object.keys(enm);
  2662. for (var i=0, key; i<keys.length; ++i)
  2663. if (enm[key = keys[i]] === value)
  2664. return key;
  2665. return null;
  2666. };
  2667. /**
  2668. * @alias ProtoBuf.Reflect.Enum.prototype
  2669. * @inner
  2670. */
  2671. var EnumPrototype = Enum.prototype = Object.create(Namespace.prototype);
  2672. /**
  2673. * Builds this enum and returns the runtime counterpart.
  2674. * @param {boolean} rebuild Whether to rebuild or not, defaults to false
  2675. * @returns {!Object.<string,number>}
  2676. * @expose
  2677. */
  2678. EnumPrototype.build = function(rebuild) {
  2679. if (this.object && !rebuild)
  2680. return this.object;
  2681. var enm = new ProtoBuf.Builder.Enum(),
  2682. values = this.getChildren(Enum.Value);
  2683. for (var i=0, k=values.length; i<k; ++i)
  2684. enm[values[i]['name']] = values[i]['id'];
  2685. if (Object.defineProperty)
  2686. Object.defineProperty(enm, '$options', {
  2687. "value": this.buildOpt(),
  2688. "enumerable": false
  2689. });
  2690. return this.object = enm;
  2691. };
  2692. /**
  2693. * @alias ProtoBuf.Reflect.Enum
  2694. * @expose
  2695. */
  2696. Reflect.Enum = Enum;
  2697. /**
  2698. * Constructs a new Enum Value.
  2699. * @exports ProtoBuf.Reflect.Enum.Value
  2700. * @param {!ProtoBuf.Builder} builder Builder reference
  2701. * @param {!ProtoBuf.Reflect.Enum} enm Enum reference
  2702. * @param {string} name Field name
  2703. * @param {number} id Unique field id
  2704. * @constructor
  2705. * @extends ProtoBuf.Reflect.T
  2706. */
  2707. var Value = function(builder, enm, name, id) {
  2708. T.call(this, builder, enm, name);
  2709. /**
  2710. * @override
  2711. */
  2712. this.className = "Enum.Value";
  2713. /**
  2714. * Unique enum value id.
  2715. * @type {number}
  2716. * @expose
  2717. */
  2718. this.id = id;
  2719. };
  2720. // Extends T
  2721. Value.prototype = Object.create(T.prototype);
  2722. /**
  2723. * @alias ProtoBuf.Reflect.Enum.Value
  2724. * @expose
  2725. */
  2726. Reflect.Enum.Value = Value;
  2727. /**
  2728. * An extension (field).
  2729. * @exports ProtoBuf.Reflect.Extension
  2730. * @constructor
  2731. * @param {!ProtoBuf.Builder} builder Builder reference
  2732. * @param {!ProtoBuf.Reflect.T} parent Parent object
  2733. * @param {string} name Object name
  2734. * @param {!ProtoBuf.Reflect.Message.Field} field Extension field
  2735. */
  2736. var Extension = function(builder, parent, name, field) {
  2737. T.call(this, builder, parent, name);
  2738. /**
  2739. * Extended message field.
  2740. * @type {!ProtoBuf.Reflect.Message.Field}
  2741. * @expose
  2742. */
  2743. this.field = field;
  2744. };
  2745. // Extends T
  2746. Extension.prototype = Object.create(T.prototype);
  2747. /**
  2748. * @alias ProtoBuf.Reflect.Extension
  2749. * @expose
  2750. */
  2751. Reflect.Extension = Extension;
  2752. /**
  2753. * Constructs a new Service.
  2754. * @exports ProtoBuf.Reflect.Service
  2755. * @param {!ProtoBuf.Builder} builder Builder reference
  2756. * @param {!ProtoBuf.Reflect.Namespace} root Root
  2757. * @param {string} name Service name
  2758. * @param {Object.<string,*>=} options Options
  2759. * @constructor
  2760. * @extends ProtoBuf.Reflect.Namespace
  2761. */
  2762. var Service = function(builder, root, name, options) {
  2763. Namespace.call(this, builder, root, name, options);
  2764. /**
  2765. * @override
  2766. */
  2767. this.className = "Service";
  2768. /**
  2769. * Built runtime service class.
  2770. * @type {?function(new:ProtoBuf.Builder.Service)}
  2771. */
  2772. this.clazz = null;
  2773. };
  2774. /**
  2775. * @alias ProtoBuf.Reflect.Service.prototype
  2776. * @inner
  2777. */
  2778. var ServicePrototype = Service.prototype = Object.create(Namespace.prototype);
  2779. /**
  2780. * Builds the service and returns the runtime counterpart, which is a fully functional class.
  2781. * @see ProtoBuf.Builder.Service
  2782. * @param {boolean=} rebuild Whether to rebuild or not
  2783. * @return {Function} Service class
  2784. * @throws {Error} If the message cannot be built
  2785. * @expose
  2786. */
  2787. ServicePrototype.build = function(rebuild) {
  2788. if (this.clazz && !rebuild)
  2789. return this.clazz;
  2790. // Create the runtime Service class in its own scope
  2791. return this.clazz = (function(ProtoBuf, T) {
  2792. /**
  2793. * Constructs a new runtime Service.
  2794. * @name ProtoBuf.Builder.Service
  2795. * @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message
  2796. * @class Barebone of all runtime services.
  2797. * @constructor
  2798. * @throws {Error} If the service cannot be created
  2799. */
  2800. var Service = function(rpcImpl) {
  2801. ProtoBuf.Builder.Service.call(this);
  2802. /**
  2803. * Service implementation.
  2804. * @name ProtoBuf.Builder.Service#rpcImpl
  2805. * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))}
  2806. * @expose
  2807. */
  2808. this.rpcImpl = rpcImpl || function(name, msg, callback) {
  2809. // This is what a user has to implement: A function receiving the method name, the actual message to
  2810. // send (type checked) and the callback that's either provided with the error as its first
  2811. // argument or null and the actual response message.
  2812. setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async!
  2813. };
  2814. };
  2815. /**
  2816. * @alias ProtoBuf.Builder.Service.prototype
  2817. * @inner
  2818. */
  2819. var ServicePrototype = Service.prototype = Object.create(ProtoBuf.Builder.Service.prototype);
  2820. /**
  2821. * Asynchronously performs an RPC call using the given RPC implementation.
  2822. * @name ProtoBuf.Builder.Service.[Method]
  2823. * @function
  2824. * @param {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} rpcImpl RPC implementation
  2825. * @param {ProtoBuf.Builder.Message} req Request
  2826. * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
  2827. * the error if any and the response either as a pre-parsed message or as its raw bytes
  2828. * @abstract
  2829. */
  2830. /**
  2831. * Asynchronously performs an RPC call using the instance's RPC implementation.
  2832. * @name ProtoBuf.Builder.Service#[Method]
  2833. * @function
  2834. * @param {ProtoBuf.Builder.Message} req Request
  2835. * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
  2836. * the error if any and the response either as a pre-parsed message or as its raw bytes
  2837. * @abstract
  2838. */
  2839. var rpc = T.getChildren(ProtoBuf.Reflect.Service.RPCMethod);
  2840. for (var i=0; i<rpc.length; i++) {
  2841. (function(method) {
  2842. // service#Method(message, callback)
  2843. ServicePrototype[method.name] = function(req, callback) {
  2844. try {
  2845. try {
  2846. // If given as a buffer, decode the request. Will throw a TypeError if not a valid buffer.
  2847. req = method.resolvedRequestType.clazz.decode(ByteBuffer.wrap(req));
  2848. } catch (err) {
  2849. if (!(err instanceof TypeError))
  2850. throw err;
  2851. }
  2852. if (req === null || typeof req !== 'object')
  2853. throw Error("Illegal arguments");
  2854. if (!(req instanceof method.resolvedRequestType.clazz))
  2855. req = new method.resolvedRequestType.clazz(req);
  2856. this.rpcImpl(method.fqn(), req, function(err, res) { // Assumes that this is properly async
  2857. if (err) {
  2858. callback(err);
  2859. return;
  2860. }
  2861. // Coalesce to empty string when service response has empty content
  2862. if (res === null)
  2863. res = ''
  2864. try { res = method.resolvedResponseType.clazz.decode(res); } catch (notABuffer) {}
  2865. if (!res || !(res instanceof method.resolvedResponseType.clazz)) {
  2866. callback(Error("Illegal response type received in service method "+ T.name+"#"+method.name));
  2867. return;
  2868. }
  2869. callback(null, res);
  2870. });
  2871. } catch (err) {
  2872. setTimeout(callback.bind(this, err), 0);
  2873. }
  2874. };
  2875. // Service.Method(rpcImpl, message, callback)
  2876. Service[method.name] = function(rpcImpl, req, callback) {
  2877. new Service(rpcImpl)[method.name](req, callback);
  2878. };
  2879. if (Object.defineProperty)
  2880. Object.defineProperty(Service[method.name], "$options", { "value": method.buildOpt() }),
  2881. Object.defineProperty(ServicePrototype[method.name], "$options", { "value": Service[method.name]["$options"] });
  2882. })(rpc[i]);
  2883. }
  2884. // Properties
  2885. /**
  2886. * Service options.
  2887. * @name ProtoBuf.Builder.Service.$options
  2888. * @type {Object.<string,*>}
  2889. * @expose
  2890. */
  2891. var $optionsS; // cc needs this
  2892. /**
  2893. * Service options.
  2894. * @name ProtoBuf.Builder.Service#$options
  2895. * @type {Object.<string,*>}
  2896. * @expose
  2897. */
  2898. var $options;
  2899. /**
  2900. * Reflection type.
  2901. * @name ProtoBuf.Builder.Service.$type
  2902. * @type {!ProtoBuf.Reflect.Service}
  2903. * @expose
  2904. */
  2905. var $typeS;
  2906. /**
  2907. * Reflection type.
  2908. * @name ProtoBuf.Builder.Service#$type
  2909. * @type {!ProtoBuf.Reflect.Service}
  2910. * @expose
  2911. */
  2912. var $type;
  2913. if (Object.defineProperty)
  2914. Object.defineProperty(Service, "$options", { "value": T.buildOpt() }),
  2915. Object.defineProperty(ServicePrototype, "$options", { "value": Service["$options"] }),
  2916. Object.defineProperty(Service, "$type", { "value": T }),
  2917. Object.defineProperty(ServicePrototype, "$type", { "value": T });
  2918. return Service;
  2919. })(ProtoBuf, this);
  2920. };
  2921. /**
  2922. * @alias ProtoBuf.Reflect.Service
  2923. * @expose
  2924. */
  2925. Reflect.Service = Service;
  2926. /**
  2927. * Abstract service method.
  2928. * @exports ProtoBuf.Reflect.Service.Method
  2929. * @param {!ProtoBuf.Builder} builder Builder reference
  2930. * @param {!ProtoBuf.Reflect.Service} svc Service
  2931. * @param {string} name Method name
  2932. * @param {Object.<string,*>=} options Options
  2933. * @constructor
  2934. * @extends ProtoBuf.Reflect.T
  2935. */
  2936. var Method = function(builder, svc, name, options) {
  2937. T.call(this, builder, svc, name);
  2938. /**
  2939. * @override
  2940. */
  2941. this.className = "Service.Method";
  2942. /**
  2943. * Options.
  2944. * @type {Object.<string, *>}
  2945. * @expose
  2946. */
  2947. this.options = options || {};
  2948. };
  2949. /**
  2950. * @alias ProtoBuf.Reflect.Service.Method.prototype
  2951. * @inner
  2952. */
  2953. var MethodPrototype = Method.prototype = Object.create(T.prototype);
  2954. /**
  2955. * Builds the method's '$options' property.
  2956. * @name ProtoBuf.Reflect.Service.Method#buildOpt
  2957. * @function
  2958. * @return {Object.<string,*>}
  2959. */
  2960. MethodPrototype.buildOpt = NamespacePrototype.buildOpt;
  2961. /**
  2962. * @alias ProtoBuf.Reflect.Service.Method
  2963. * @expose
  2964. */
  2965. Reflect.Service.Method = Method;
  2966. /**
  2967. * RPC service method.
  2968. * @exports ProtoBuf.Reflect.Service.RPCMethod
  2969. * @param {!ProtoBuf.Builder} builder Builder reference
  2970. * @param {!ProtoBuf.Reflect.Service} svc Service
  2971. * @param {string} name Method name
  2972. * @param {string} request Request message name
  2973. * @param {string} response Response message name
  2974. * @param {boolean} request_stream Whether requests are streamed
  2975. * @param {boolean} response_stream Whether responses are streamed
  2976. * @param {Object.<string,*>=} options Options
  2977. * @constructor
  2978. * @extends ProtoBuf.Reflect.Service.Method
  2979. */
  2980. var RPCMethod = function(builder, svc, name, request, response, request_stream, response_stream, options) {
  2981. Method.call(this, builder, svc, name, options);
  2982. /**
  2983. * @override
  2984. */
  2985. this.className = "Service.RPCMethod";
  2986. /**
  2987. * Request message name.
  2988. * @type {string}
  2989. * @expose
  2990. */
  2991. this.requestName = request;
  2992. /**
  2993. * Response message name.
  2994. * @type {string}
  2995. * @expose
  2996. */
  2997. this.responseName = response;
  2998. /**
  2999. * Whether requests are streamed
  3000. * @type {bool}
  3001. * @expose
  3002. */
  3003. this.requestStream = request_stream;
  3004. /**
  3005. * Whether responses are streamed
  3006. * @type {bool}
  3007. * @expose
  3008. */
  3009. this.responseStream = response_stream;
  3010. /**
  3011. * Resolved request message type.
  3012. * @type {ProtoBuf.Reflect.Message}
  3013. * @expose
  3014. */
  3015. this.resolvedRequestType = null;
  3016. /**
  3017. * Resolved response message type.
  3018. * @type {ProtoBuf.Reflect.Message}
  3019. * @expose
  3020. */
  3021. this.resolvedResponseType = null;
  3022. };
  3023. // Extends Method
  3024. RPCMethod.prototype = Object.create(Method.prototype);
  3025. /**
  3026. * @alias ProtoBuf.Reflect.Service.RPCMethod
  3027. * @expose
  3028. */
  3029. Reflect.Service.RPCMethod = RPCMethod;
  3030. return Reflect;
  3031. })(ProtoBuf);
  3032. /**
  3033. * @alias ProtoBuf.Builder
  3034. * @expose
  3035. */
  3036. ProtoBuf.Builder = (function(ProtoBuf, Lang, Reflect) {
  3037. "use strict";
  3038. /**
  3039. * Constructs a new Builder.
  3040. * @exports ProtoBuf.Builder
  3041. * @class Provides the functionality to build protocol messages.
  3042. * @param {Object.<string,*>=} options Options
  3043. * @constructor
  3044. */
  3045. var Builder = function(options) {
  3046. /**
  3047. * Namespace.
  3048. * @type {ProtoBuf.Reflect.Namespace}
  3049. * @expose
  3050. */
  3051. this.ns = new Reflect.Namespace(this, null, ""); // Global namespace
  3052. /**
  3053. * Namespace pointer.
  3054. * @type {ProtoBuf.Reflect.T}
  3055. * @expose
  3056. */
  3057. this.ptr = this.ns;
  3058. /**
  3059. * Resolved flag.
  3060. * @type {boolean}
  3061. * @expose
  3062. */
  3063. this.resolved = false;
  3064. /**
  3065. * The current building result.
  3066. * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
  3067. * @expose
  3068. */
  3069. this.result = null;
  3070. /**
  3071. * Imported files.
  3072. * @type {Array.<string>}
  3073. * @expose
  3074. */
  3075. this.files = {};
  3076. /**
  3077. * Import root override.
  3078. * @type {?string}
  3079. * @expose
  3080. */
  3081. this.importRoot = null;
  3082. /**
  3083. * Options.
  3084. * @type {!Object.<string, *>}
  3085. * @expose
  3086. */
  3087. this.options = options || {};
  3088. };
  3089. /**
  3090. * @alias ProtoBuf.Builder.prototype
  3091. * @inner
  3092. */
  3093. var BuilderPrototype = Builder.prototype;
  3094. // ----- Definition tests -----
  3095. /**
  3096. * Tests if a definition most likely describes a message.
  3097. * @param {!Object} def
  3098. * @returns {boolean}
  3099. * @expose
  3100. */
  3101. Builder.isMessage = function(def) {
  3102. // Messages require a string name
  3103. if (typeof def["name"] !== 'string')
  3104. return false;
  3105. // Messages do not contain values (enum) or rpc methods (service)
  3106. if (typeof def["values"] !== 'undefined' || typeof def["rpc"] !== 'undefined')
  3107. return false;
  3108. return true;
  3109. };
  3110. /**
  3111. * Tests if a definition most likely describes a message field.
  3112. * @param {!Object} def
  3113. * @returns {boolean}
  3114. * @expose
  3115. */
  3116. Builder.isMessageField = function(def) {
  3117. // Message fields require a string rule, name and type and an id
  3118. if (typeof def["rule"] !== 'string' || typeof def["name"] !== 'string' || typeof def["type"] !== 'string' || typeof def["id"] === 'undefined')
  3119. return false;
  3120. return true;
  3121. };
  3122. /**
  3123. * Tests if a definition most likely describes an enum.
  3124. * @param {!Object} def
  3125. * @returns {boolean}
  3126. * @expose
  3127. */
  3128. Builder.isEnum = function(def) {
  3129. // Enums require a string name
  3130. if (typeof def["name"] !== 'string')
  3131. return false;
  3132. // Enums require at least one value
  3133. if (typeof def["values"] === 'undefined' || !Array.isArray(def["values"]) || def["values"].length === 0)
  3134. return false;
  3135. return true;
  3136. };
  3137. /**
  3138. * Tests if a definition most likely describes a service.
  3139. * @param {!Object} def
  3140. * @returns {boolean}
  3141. * @expose
  3142. */
  3143. Builder.isService = function(def) {
  3144. // Services require a string name and an rpc object
  3145. if (typeof def["name"] !== 'string' || typeof def["rpc"] !== 'object' || !def["rpc"])
  3146. return false;
  3147. return true;
  3148. };
  3149. /**
  3150. * Tests if a definition most likely describes an extended message
  3151. * @param {!Object} def
  3152. * @returns {boolean}
  3153. * @expose
  3154. */
  3155. Builder.isExtend = function(def) {
  3156. // Extends rquire a string ref
  3157. if (typeof def["ref"] !== 'string')
  3158. return false;
  3159. return true;
  3160. };
  3161. // ----- Building -----
  3162. /**
  3163. * Resets the pointer to the root namespace.
  3164. * @returns {!ProtoBuf.Builder} this
  3165. * @expose
  3166. */
  3167. BuilderPrototype.reset = function() {
  3168. this.ptr = this.ns;
  3169. return this;
  3170. };
  3171. /**
  3172. * Defines a namespace on top of the current pointer position and places the pointer on it.
  3173. * @param {string} namespace
  3174. * @return {!ProtoBuf.Builder} this
  3175. * @expose
  3176. */
  3177. BuilderPrototype.define = function(namespace) {
  3178. if (typeof namespace !== 'string' || !Lang.TYPEREF.test(namespace))
  3179. throw Error("illegal namespace: "+namespace);
  3180. namespace.split(".").forEach(function(part) {
  3181. var ns = this.ptr.getChild(part);
  3182. if (ns === null) // Keep existing
  3183. this.ptr.addChild(ns = new Reflect.Namespace(this, this.ptr, part));
  3184. this.ptr = ns;
  3185. }, this);
  3186. return this;
  3187. };
  3188. /**
  3189. * Creates the specified definitions at the current pointer position.
  3190. * @param {!Array.<!Object>} defs Messages, enums or services to create
  3191. * @returns {!ProtoBuf.Builder} this
  3192. * @throws {Error} If a message definition is invalid
  3193. * @expose
  3194. */
  3195. BuilderPrototype.create = function(defs) {
  3196. if (!defs)
  3197. return this; // Nothing to create
  3198. if (!Array.isArray(defs))
  3199. defs = [defs];
  3200. else {
  3201. if (defs.length === 0)
  3202. return this;
  3203. defs = defs.slice();
  3204. }
  3205. // It's quite hard to keep track of scopes and memory here, so let's do this iteratively.
  3206. var stack = [defs];
  3207. while (stack.length > 0) {
  3208. defs = stack.pop();
  3209. if (!Array.isArray(defs)) // Stack always contains entire namespaces
  3210. throw Error("not a valid namespace: "+JSON.stringify(defs));
  3211. while (defs.length > 0) {
  3212. var def = defs.shift(); // Namespaces always contain an array of messages, enums and services
  3213. if (Builder.isMessage(def)) {
  3214. var obj = new Reflect.Message(this, this.ptr, def["name"], def["options"], def["isGroup"], def["syntax"]);
  3215. // Create OneOfs
  3216. var oneofs = {};
  3217. if (def["oneofs"])
  3218. Object.keys(def["oneofs"]).forEach(function(name) {
  3219. obj.addChild(oneofs[name] = new Reflect.Message.OneOf(this, obj, name));
  3220. }, this);
  3221. // Create fields
  3222. if (def["fields"])
  3223. def["fields"].forEach(function(fld) {
  3224. if (obj.getChild(fld["id"]|0) !== null)
  3225. throw Error("duplicate or invalid field id in "+obj.name+": "+fld['id']);
  3226. if (fld["options"] && typeof fld["options"] !== 'object')
  3227. throw Error("illegal field options in "+obj.name+"#"+fld["name"]);
  3228. var oneof = null;
  3229. if (typeof fld["oneof"] === 'string' && !(oneof = oneofs[fld["oneof"]]))
  3230. throw Error("illegal oneof in "+obj.name+"#"+fld["name"]+": "+fld["oneof"]);
  3231. fld = new Reflect.Message.Field(this, obj, fld["rule"], fld["keytype"], fld["type"], fld["name"], fld["id"], fld["options"], oneof, def["syntax"]);
  3232. if (oneof)
  3233. oneof.fields.push(fld);
  3234. obj.addChild(fld);
  3235. }, this);
  3236. // Push children to stack
  3237. var subObj = [];
  3238. if (def["enums"])
  3239. def["enums"].forEach(function(enm) {
  3240. subObj.push(enm);
  3241. });
  3242. if (def["messages"])
  3243. def["messages"].forEach(function(msg) {
  3244. subObj.push(msg);
  3245. });
  3246. if (def["services"])
  3247. def["services"].forEach(function(svc) {
  3248. subObj.push(svc);
  3249. });
  3250. // Set extension ranges
  3251. if (def["extensions"]) {
  3252. if (typeof def["extensions"][0] === 'number') // pre 5.0.1
  3253. obj.extensions = [ def["extensions"] ];
  3254. else
  3255. obj.extensions = def["extensions"];
  3256. }
  3257. // Create on top of current namespace
  3258. this.ptr.addChild(obj);
  3259. if (subObj.length > 0) {
  3260. stack.push(defs); // Push the current level back
  3261. defs = subObj; // Continue processing sub level
  3262. subObj = null;
  3263. this.ptr = obj; // And move the pointer to this namespace
  3264. obj = null;
  3265. continue;
  3266. }
  3267. subObj = null;
  3268. } else if (Builder.isEnum(def)) {
  3269. obj = new Reflect.Enum(this, this.ptr, def["name"], def["options"], def["syntax"]);
  3270. def["values"].forEach(function(val) {
  3271. obj.addChild(new Reflect.Enum.Value(this, obj, val["name"], val["id"]));
  3272. }, this);
  3273. this.ptr.addChild(obj);
  3274. } else if (Builder.isService(def)) {
  3275. obj = new Reflect.Service(this, this.ptr, def["name"], def["options"]);
  3276. Object.keys(def["rpc"]).forEach(function(name) {
  3277. var mtd = def["rpc"][name];
  3278. obj.addChild(new Reflect.Service.RPCMethod(this, obj, name, mtd["request"], mtd["response"], !!mtd["request_stream"], !!mtd["response_stream"], mtd["options"]));
  3279. }, this);
  3280. this.ptr.addChild(obj);
  3281. } else if (Builder.isExtend(def)) {
  3282. obj = this.ptr.resolve(def["ref"], true);
  3283. if (obj) {
  3284. def["fields"].forEach(function(fld) {
  3285. if (obj.getChild(fld['id']|0) !== null)
  3286. throw Error("duplicate extended field id in "+obj.name+": "+fld['id']);
  3287. // Check if field id is allowed to be extended
  3288. if (obj.extensions) {
  3289. var valid = false;
  3290. obj.extensions.forEach(function(range) {
  3291. if (fld["id"] >= range[0] && fld["id"] <= range[1])
  3292. valid = true;
  3293. });
  3294. if (!valid)
  3295. throw Error("illegal extended field id in "+obj.name+": "+fld['id']+" (not within valid ranges)");
  3296. }
  3297. // Convert extension field names to camel case notation if the override is set
  3298. var name = fld["name"];
  3299. if (this.options['convertFieldsToCamelCase'])
  3300. name = ProtoBuf.Util.toCamelCase(name);
  3301. // see #161: Extensions use their fully qualified name as their runtime key and...
  3302. var field = new Reflect.Message.ExtensionField(this, obj, fld["rule"], fld["type"], this.ptr.fqn()+'.'+name, fld["id"], fld["options"]);
  3303. // ...are added on top of the current namespace as an extension which is used for
  3304. // resolving their type later on (the extension always keeps the original name to
  3305. // prevent naming collisions)
  3306. var ext = new Reflect.Extension(this, this.ptr, fld["name"], field);
  3307. field.extension = ext;
  3308. this.ptr.addChild(ext);
  3309. obj.addChild(field);
  3310. }, this);
  3311. } else if (!/\.?google\.protobuf\./.test(def["ref"])) // Silently skip internal extensions
  3312. throw Error("extended message "+def["ref"]+" is not defined");
  3313. } else
  3314. throw Error("not a valid definition: "+JSON.stringify(def));
  3315. def = null;
  3316. obj = null;
  3317. }
  3318. // Break goes here
  3319. defs = null;
  3320. this.ptr = this.ptr.parent; // Namespace done, continue at parent
  3321. }
  3322. this.resolved = false; // Require re-resolve
  3323. this.result = null; // Require re-build
  3324. return this;
  3325. };
  3326. /**
  3327. * Propagates syntax to all children.
  3328. * @param {!Object} parent
  3329. * @inner
  3330. */
  3331. function propagateSyntax(parent) {
  3332. if (parent['messages']) {
  3333. parent['messages'].forEach(function(child) {
  3334. child["syntax"] = parent["syntax"];
  3335. propagateSyntax(child);
  3336. });
  3337. }
  3338. if (parent['enums']) {
  3339. parent['enums'].forEach(function(child) {
  3340. child["syntax"] = parent["syntax"];
  3341. });
  3342. }
  3343. }
  3344. /**
  3345. * Imports another definition into this builder.
  3346. * @param {Object.<string,*>} json Parsed import
  3347. * @param {(string|{root: string, file: string})=} filename Imported file name
  3348. * @returns {!ProtoBuf.Builder} this
  3349. * @throws {Error} If the definition or file cannot be imported
  3350. * @expose
  3351. */
  3352. BuilderPrototype["import"] = function(json, filename) {
  3353. var delim = '/';
  3354. // Make sure to skip duplicate imports
  3355. if (typeof filename === 'string') {
  3356. if (ProtoBuf.Util.IS_NODE)
  3357. filename = require("path")['resolve'](filename);
  3358. if (this.files[filename] === true)
  3359. return this.reset();
  3360. this.files[filename] = true;
  3361. } else if (typeof filename === 'object') { // Object with root, file.
  3362. var root = filename.root;
  3363. if (ProtoBuf.Util.IS_NODE)
  3364. root = require("path")['resolve'](root);
  3365. if (root.indexOf("\\") >= 0 || filename.file.indexOf("\\") >= 0)
  3366. delim = '\\';
  3367. var fname;
  3368. if (ProtoBuf.Util.IS_NODE)
  3369. fname = require("path")['join'](root, filename.file);
  3370. else
  3371. fname = root + delim + filename.file;
  3372. if (this.files[fname] === true)
  3373. return this.reset();
  3374. this.files[fname] = true;
  3375. }
  3376. // Import imports
  3377. if (json['imports'] && json['imports'].length > 0) {
  3378. var importRoot,
  3379. resetRoot = false;
  3380. if (typeof filename === 'object') { // If an import root is specified, override
  3381. this.importRoot = filename["root"]; resetRoot = true; // ... and reset afterwards
  3382. importRoot = this.importRoot;
  3383. filename = filename["file"];
  3384. if (importRoot.indexOf("\\") >= 0 || filename.indexOf("\\") >= 0)
  3385. delim = '\\';
  3386. } else if (typeof filename === 'string') {
  3387. if (this.importRoot) // If import root is overridden, use it
  3388. importRoot = this.importRoot;
  3389. else { // Otherwise compute from filename
  3390. if (filename.indexOf("/") >= 0) { // Unix
  3391. importRoot = filename.replace(/\/[^\/]*$/, "");
  3392. if (/* /file.proto */ importRoot === "")
  3393. importRoot = "/";
  3394. } else if (filename.indexOf("\\") >= 0) { // Windows
  3395. importRoot = filename.replace(/\\[^\\]*$/, "");
  3396. delim = '\\';
  3397. } else
  3398. importRoot = ".";
  3399. }
  3400. } else
  3401. importRoot = null;
  3402. for (var i=0; i<json['imports'].length; i++) {
  3403. if (typeof json['imports'][i] === 'string') { // Import file
  3404. if (!importRoot)
  3405. throw Error("cannot determine import root");
  3406. var importFilename = json['imports'][i];
  3407. if (importFilename === "google/protobuf/descriptor.proto")
  3408. continue; // Not needed and therefore not used
  3409. if (ProtoBuf.Util.IS_NODE)
  3410. importFilename = require("path")['join'](importRoot, importFilename);
  3411. else
  3412. importFilename = importRoot + delim + importFilename;
  3413. if (this.files[importFilename] === true)
  3414. continue; // Already imported
  3415. if (/\.proto$/i.test(importFilename) && !ProtoBuf.DotProto) // If this is a light build
  3416. importFilename = importFilename.replace(/\.proto$/, ".json"); // always load the JSON file
  3417. var contents = ProtoBuf.Util.fetch(importFilename);
  3418. if (contents === null)
  3419. throw Error("failed to import '"+importFilename+"' in '"+filename+"': file not found");
  3420. if (/\.json$/i.test(importFilename)) // Always possible
  3421. this["import"](JSON.parse(contents+""), importFilename); // May throw
  3422. else
  3423. this["import"](ProtoBuf.DotProto.Parser.parse(contents), importFilename); // May throw
  3424. } else // Import structure
  3425. if (!filename)
  3426. this["import"](json['imports'][i]);
  3427. else if (/\.(\w+)$/.test(filename)) // With extension: Append _importN to the name portion to make it unique
  3428. this["import"](json['imports'][i], filename.replace(/^(.+)\.(\w+)$/, function($0, $1, $2) { return $1+"_import"+i+"."+$2; }));
  3429. else // Without extension: Append _importN to make it unique
  3430. this["import"](json['imports'][i], filename+"_import"+i);
  3431. }
  3432. if (resetRoot) // Reset import root override when all imports are done
  3433. this.importRoot = null;
  3434. }
  3435. // Import structures
  3436. if (json['package'])
  3437. this.define(json['package']);
  3438. if (json['syntax'])
  3439. propagateSyntax(json);
  3440. var base = this.ptr;
  3441. if (json['options'])
  3442. Object.keys(json['options']).forEach(function(key) {
  3443. base.options[key] = json['options'][key];
  3444. });
  3445. if (json['messages'])
  3446. this.create(json['messages']),
  3447. this.ptr = base;
  3448. if (json['enums'])
  3449. this.create(json['enums']),
  3450. this.ptr = base;
  3451. if (json['services'])
  3452. this.create(json['services']),
  3453. this.ptr = base;
  3454. if (json['extends'])
  3455. this.create(json['extends']);
  3456. return this.reset();
  3457. };
  3458. /**
  3459. * Resolves all namespace objects.
  3460. * @throws {Error} If a type cannot be resolved
  3461. * @returns {!ProtoBuf.Builder} this
  3462. * @expose
  3463. */
  3464. BuilderPrototype.resolveAll = function() {
  3465. // Resolve all reflected objects
  3466. var res;
  3467. if (this.ptr == null || typeof this.ptr.type === 'object')
  3468. return this; // Done (already resolved)
  3469. if (this.ptr instanceof Reflect.Namespace) { // Resolve children
  3470. this.ptr.children.forEach(function(child) {
  3471. this.ptr = child;
  3472. this.resolveAll();
  3473. }, this);
  3474. } else if (this.ptr instanceof Reflect.Message.Field) { // Resolve type
  3475. if (!Lang.TYPE.test(this.ptr.type)) {
  3476. if (!Lang.TYPEREF.test(this.ptr.type))
  3477. throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  3478. res = (this.ptr instanceof Reflect.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, true);
  3479. if (!res)
  3480. throw Error("unresolvable type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  3481. this.ptr.resolvedType = res;
  3482. if (res instanceof Reflect.Enum) {
  3483. this.ptr.type = ProtoBuf.TYPES["enum"];
  3484. if (this.ptr.syntax === 'proto3' && res.syntax !== 'proto3')
  3485. throw Error("proto3 message cannot reference proto2 enum");
  3486. }
  3487. else if (res instanceof Reflect.Message)
  3488. this.ptr.type = res.isGroup ? ProtoBuf.TYPES["group"] : ProtoBuf.TYPES["message"];
  3489. else
  3490. throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  3491. } else
  3492. this.ptr.type = ProtoBuf.TYPES[this.ptr.type];
  3493. // If it's a map field, also resolve the key type. The key type can be only a numeric, string, or bool type
  3494. // (i.e., no enums or messages), so we don't need to resolve against the current namespace.
  3495. if (this.ptr.map) {
  3496. if (!Lang.TYPE.test(this.ptr.keyType))
  3497. throw Error("illegal key type for map field in "+this.ptr.toString(true)+": "+this.ptr.keyType);
  3498. this.ptr.keyType = ProtoBuf.TYPES[this.ptr.keyType];
  3499. }
  3500. // If it's a repeated and packable field then proto3 mandates it should be packed by
  3501. // default
  3502. if (
  3503. this.ptr.syntax === 'proto3' &&
  3504. this.ptr.repeated && this.ptr.options.packed === undefined &&
  3505. ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.ptr.type.wireType) !== -1
  3506. ) {
  3507. this.ptr.options.packed = true;
  3508. }
  3509. } else if (this.ptr instanceof ProtoBuf.Reflect.Service.Method) {
  3510. if (this.ptr instanceof ProtoBuf.Reflect.Service.RPCMethod) {
  3511. res = this.ptr.parent.resolve(this.ptr.requestName, true);
  3512. if (!res || !(res instanceof ProtoBuf.Reflect.Message))
  3513. throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.requestName);
  3514. this.ptr.resolvedRequestType = res;
  3515. res = this.ptr.parent.resolve(this.ptr.responseName, true);
  3516. if (!res || !(res instanceof ProtoBuf.Reflect.Message))
  3517. throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.responseName);
  3518. this.ptr.resolvedResponseType = res;
  3519. } else // Should not happen as nothing else is implemented
  3520. throw Error("illegal service type in "+this.ptr.toString(true));
  3521. } else if (
  3522. !(this.ptr instanceof ProtoBuf.Reflect.Message.OneOf) && // Not built
  3523. !(this.ptr instanceof ProtoBuf.Reflect.Extension) && // Not built
  3524. !(this.ptr instanceof ProtoBuf.Reflect.Enum.Value) // Built in enum
  3525. )
  3526. throw Error("illegal object in namespace: "+typeof(this.ptr)+": "+this.ptr);
  3527. return this.reset();
  3528. };
  3529. /**
  3530. * Builds the protocol. This will first try to resolve all definitions and, if this has been successful,
  3531. * return the built package.
  3532. * @param {(string|Array.<string>)=} path Specifies what to return. If omitted, the entire namespace will be returned.
  3533. * @returns {!ProtoBuf.Builder.Message|!Object.<string,*>}
  3534. * @throws {Error} If a type could not be resolved
  3535. * @expose
  3536. */
  3537. BuilderPrototype.build = function(path) {
  3538. this.reset();
  3539. if (!this.resolved)
  3540. this.resolveAll(),
  3541. this.resolved = true,
  3542. this.result = null; // Require re-build
  3543. if (this.result === null) // (Re-)Build
  3544. this.result = this.ns.build();
  3545. if (!path)
  3546. return this.result;
  3547. var part = typeof path === 'string' ? path.split(".") : path,
  3548. ptr = this.result; // Build namespace pointer (no hasChild etc.)
  3549. for (var i=0; i<part.length; i++)
  3550. if (ptr[part[i]])
  3551. ptr = ptr[part[i]];
  3552. else {
  3553. ptr = null;
  3554. break;
  3555. }
  3556. return ptr;
  3557. };
  3558. /**
  3559. * Similar to {@link ProtoBuf.Builder#build}, but looks up the internal reflection descriptor.
  3560. * @param {string=} path Specifies what to return. If omitted, the entire namespace wiil be returned.
  3561. * @param {boolean=} excludeNonNamespace Excludes non-namespace types like fields, defaults to `false`
  3562. * @returns {?ProtoBuf.Reflect.T} Reflection descriptor or `null` if not found
  3563. */
  3564. BuilderPrototype.lookup = function(path, excludeNonNamespace) {
  3565. return path ? this.ns.resolve(path, excludeNonNamespace) : this.ns;
  3566. };
  3567. /**
  3568. * Returns a string representation of this object.
  3569. * @return {string} String representation as of "Builder"
  3570. * @expose
  3571. */
  3572. BuilderPrototype.toString = function() {
  3573. return "Builder";
  3574. };
  3575. // ----- Base classes -----
  3576. // Exist for the sole purpose of being able to "... instanceof ProtoBuf.Builder.Message" etc.
  3577. /**
  3578. * @alias ProtoBuf.Builder.Message
  3579. */
  3580. Builder.Message = function() {};
  3581. /**
  3582. * @alias ProtoBuf.Builder.Enum
  3583. */
  3584. Builder.Enum = function() {};
  3585. /**
  3586. * @alias ProtoBuf.Builder.Message
  3587. */
  3588. Builder.Service = function() {};
  3589. return Builder;
  3590. })(ProtoBuf, ProtoBuf.Lang, ProtoBuf.Reflect);
  3591. /**
  3592. * @alias ProtoBuf.Map
  3593. * @expose
  3594. */
  3595. ProtoBuf.Map = (function(ProtoBuf, Reflect) {
  3596. "use strict";
  3597. /**
  3598. * Constructs a new Map. A Map is a container that is used to implement map
  3599. * fields on message objects. It closely follows the ES6 Map API; however,
  3600. * it is distinct because we do not want to depend on external polyfills or
  3601. * on ES6 itself.
  3602. *
  3603. * @exports ProtoBuf.Map
  3604. * @param {!ProtoBuf.Reflect.Field} field Map field
  3605. * @param {Object.<string,*>=} contents Initial contents
  3606. * @constructor
  3607. */
  3608. var Map = function(field, contents) {
  3609. if (!field.map)
  3610. throw Error("field is not a map");
  3611. /**
  3612. * The field corresponding to this map.
  3613. * @type {!ProtoBuf.Reflect.Field}
  3614. */
  3615. this.field = field;
  3616. /**
  3617. * Element instance corresponding to key type.
  3618. * @type {!ProtoBuf.Reflect.Element}
  3619. */
  3620. this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);
  3621. /**
  3622. * Element instance corresponding to value type.
  3623. * @type {!ProtoBuf.Reflect.Element}
  3624. */
  3625. this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);
  3626. /**
  3627. * Internal map: stores mapping of (string form of key) -> (key, value)
  3628. * pair.
  3629. *
  3630. * We provide map semantics for arbitrary key types, but we build on top
  3631. * of an Object, which has only string keys. In order to avoid the need
  3632. * to convert a string key back to its native type in many situations,
  3633. * we store the native key value alongside the value. Thus, we only need
  3634. * a one-way mapping from a key type to its string form that guarantees
  3635. * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
  3636. * === K2).
  3637. *
  3638. * @type {!Object<string, {key: *, value: *}>}
  3639. */
  3640. this.map = {};
  3641. /**
  3642. * Returns the number of elements in the map.
  3643. */
  3644. Object.defineProperty(this, "size", {
  3645. get: function() { return Object.keys(this.map).length; }
  3646. });
  3647. // Fill initial contents from a raw object.
  3648. if (contents) {
  3649. var keys = Object.keys(contents);
  3650. for (var i = 0; i < keys.length; i++) {
  3651. var key = this.keyElem.valueFromString(keys[i]);
  3652. var val = this.valueElem.verifyValue(contents[keys[i]]);
  3653. this.map[this.keyElem.valueToString(key)] =
  3654. { key: key, value: val };
  3655. }
  3656. }
  3657. };
  3658. var MapPrototype = Map.prototype;
  3659. /**
  3660. * Helper: return an iterator over an array.
  3661. * @param {!Array<*>} arr the array
  3662. * @returns {!Object} an iterator
  3663. * @inner
  3664. */
  3665. function arrayIterator(arr) {
  3666. var idx = 0;
  3667. return {
  3668. next: function() {
  3669. if (idx < arr.length)
  3670. return { done: false, value: arr[idx++] };
  3671. return { done: true };
  3672. }
  3673. }
  3674. }
  3675. /**
  3676. * Clears the map.
  3677. */
  3678. MapPrototype.clear = function() {
  3679. this.map = {};
  3680. };
  3681. /**
  3682. * Deletes a particular key from the map.
  3683. * @returns {boolean} Whether any entry with this key was deleted.
  3684. */
  3685. MapPrototype["delete"] = function(key) {
  3686. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  3687. var hadKey = keyValue in this.map;
  3688. delete this.map[keyValue];
  3689. return hadKey;
  3690. };
  3691. /**
  3692. * Returns an iterator over [key, value] pairs in the map.
  3693. * @returns {Object} The iterator
  3694. */
  3695. MapPrototype.entries = function() {
  3696. var entries = [];
  3697. var strKeys = Object.keys(this.map);
  3698. for (var i = 0, entry; i < strKeys.length; i++)
  3699. entries.push([(entry=this.map[strKeys[i]]).key, entry.value]);
  3700. return arrayIterator(entries);
  3701. };
  3702. /**
  3703. * Returns an iterator over keys in the map.
  3704. * @returns {Object} The iterator
  3705. */
  3706. MapPrototype.keys = function() {
  3707. var keys = [];
  3708. var strKeys = Object.keys(this.map);
  3709. for (var i = 0; i < strKeys.length; i++)
  3710. keys.push(this.map[strKeys[i]].key);
  3711. return arrayIterator(keys);
  3712. };
  3713. /**
  3714. * Returns an iterator over values in the map.
  3715. * @returns {!Object} The iterator
  3716. */
  3717. MapPrototype.values = function() {
  3718. var values = [];
  3719. var strKeys = Object.keys(this.map);
  3720. for (var i = 0; i < strKeys.length; i++)
  3721. values.push(this.map[strKeys[i]].value);
  3722. return arrayIterator(values);
  3723. };
  3724. /**
  3725. * Iterates over entries in the map, calling a function on each.
  3726. * @param {function(this:*, *, *, *)} cb The callback to invoke with value, key, and map arguments.
  3727. * @param {Object=} thisArg The `this` value for the callback
  3728. */
  3729. MapPrototype.forEach = function(cb, thisArg) {
  3730. var strKeys = Object.keys(this.map);
  3731. for (var i = 0, entry; i < strKeys.length; i++)
  3732. cb.call(thisArg, (entry=this.map[strKeys[i]]).value, entry.key, this);
  3733. };
  3734. /**
  3735. * Sets a key in the map to the given value.
  3736. * @param {*} key The key
  3737. * @param {*} value The value
  3738. * @returns {!ProtoBuf.Map} The map instance
  3739. */
  3740. MapPrototype.set = function(key, value) {
  3741. var keyValue = this.keyElem.verifyValue(key);
  3742. var valValue = this.valueElem.verifyValue(value);
  3743. this.map[this.keyElem.valueToString(keyValue)] =
  3744. { key: keyValue, value: valValue };
  3745. return this;
  3746. };
  3747. /**
  3748. * Gets the value corresponding to a key in the map.
  3749. * @param {*} key The key
  3750. * @returns {*|undefined} The value, or `undefined` if key not present
  3751. */
  3752. MapPrototype.get = function(key) {
  3753. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  3754. if (!(keyValue in this.map))
  3755. return undefined;
  3756. return this.map[keyValue].value;
  3757. };
  3758. /**
  3759. * Determines whether the given key is present in the map.
  3760. * @param {*} key The key
  3761. * @returns {boolean} `true` if the key is present
  3762. */
  3763. MapPrototype.has = function(key) {
  3764. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  3765. return (keyValue in this.map);
  3766. };
  3767. return Map;
  3768. })(ProtoBuf, ProtoBuf.Reflect);
  3769. /**
  3770. * Constructs a new empty Builder.
  3771. * @param {Object.<string,*>=} options Builder options, defaults to global options set on ProtoBuf
  3772. * @return {!ProtoBuf.Builder} Builder
  3773. * @expose
  3774. */
  3775. ProtoBuf.newBuilder = function(options) {
  3776. options = options || {};
  3777. if (typeof options['convertFieldsToCamelCase'] === 'undefined')
  3778. options['convertFieldsToCamelCase'] = ProtoBuf.convertFieldsToCamelCase;
  3779. if (typeof options['populateAccessors'] === 'undefined')
  3780. options['populateAccessors'] = ProtoBuf.populateAccessors;
  3781. return new ProtoBuf.Builder(options);
  3782. };
  3783. /**
  3784. * Loads a .json definition and returns the Builder.
  3785. * @param {!*|string} json JSON definition
  3786. * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
  3787. * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
  3788. * @return {ProtoBuf.Builder} Builder to create new messages
  3789. * @throws {Error} If the definition cannot be parsed or built
  3790. * @expose
  3791. */
  3792. ProtoBuf.loadJson = function(json, builder, filename) {
  3793. if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
  3794. filename = builder,
  3795. builder = null;
  3796. if (!builder || typeof builder !== 'object')
  3797. builder = ProtoBuf.newBuilder();
  3798. if (typeof json === 'string')
  3799. json = JSON.parse(json);
  3800. builder["import"](json, filename);
  3801. builder.resolveAll();
  3802. return builder;
  3803. };
  3804. /**
  3805. * Loads a .json file and returns the Builder.
  3806. * @param {string|!{root: string, file: string}} filename Path to json file or an object specifying 'file' with
  3807. * an overridden 'root' path for all imported files.
  3808. * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
  3809. * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
  3810. * file will be read synchronously and this function will return the Builder.
  3811. * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
  3812. * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
  3813. * request has failed), else undefined
  3814. * @expose
  3815. */
  3816. ProtoBuf.loadJsonFile = function(filename, callback, builder) {
  3817. if (callback && typeof callback === 'object')
  3818. builder = callback,
  3819. callback = null;
  3820. else if (!callback || typeof callback !== 'function')
  3821. callback = null;
  3822. if (callback)
  3823. return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"]+"/"+filename["file"], function(contents) {
  3824. if (contents === null) {
  3825. callback(Error("Failed to fetch file"));
  3826. return;
  3827. }
  3828. try {
  3829. callback(null, ProtoBuf.loadJson(JSON.parse(contents), builder, filename));
  3830. } catch (e) {
  3831. callback(e);
  3832. }
  3833. });
  3834. var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"]+"/"+filename["file"] : filename);
  3835. return contents === null ? null : ProtoBuf.loadJson(JSON.parse(contents), builder, filename);
  3836. };
  3837. return ProtoBuf;
  3838. });