智慧水务管理系统 - 精河县供水工程综合管理平台

protobuf.js 323KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539
  1. /*!
  2. * protobuf.js v8.6.3 (c) 2016, daniel wirtz
  3. * compiled thu, 11 jun 2026 00:02:30 utc
  4. * licensed under the bsd-3-clause license
  5. * see: https://github.com/dcodeio/protobuf.js for details
  6. */
  7. (function(undefined){"use strict";(function prelude(modules, cache, entries) {
  8. // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS
  9. // sources through a conflict-free require shim and is again wrapped within an iife that
  10. // provides a minification-friendly `undefined` var plus a global "use strict" directive
  11. // so that minification can remove the directives of each module.
  12. function $require(name) {
  13. var $module = cache[name];
  14. if (!$module)
  15. modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);
  16. return $module.exports;
  17. }
  18. var protobuf = $require(entries[0]);
  19. // Expose globally
  20. protobuf.util.global.protobuf = protobuf;
  21. // Be nice to AMD
  22. if (typeof define === "function" && define.amd)
  23. define(["long"], function(Long) {
  24. if (Long && Long.isLong) {
  25. protobuf.util.Long = Long;
  26. protobuf.configure();
  27. }
  28. return protobuf;
  29. });
  30. // Be nice to CommonJS
  31. if (typeof module === "object" && module && module.exports)
  32. module.exports = protobuf;
  33. })/* end of prelude */({1:[function(require,module,exports){
  34. },{}],2:[function(require,module,exports){
  35. "use strict";
  36. module.exports = common;
  37. var commonRe = /\/|\./;
  38. /**
  39. * Provides common type definitions.
  40. * Can also be used to provide additional google types or your own custom types.
  41. * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name
  42. * @param {Object.<string,*>} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition
  43. * @returns {undefined}
  44. * @property {INamespace} google/protobuf/any.proto Any
  45. * @property {INamespace} google/protobuf/duration.proto Duration
  46. * @property {INamespace} google/protobuf/empty.proto Empty
  47. * @property {INamespace} google/protobuf/field_mask.proto FieldMask
  48. * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue
  49. * @property {INamespace} google/protobuf/timestamp.proto Timestamp
  50. * @property {INamespace} google/protobuf/wrappers.proto Wrappers
  51. * @example
  52. * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)
  53. * protobuf.common("descriptor", descriptorJson);
  54. *
  55. * // manually provides a custom definition (uses my.foo namespace)
  56. * protobuf.common("my/foo/bar.proto", myFooBarJson);
  57. */
  58. function common(name, json) {
  59. if (!commonRe.test(name)) {
  60. name = "google/protobuf/" + name + ".proto";
  61. json = { nested: { google: { nested: { protobuf: { nested: json } } } } };
  62. }
  63. common[name] = json;
  64. }
  65. // Not provided because of limited use (feel free to discuss or to provide yourself):
  66. //
  67. // google/protobuf/descriptor.proto
  68. // google/protobuf/source_context.proto
  69. // google/protobuf/type.proto
  70. //
  71. // Stripped and pre-parsed versions of these non-bundled files are instead available as part of
  72. // the repository or package within the google/protobuf directory.
  73. common("any", {
  74. /**
  75. * Properties of a google.protobuf.Any message.
  76. * @interface IAny
  77. * @type {Object}
  78. * @property {string} [typeUrl]
  79. * @property {Uint8Array} [bytes]
  80. * @memberof common
  81. */
  82. Any: {
  83. fields: {
  84. type_url: {
  85. type: "string",
  86. id: 1
  87. },
  88. value: {
  89. type: "bytes",
  90. id: 2
  91. }
  92. }
  93. }
  94. });
  95. var timeType;
  96. common("duration", {
  97. /**
  98. * Properties of a google.protobuf.Duration message.
  99. * @interface IDuration
  100. * @type {Object}
  101. * @property {number|Long} [seconds]
  102. * @property {number} [nanos]
  103. * @memberof common
  104. */
  105. Duration: timeType = {
  106. fields: {
  107. seconds: {
  108. type: "int64",
  109. id: 1
  110. },
  111. nanos: {
  112. type: "int32",
  113. id: 2
  114. }
  115. }
  116. }
  117. });
  118. common("timestamp", {
  119. /**
  120. * Properties of a google.protobuf.Timestamp message.
  121. * @interface ITimestamp
  122. * @type {Object}
  123. * @property {number|Long} [seconds]
  124. * @property {number} [nanos]
  125. * @memberof common
  126. */
  127. Timestamp: timeType
  128. });
  129. common("empty", {
  130. /**
  131. * Properties of a google.protobuf.Empty message.
  132. * @interface IEmpty
  133. * @memberof common
  134. */
  135. Empty: {
  136. fields: {}
  137. }
  138. });
  139. common("struct", {
  140. /**
  141. * Properties of a google.protobuf.Struct message.
  142. * @interface IStruct
  143. * @type {Object}
  144. * @property {Object.<string,IValue>} [fields]
  145. * @memberof common
  146. */
  147. Struct: {
  148. fields: {
  149. fields: {
  150. keyType: "string",
  151. type: "Value",
  152. id: 1
  153. }
  154. }
  155. },
  156. /**
  157. * Properties of a google.protobuf.Value message.
  158. * @interface IValue
  159. * @type {Object}
  160. * @property {string} [kind]
  161. * @property {0} [nullValue]
  162. * @property {number} [numberValue]
  163. * @property {string} [stringValue]
  164. * @property {boolean} [boolValue]
  165. * @property {IStruct} [structValue]
  166. * @property {IListValue} [listValue]
  167. * @memberof common
  168. */
  169. Value: {
  170. oneofs: {
  171. kind: {
  172. oneof: [
  173. "nullValue",
  174. "numberValue",
  175. "stringValue",
  176. "boolValue",
  177. "structValue",
  178. "listValue"
  179. ]
  180. }
  181. },
  182. fields: {
  183. nullValue: {
  184. type: "NullValue",
  185. id: 1
  186. },
  187. numberValue: {
  188. type: "double",
  189. id: 2
  190. },
  191. stringValue: {
  192. type: "string",
  193. id: 3
  194. },
  195. boolValue: {
  196. type: "bool",
  197. id: 4
  198. },
  199. structValue: {
  200. type: "Struct",
  201. id: 5
  202. },
  203. listValue: {
  204. type: "ListValue",
  205. id: 6
  206. }
  207. }
  208. },
  209. NullValue: {
  210. values: {
  211. NULL_VALUE: 0
  212. }
  213. },
  214. /**
  215. * Properties of a google.protobuf.ListValue message.
  216. * @interface IListValue
  217. * @type {Object}
  218. * @property {Array.<IValue>} [values]
  219. * @memberof common
  220. */
  221. ListValue: {
  222. fields: {
  223. values: {
  224. rule: "repeated",
  225. type: "Value",
  226. id: 1
  227. }
  228. }
  229. }
  230. });
  231. common("wrappers", {
  232. /**
  233. * Properties of a google.protobuf.DoubleValue message.
  234. * @interface IDoubleValue
  235. * @type {Object}
  236. * @property {number} [value]
  237. * @memberof common
  238. */
  239. DoubleValue: {
  240. fields: {
  241. value: {
  242. type: "double",
  243. id: 1
  244. }
  245. }
  246. },
  247. /**
  248. * Properties of a google.protobuf.FloatValue message.
  249. * @interface IFloatValue
  250. * @type {Object}
  251. * @property {number} [value]
  252. * @memberof common
  253. */
  254. FloatValue: {
  255. fields: {
  256. value: {
  257. type: "float",
  258. id: 1
  259. }
  260. }
  261. },
  262. /**
  263. * Properties of a google.protobuf.Int64Value message.
  264. * @interface IInt64Value
  265. * @type {Object}
  266. * @property {number|Long} [value]
  267. * @memberof common
  268. */
  269. Int64Value: {
  270. fields: {
  271. value: {
  272. type: "int64",
  273. id: 1
  274. }
  275. }
  276. },
  277. /**
  278. * Properties of a google.protobuf.UInt64Value message.
  279. * @interface IUInt64Value
  280. * @type {Object}
  281. * @property {number|Long} [value]
  282. * @memberof common
  283. */
  284. UInt64Value: {
  285. fields: {
  286. value: {
  287. type: "uint64",
  288. id: 1
  289. }
  290. }
  291. },
  292. /**
  293. * Properties of a google.protobuf.Int32Value message.
  294. * @interface IInt32Value
  295. * @type {Object}
  296. * @property {number} [value]
  297. * @memberof common
  298. */
  299. Int32Value: {
  300. fields: {
  301. value: {
  302. type: "int32",
  303. id: 1
  304. }
  305. }
  306. },
  307. /**
  308. * Properties of a google.protobuf.UInt32Value message.
  309. * @interface IUInt32Value
  310. * @type {Object}
  311. * @property {number} [value]
  312. * @memberof common
  313. */
  314. UInt32Value: {
  315. fields: {
  316. value: {
  317. type: "uint32",
  318. id: 1
  319. }
  320. }
  321. },
  322. /**
  323. * Properties of a google.protobuf.BoolValue message.
  324. * @interface IBoolValue
  325. * @type {Object}
  326. * @property {boolean} [value]
  327. * @memberof common
  328. */
  329. BoolValue: {
  330. fields: {
  331. value: {
  332. type: "bool",
  333. id: 1
  334. }
  335. }
  336. },
  337. /**
  338. * Properties of a google.protobuf.StringValue message.
  339. * @interface IStringValue
  340. * @type {Object}
  341. * @property {string} [value]
  342. * @memberof common
  343. */
  344. StringValue: {
  345. fields: {
  346. value: {
  347. type: "string",
  348. id: 1
  349. }
  350. }
  351. },
  352. /**
  353. * Properties of a google.protobuf.BytesValue message.
  354. * @interface IBytesValue
  355. * @type {Object}
  356. * @property {Uint8Array} [value]
  357. * @memberof common
  358. */
  359. BytesValue: {
  360. fields: {
  361. value: {
  362. type: "bytes",
  363. id: 1
  364. }
  365. }
  366. }
  367. });
  368. common("field_mask", {
  369. /**
  370. * Properties of a google.protobuf.FieldMask message.
  371. * @interface IFieldMask
  372. * @type {Object}
  373. * @property {string[]} [paths]
  374. * @memberof common
  375. */
  376. FieldMask: {
  377. fields: {
  378. paths: {
  379. rule: "repeated",
  380. type: "string",
  381. id: 1
  382. }
  383. }
  384. }
  385. });
  386. /**
  387. * Gets the root definition of the specified common proto file.
  388. *
  389. * Bundled definitions are:
  390. * - google/protobuf/any.proto
  391. * - google/protobuf/duration.proto
  392. * - google/protobuf/empty.proto
  393. * - google/protobuf/field_mask.proto
  394. * - google/protobuf/struct.proto
  395. * - google/protobuf/timestamp.proto
  396. * - google/protobuf/wrappers.proto
  397. *
  398. * @param {string} file Proto file name
  399. * @returns {INamespace|null} Root definition or `null` if not defined
  400. */
  401. common.get = function get(file) {
  402. return common[file] || null;
  403. };
  404. },{}],3:[function(require,module,exports){
  405. "use strict";
  406. /**
  407. * Runtime message from/to plain object converters.
  408. * @namespace
  409. */
  410. var converter = exports;
  411. var Enum = require(6),
  412. types = require(27),
  413. util = require(28);
  414. /**
  415. * Generates a partial value fromObject conveter.
  416. * @param {Codegen} gen Codegen instance
  417. * @param {Field} field Reflected field
  418. * @param {number} fieldIndex Field index
  419. * @param {string} prop Property reference
  420. * @returns {Codegen} Codegen instance
  421. * @ignore
  422. */
  423. function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
  424. var defaultAlreadyEmitted = false;
  425. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  426. if (field.resolvedType) {
  427. if (field.resolvedType instanceof Enum) { gen
  428. ("switch(d%s){", prop);
  429. for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
  430. // enum unknown values passthrough
  431. if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen
  432. ("default:")
  433. ("if(typeof d%s===\"number\"){m%s=d%s;break}", prop, prop, prop);
  434. if (!field.repeated) gen // fallback to default value only for
  435. // arrays, to avoid leaving holes.
  436. ("break"); // for non-repeated fields, just ignore
  437. defaultAlreadyEmitted = true;
  438. }
  439. gen
  440. ("case%j:", keys[i])
  441. ("case %i:", values[keys[i]])
  442. ("m%s=%j", prop, values[keys[i]])
  443. ("break");
  444. } gen
  445. ("}");
  446. } else gen
  447. ("if(!util.isObject(d%s))", prop)
  448. ("throw TypeError(%j)", field.fullName + ": object expected")
  449. ("m%s=types[%i].fromObject(d%s,q+1)", prop, fieldIndex, prop);
  450. } else {
  451. var isUnsigned = false;
  452. switch (field.type) {
  453. case "double":
  454. case "float": gen
  455. ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity"
  456. break;
  457. case "uint32":
  458. case "fixed32": gen
  459. ("m%s=d%s>>>0", prop, prop);
  460. break;
  461. case "int32":
  462. case "sint32":
  463. case "sfixed32": gen
  464. ("m%s=d%s|0", prop, prop);
  465. break;
  466. case "uint64":
  467. case "fixed64":
  468. isUnsigned = true;
  469. // eslint-disable-next-line no-fallthrough
  470. case "int64":
  471. case "sint64":
  472. case "sfixed64": gen
  473. ("if(util.Long)")
  474. ("m%s=util.Long.fromValue(d%s,%j)", prop, prop, isUnsigned)
  475. ("else if(typeof d%s===\"string\")", prop)
  476. ("m%s=parseInt(d%s,10)", prop, prop)
  477. ("else if(typeof d%s===\"number\")", prop)
  478. ("m%s=d%s", prop, prop)
  479. ("else if(typeof d%s===\"object\")", prop)
  480. ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : "");
  481. break;
  482. case "bytes": gen
  483. ("if(typeof d%s===\"string\")", prop)
  484. ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)
  485. ("else if(d%s.length>=0)", prop)
  486. ("m%s=d%s", prop, prop);
  487. break;
  488. case "string": gen
  489. ("m%s=String(d%s)", prop, prop);
  490. break;
  491. case "bool": gen
  492. ("m%s=Boolean(d%s)", prop, prop);
  493. break;
  494. /* default: gen
  495. ("m%s=d%s", prop, prop);
  496. break; */
  497. }
  498. }
  499. return gen;
  500. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  501. }
  502. /**
  503. * Generates a plain object to runtime message converter specific to the specified message type.
  504. * @param {Type} mtype Message type
  505. * @returns {Codegen} Codegen instance
  506. */
  507. converter.fromObject = function fromObject(mtype) {
  508. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  509. var fields = mtype.fieldsArray;
  510. var gen = util.codegen(["d", "q"])
  511. ("if(d instanceof C)")
  512. ("return d")
  513. ("if(!util.isObject(d))")
  514. ("throw TypeError(%j)", mtype.fullName + ": object expected")
  515. ("if(q===undefined)q=0")
  516. ("if(q>util.recursionLimit)")
  517. ("throw Error(\"max depth exceeded\")");
  518. if (!fields.length) return gen
  519. ("return new C");
  520. gen
  521. ("var m=new C");
  522. for (var i = 0; i < fields.length; ++i) {
  523. var field = fields[i].resolve(),
  524. prop = util.safeProp(field.name),
  525. implicitPresence = !field.hasPresence && !field.repeated && !field.map
  526. && (field.resolvedType instanceof Enum || types.basic[field.type] !== undefined);
  527. // Map fields
  528. if (field.map) { gen
  529. ("if(d%s){", prop)
  530. ("if(!util.isObject(d%s))", prop)
  531. ("throw TypeError(%j)", field.fullName + ": object expected")
  532. ("m%s={}", prop)
  533. ("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){", prop);
  534. gen
  535. ("if(ks[i]===\"__proto__\")")
  536. ("util.makeProp(m%s,ks[i])", prop);
  537. genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[ks[i]]")
  538. ("}")
  539. ("}");
  540. // Repeated fields
  541. } else if (field.repeated) { gen
  542. ("if(d%s){", prop)
  543. ("if(!Array.isArray(d%s))", prop)
  544. ("throw TypeError(%j)", field.fullName + ": array expected")
  545. ("m%s=Array(d%s.length)", prop, prop)
  546. ("for(var i=0;i<d%s.length;++i){", prop);
  547. genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[i]")
  548. ("}")
  549. ("}");
  550. // Non-repeated fields
  551. } else {
  552. if (!(field.resolvedType instanceof Enum)) gen // no need to test for null/undefined if an enum (uses switch)
  553. ("if(d%s!=null){", prop); // !== undefined && !== null
  554. if (implicitPresence) {
  555. if (field.resolvedType instanceof Enum) gen
  556. ("if(d%s!==%j&&(typeof d%s!==\"string\"||types[%i].values[d%s]!==%j)){", prop, field.typeDefault, prop, i, prop, field.typeDefault);
  557. else if (field.type === "string") gen
  558. ("if(typeof d%s!==\"string\"||d%s.length){", prop, prop);
  559. else if (field.type === "bytes") gen
  560. ("if(d%s.length){", prop);
  561. else if (field.type === "bool") gen
  562. ("if(d%s){", prop);
  563. else if (types.long[field.type] !== undefined) gen
  564. ("if(typeof d%s===\"object\"?d%s.low||d%s.high:Number(d%s)!==0){", prop, prop, prop, prop);
  565. else gen
  566. ("if(Number(d%s)!==0){", prop);
  567. }
  568. genValuePartial_fromObject(gen, field, /* not sorted */ i, prop);
  569. if (implicitPresence) gen
  570. ("}");
  571. if (!(field.resolvedType instanceof Enum)) gen
  572. ("}");
  573. }
  574. } return gen
  575. ("return m");
  576. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  577. };
  578. /**
  579. * Generates a partial value toObject converter.
  580. * @param {Codegen} gen Codegen instance
  581. * @param {Field} field Reflected field
  582. * @param {number} fieldIndex Field index
  583. * @param {string} dstProp Destination property reference
  584. * @param {string} [srcProp] Source property reference
  585. * @returns {Codegen} Codegen instance
  586. * @ignore
  587. */
  588. function genValuePartial_toObject(gen, field, fieldIndex, dstProp, srcProp) {
  589. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  590. if (!srcProp)
  591. srcProp = dstProp;
  592. if (field.resolvedType) {
  593. if (field.resolvedType instanceof Enum) gen
  594. ("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s", dstProp, fieldIndex, srcProp, srcProp, fieldIndex, srcProp, srcProp);
  595. else gen
  596. ("d%s=types[%i].toObject(m%s,o,q+1)", dstProp, fieldIndex, srcProp);
  597. } else {
  598. var isUnsigned = false;
  599. switch (field.type) {
  600. case "double":
  601. case "float": gen
  602. ("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", dstProp, srcProp, srcProp, srcProp);
  603. break;
  604. case "uint64":
  605. case "fixed64":
  606. isUnsigned = true;
  607. // eslint-disable-next-line no-fallthrough
  608. case "int64":
  609. case "sint64":
  610. case "sfixed64": gen
  611. ("if(typeof BigInt!==\"undefined\"&&o.longs===BigInt)")
  612. ("d%s=typeof m%s===\"number\"?BigInt(m%s):util.Long.fromBits(m%s.low>>>0,m%s.high>>>0,%j).toBigInt()", dstProp, srcProp, srcProp, srcProp, srcProp, isUnsigned)
  613. ("else if(typeof m%s===\"number\")", srcProp)
  614. ("d%s=o.longs===String?String(m%s):m%s", dstProp, srcProp, srcProp)
  615. ("else") // Long-like
  616. ("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s", dstProp, srcProp, srcProp, srcProp, isUnsigned ? "true": "", srcProp);
  617. break;
  618. case "bytes": gen
  619. ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", dstProp, srcProp, srcProp, srcProp, srcProp);
  620. break;
  621. default: gen
  622. ("d%s=m%s", dstProp, srcProp);
  623. break;
  624. }
  625. }
  626. return gen;
  627. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  628. }
  629. /**
  630. * Generates a runtime message to plain object converter specific to the specified message type.
  631. * @param {Type} mtype Message type
  632. * @returns {Codegen} Codegen instance
  633. */
  634. converter.toObject = function toObject(mtype) {
  635. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  636. var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);
  637. if (!fields.length)
  638. return util.codegen()("return {}");
  639. var gen = util.codegen(["m", "o", "q"])
  640. ("if(!o)")
  641. ("o={}")
  642. ("if(q===undefined)q=0")
  643. ("if(q>util.recursionLimit)")
  644. ("throw Error(\"max depth exceeded\")")
  645. ("var d={}");
  646. var repeatedFields = [],
  647. mapFields = [],
  648. normalFields = [],
  649. i = 0;
  650. for (; i < fields.length; ++i)
  651. if (!fields[i].partOf)
  652. ( fields[i].resolve().repeated ? repeatedFields
  653. : fields[i].map ? mapFields
  654. : normalFields).push(fields[i]);
  655. if (repeatedFields.length) { gen
  656. ("if(o.arrays||o.defaults){");
  657. for (i = 0; i < repeatedFields.length; ++i) gen
  658. ("d%s=[]", util.safeProp(repeatedFields[i].name));
  659. gen
  660. ("}");
  661. }
  662. if (mapFields.length) { gen
  663. ("if(o.objects||o.defaults){");
  664. for (i = 0; i < mapFields.length; ++i) gen
  665. ("d%s={}", util.safeProp(mapFields[i].name));
  666. gen
  667. ("}");
  668. }
  669. if (normalFields.length) { gen
  670. ("if(o.defaults){");
  671. for (i = 0; i < normalFields.length; ++i) {
  672. var field = normalFields[i],
  673. prop = util.safeProp(field.name);
  674. if (field.resolvedType instanceof Enum) gen
  675. ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);
  676. else if (field.long) gen
  677. ("if(util.Long){")
  678. ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)
  679. ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():typeof BigInt!==\"undefined\"&&o.longs===BigInt?n.toBigInt():n", prop)
  680. ("}else")
  681. ("d%s=o.longs===String?%j:typeof BigInt!==\"undefined\"&&o.longs===BigInt?BigInt(%j):%i", prop, field.typeDefault.toString(), field.typeDefault.toString(), field.typeDefault.toNumber());
  682. else if (field.bytes) {
  683. var arrayDefault = Array.prototype.slice.call(field.typeDefault);
  684. gen
  685. ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault))
  686. ("else{")
  687. ("d%s=%j", prop, arrayDefault)
  688. ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop)
  689. ("}");
  690. } else gen
  691. ("d%s=%j", prop, field.typeDefault); // also messages (=null)
  692. } gen
  693. ("}");
  694. }
  695. var hasKs2 = false;
  696. for (i = 0; i < fields.length; ++i) {
  697. var field = fields[i],
  698. index = mtype._fieldsArray.indexOf(field),
  699. prop = util.safeProp(field.name);
  700. if (field.map) {
  701. if (!hasKs2) { hasKs2 = true; gen
  702. ("var ks2");
  703. } gen
  704. ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)
  705. ("d%s={}", prop);
  706. var longKey = types.long[field.keyType] !== undefined,
  707. srcProp = prop + "[ks2[j]]";
  708. gen
  709. ("for(var j=0;j<ks2.length;++j){");
  710. if (longKey) gen
  711. ("var k2=util.longFromKey(ks2[j],%j).toString()", field.keyType === "uint64" || field.keyType === "fixed64");
  712. gen
  713. ("if(ks2[j]===\"__proto__\")")
  714. ("util.makeProp(d%s,ks2[j])", prop);
  715. genValuePartial_toObject(gen, field, /* sorted */ index, longKey ? prop + "[k2]" : srcProp, srcProp)
  716. ("}");
  717. } else if (field.repeated) { gen
  718. ("if(m%s&&m%s.length){", prop, prop)
  719. ("d%s=Array(m%s.length)", prop, prop)
  720. ("for(var j=0;j<m%s.length;++j){", prop);
  721. genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[j]")
  722. ("}");
  723. } else { gen
  724. ("if(m%s!=null&&Object.hasOwnProperty.call(m,%j)){", prop, field.name); // !== undefined && !== null
  725. genValuePartial_toObject(gen, field, /* sorted */ index, prop);
  726. if (field.partOf && !field.partOf.isProto3Optional) gen
  727. ("if(o.oneofs)")
  728. ("d%s=%j", util.safeProp(field.partOf.name), field.name);
  729. }
  730. gen
  731. ("}");
  732. }
  733. return gen
  734. ("return d");
  735. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  736. };
  737. },{"27":27,"28":28,"6":6}],4:[function(require,module,exports){
  738. "use strict";
  739. module.exports = decoder;
  740. var Enum = require(6),
  741. types = require(27),
  742. util = require(28);
  743. function missing(field) {
  744. return "missing required '" + field.name + "'";
  745. }
  746. function stringMethod(field) {
  747. return field._features.utf8_validation === "VERIFY" ? "stringVerify" : "string";
  748. }
  749. /**
  750. * Generates a decoder specific to the specified message type.
  751. * @param {Type} mtype Message type
  752. * @returns {Codegen} Codegen instance
  753. */
  754. function decoder(mtype) {
  755. /* eslint-disable no-unexpected-multiline */
  756. var hasMapField = false,
  757. hasImplicitPresenceField = false,
  758. i = 0;
  759. for (; i < mtype.fieldsArray.length; ++i) {
  760. var pfield = mtype._fieldsArray[i];
  761. if (pfield.map)
  762. hasMapField = true;
  763. if (!pfield.repeated && !pfield.map && !pfield.hasPresence)
  764. hasImplicitPresenceField = true;
  765. }
  766. var gen = util.codegen(["r", "l", "z", "q", "g"])
  767. ("if(!(r instanceof Reader))")
  768. ("r=Reader.create(r)")
  769. ("if(q===undefined)q=0")
  770. ("if(q>Reader.recursionLimit)")
  771. ("throw Error(\"max depth exceeded\")")
  772. ("var c=l===undefined?r.len:r.pos+l,m=g||new C" + (hasMapField ? ",k,v" : hasImplicitPresenceField ? ",v" : ""))
  773. ("while(r.pos<c){")
  774. ("var s=r.pos")
  775. ("var t=r.tag()")
  776. ("if(t===z){")
  777. ("z=undefined")
  778. ("break")
  779. ("}");
  780. if (mtype.fieldsArray.length) gen
  781. ("var u=t&7")
  782. ("switch(t>>>=3){");
  783. for (i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {
  784. var field = mtype._fieldsArray[i].resolve(),
  785. type = field.resolvedType instanceof Enum ? "int32" : field.type,
  786. ref = "m" + util.safeProp(field.name);
  787. // Map fields
  788. if (field.map) {
  789. gen
  790. ("case %i:{", field.id)
  791. ("if(u!==2)")
  792. ("break")
  793. ("if(%s===util.emptyObject)", ref)
  794. ("%s={}", ref)
  795. ("var c2=r.uint32()+r.pos");
  796. if (types.defaults[field.keyType] !== undefined) gen
  797. ("k=%j", types.defaults[field.keyType]);
  798. else gen
  799. ("k=null");
  800. if (types.long[type] !== undefined) gen
  801. ("v=util.Long?util.Long.fromNumber(0,%j):0", type === "uint64" || type === "fixed64");
  802. else if (types.defaults[type] !== undefined) gen
  803. ("v=%j", types.defaults[type]);
  804. else gen
  805. ("v=null");
  806. gen
  807. ("while(r.pos<c2){")
  808. ("var t2=r.tag()")
  809. ("u=t2&7")
  810. ("switch(t2>>>=3){")
  811. ("case 1:")
  812. ("if(u!==%i)", types.mapKey[field.keyType])
  813. ("break")
  814. ("k=r.%s()", field.keyType === "string" ? stringMethod(field) : field.keyType)
  815. ("continue")
  816. ("case 2:")
  817. ("if(u!==%i)", types.basic[type] === undefined ? 2 : types.basic[type])
  818. ("break");
  819. if (types.basic[type] === undefined) gen
  820. ("v=types[%i].decode(r,r.uint32(),undefined,q+1)", i); // can't be groups
  821. else gen
  822. ("v=r.%s()", type === "string" ? stringMethod(field) : type);
  823. gen
  824. ("continue")
  825. ("}")
  826. ("r.skipType(u,q,t2)")
  827. ("}");
  828. var val = types.basic[type] === undefined ? "v||new types[" + i + "].ctor" : "v";
  829. if (types.long[field.keyType] !== undefined) gen
  830. ("%s[typeof k===\"object\"?util.longToHash(k):k]=%s", ref, val);
  831. else {
  832. if (field.keyType === "string") gen
  833. ("if(k===\"__proto__\")")
  834. ("util.makeProp(%s,k)", ref);
  835. gen
  836. ("%s[k]=%s", ref, val);
  837. }
  838. // Repeated fields
  839. } else if (field.repeated) { gen
  840. ("case %i:", field.id)
  841. ("{");
  842. // Packable (always check for forward and backward compatiblity)
  843. if (types.packed[type] !== undefined) gen
  844. ("if(u===2){")
  845. ("if(!(%s&&%s.length))", ref, ref)
  846. ("%s=[]", ref)
  847. ("var c2=r.uint32()+r.pos")
  848. ("while(r.pos<c2)")
  849. ("%s.push(r.%s())", ref, type)
  850. ("continue")
  851. ("}");
  852. // Non-packed
  853. gen
  854. ("if(u!==%i)", types.basic[type] === undefined ? field.delimited ? 3 : 2 : types.basic[type])
  855. ("break")
  856. ("if(!(%s&&%s.length))", ref, ref)
  857. ("%s=[]", ref);
  858. if (types.basic[type] === undefined) {
  859. if (field.delimited) gen
  860. ("%s.push(types[%i].decode(r,undefined,%i,q+1))", ref, i, field.id * 8 + 4);
  861. else gen
  862. ("%s.push(types[%i].decode(r,r.uint32(),undefined,q+1))", ref, i);
  863. } else gen
  864. ("%s.push(r.%s())", ref, type === "string" ? stringMethod(field) : type);
  865. // Non-repeated
  866. } else if (types.basic[type] === undefined) {
  867. gen
  868. ("case %i:{", field.id)
  869. ("if(u!==%i)", field.delimited ? 3 : 2)
  870. ("break");
  871. if (field.delimited) gen
  872. ("%s=types[%i].decode(r,undefined,%i,q+1,%s)", ref, i, field.id * 8 + 4, ref);
  873. else gen
  874. ("%s=types[%i].decode(r,r.uint32(),undefined,q+1,%s)", ref, i, ref);
  875. }
  876. else if (field.hasPresence) {
  877. gen
  878. ("case %i:{", field.id)
  879. ("if(u!==%i)", types.basic[type])
  880. ("break")
  881. ("%s=r.%s()", ref, type === "string" ? stringMethod(field) : type);
  882. } else {
  883. gen
  884. ("case %i:{", field.id)
  885. ("if(u!==%i)", types.basic[type])
  886. ("break");
  887. if (field.resolvedType instanceof Enum && field.typeDefault !== 0) gen
  888. // TODO: Protoc rejects open enums whose first value is not zero.
  889. // We should do the same, but for v8 this would be a regression.
  890. ("if((v=r.%s())!==%j)", type, field.typeDefault);
  891. else if (type === "string") gen
  892. ("if((v=r.%s()).length)", stringMethod(field));
  893. else if (type === "bytes") gen
  894. ("if((v=r.%s()).length)", type);
  895. else if (types.long[type] !== undefined) gen
  896. ("if(typeof(v=r.%s())===\"object\"?v.low||v.high:v!==0)", type);
  897. else if (type === "double" || type === "float") gen
  898. ("if((v=r.%s())!==0)", type);
  899. else gen
  900. ("if(v=r.%s())", type);
  901. gen
  902. ("%s=v", ref)
  903. ("else")
  904. ("delete %s", ref); // rare/odd case: later default clears earlier non-default
  905. }
  906. if (field.partOf) gen
  907. ("m%s=%j", util.safeProp(field.partOf.name), field.name);
  908. gen
  909. ("continue")
  910. ("}");
  911. }
  912. if (i) gen
  913. ("}");
  914. // Unknown fields
  915. gen
  916. ("r.skipType(%s,q,t)", i ? "u" : "t&7")
  917. ("if(!r.discardUnknown){")
  918. ("util.makeProp(m,\"$unknowns\",false);")
  919. ("(m.$unknowns||(m.$unknowns=[])).push(r.raw(s,r.pos))")
  920. ("}")
  921. ("}")
  922. ("if(z!==undefined)")
  923. ("throw Error(\"missing end group\")");
  924. // Field presence
  925. for (i = 0; i < mtype._fieldsArray.length; ++i) {
  926. var rfield = mtype._fieldsArray[i];
  927. if (rfield.required) gen
  928. ("if(!Object.hasOwnProperty.call(m,%j))", rfield.name)
  929. ("throw util.ProtocolError(%j,{instance:m})", missing(rfield));
  930. }
  931. return gen
  932. ("return m");
  933. /* eslint-enable no-unexpected-multiline */
  934. }
  935. },{"27":27,"28":28,"6":6}],5:[function(require,module,exports){
  936. "use strict";
  937. module.exports = encoder;
  938. var Enum = require(6),
  939. types = require(27),
  940. util = require(28);
  941. /**
  942. * Generates a partial message type encoder.
  943. * @param {Codegen} gen Codegen instance
  944. * @param {Field} field Reflected field
  945. * @param {number} fieldIndex Field index
  946. * @param {string} ref Variable reference
  947. * @returns {Codegen} Codegen instance
  948. * @ignore
  949. */
  950. function genTypePartial(gen, field, fieldIndex, ref) {
  951. return field.delimited
  952. ? gen("types[%i].encode(%s,w.uint32(%i),q+1).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0)
  953. : gen("types[%i].encode(%s,w.uint32(%i).fork(),q+1).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0);
  954. }
  955. /**
  956. * Generates an encoder specific to the specified message type.
  957. * @param {Type} mtype Message type
  958. * @returns {Codegen} Codegen instance
  959. */
  960. function encoder(mtype) {
  961. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  962. var gen = util.codegen(["m", "w", "q"])
  963. ("if(!w)")
  964. ("w=Writer.create()")
  965. ("if(q===undefined)q=0")
  966. ("if(q>util.recursionLimit)")
  967. ("throw Error(\"max depth exceeded\")");
  968. var i, ref;
  969. // "when a message is serialized its known fields should be written sequentially by field number"
  970. var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);
  971. for (var i = 0; i < fields.length; ++i) {
  972. var field = fields[i].resolve(),
  973. index = mtype._fieldsArray.indexOf(field),
  974. type = field.resolvedType instanceof Enum ? "int32" : field.type,
  975. wireType = types.basic[type];
  976. ref = "m" + util.safeProp(field.name);
  977. // Map fields
  978. if (field.map) {
  979. gen
  980. ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null
  981. ("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", ref);
  982. if (field.keyType === "bool") gen
  983. ("w.uint32(%i).fork().uint32(%i).bool(util.boolFromKey(ks[i]))", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType]);
  984. else if (types.long[field.keyType] !== undefined) gen
  985. ("w.uint32(%i).fork().uint32(%i).%s(util.longFromKey(ks[i],%j))", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType, field.keyType === "uint64" || field.keyType === "fixed64");
  986. else gen
  987. ("w.uint32(%i).fork().uint32(%i).%s(ks[i])", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);
  988. if (wireType === undefined) gen
  989. ("types[%i].encode(%s[ks[i]],w.uint32(18).fork(),q+1).ldelim().ldelim()", index, ref); // can't be groups
  990. else gen
  991. (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref);
  992. gen
  993. ("}")
  994. ("}");
  995. // Repeated fields
  996. } else if (field.repeated) { gen
  997. ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null
  998. // Packed repeated
  999. if (field.packed && types.packed[type] !== undefined) { gen
  1000. ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)
  1001. ("for(var i=0;i<%s.length;++i)", ref)
  1002. ("w.%s(%s[i])", type, ref)
  1003. ("w.ldelim()");
  1004. // Non-packed
  1005. } else { gen
  1006. ("for(var i=0;i<%s.length;++i)", ref);
  1007. if (wireType === undefined)
  1008. genTypePartial(gen, field, index, ref + "[i]");
  1009. else gen
  1010. ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref);
  1011. } gen
  1012. ("}");
  1013. // Non-repeated
  1014. } else {
  1015. if (!field.required) gen
  1016. ("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null
  1017. if (wireType === undefined)
  1018. genTypePartial(gen, field, index, ref);
  1019. else gen
  1020. ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref);
  1021. }
  1022. }
  1023. return gen
  1024. ("if(m.$unknowns!=null&&Object.hasOwnProperty.call(m,\"$unknowns\"))")
  1025. ("for(var i=0;i<m.$unknowns.length;++i)")
  1026. ("w.raw(m.$unknowns[i])")
  1027. ("return w");
  1028. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1029. }
  1030. },{"27":27,"28":28,"6":6}],6:[function(require,module,exports){
  1031. "use strict";
  1032. module.exports = Enum;
  1033. // extends ReflectionObject
  1034. var ReflectionObject = require(15);
  1035. ((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum";
  1036. var Namespace = require(14),
  1037. util = require(28);
  1038. /**
  1039. * Constructs a new enum instance.
  1040. * @classdesc Reflected enum.
  1041. * @extends ReflectionObject
  1042. * @constructor
  1043. * @param {string} name Unique name within its namespace
  1044. * @param {Object.<string,number>} [values] Enum values as an object, by name
  1045. * @param {Object.<string,*>} [options] Declared options
  1046. * @param {string} [comment] The comment for this enum
  1047. * @param {Object.<string,string|null>} [comments] The value comments for this enum
  1048. * @param {Object.<string,Object<string,*>>|undefined} [valuesOptions] The value options for this enum
  1049. */
  1050. function Enum(name, values, options, comment, comments, valuesOptions) {
  1051. ReflectionObject.call(this, name, options);
  1052. if (values && typeof values !== "object")
  1053. throw TypeError("values must be an object");
  1054. /**
  1055. * Enum values by id.
  1056. * @type {Object.<number,string>}
  1057. */
  1058. this.valuesById = {};
  1059. /**
  1060. * Enum values by name.
  1061. * @type {Object.<string,number>}
  1062. */
  1063. this.values = Object.create(this.valuesById); // toJSON, marker
  1064. /**
  1065. * Enum comment text.
  1066. * @type {string|null}
  1067. */
  1068. this.comment = comment;
  1069. /**
  1070. * Value comment texts, if any.
  1071. * @type {Object.<string,string|null>}
  1072. */
  1073. this.comments = comments || {};
  1074. /**
  1075. * Values options, if any
  1076. * @type {Object<string, Object<string, *>>|undefined}
  1077. */
  1078. this.valuesOptions = valuesOptions;
  1079. /**
  1080. * Resolved values features, if any
  1081. * @type {Object<string, Object<string, *>>|undefined}
  1082. */
  1083. this._valuesFeatures = {};
  1084. /**
  1085. * Reserved ranges, if any.
  1086. * @type {Array.<number[]|string>}
  1087. */
  1088. this.reserved = undefined; // toJSON
  1089. // Note that values inherit valuesById on their prototype which makes them a TypeScript-
  1090. // compatible enum. This is used by pbts to write actual enum definitions that work for
  1091. // static and reflection code alike instead of emitting generic object definitions.
  1092. if (values)
  1093. for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)
  1094. if (keys[i] !== "__proto__" && typeof values[keys[i]] === "number") // use forward entries only
  1095. this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];
  1096. }
  1097. /**
  1098. * @override
  1099. */
  1100. Enum.prototype._resolveFeatures = function _resolveFeatures(edition) {
  1101. edition = this._edition || edition;
  1102. ReflectionObject.prototype._resolveFeatures.call(this, edition);
  1103. Object.keys(this.values).forEach(key => {
  1104. var parentFeaturesCopy = util.merge({}, this._features);
  1105. this._valuesFeatures[key] = util.merge(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features || {});
  1106. });
  1107. return this;
  1108. };
  1109. /**
  1110. * Enum descriptor.
  1111. * @interface IEnum
  1112. * @property {string} [edition] Edition
  1113. * @property {Object.<string,number>} values Enum values
  1114. * @property {Object.<string,*>} [options] Enum options
  1115. * @property {Object.<string,Object.<string,*>>} [valuesOptions] Enum value options
  1116. * @property {Array.<number[]|string>} [reserved] Reserved ranges
  1117. * @property {string|null} [comment] Enum comment
  1118. * @property {Object.<string,string|null>} [comments] Value comments
  1119. */
  1120. /**
  1121. * Constructs an enum from an enum descriptor.
  1122. * @param {string} name Enum name
  1123. * @param {IEnum} json Enum descriptor
  1124. * @returns {Enum} Created enum
  1125. * @throws {TypeError} If arguments are invalid
  1126. */
  1127. Enum.fromJSON = function fromJSON(name, json) {
  1128. var enm = new Enum(name, json.values, json.options, json.comment, json.comments, json.valuesOptions);
  1129. enm.reserved = json.reserved;
  1130. if (json.edition)
  1131. enm._edition = json.edition;
  1132. enm._defaultEdition = "proto3"; // For backwards-compatibility.
  1133. return enm;
  1134. };
  1135. /**
  1136. * Converts this enum to an enum descriptor.
  1137. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  1138. * @returns {IEnum} Enum descriptor
  1139. */
  1140. Enum.prototype.toJSON = function toJSON(toJSONOptions) {
  1141. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  1142. return util.toObject([
  1143. "edition" , this._editionToJSON(),
  1144. "options" , this.options,
  1145. "valuesOptions" , this.valuesOptions,
  1146. "values" , this.values,
  1147. "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,
  1148. "comment" , keepComments ? this.comment : undefined,
  1149. "comments" , keepComments ? this.comments : undefined
  1150. ]);
  1151. };
  1152. /**
  1153. * Adds a value to this enum.
  1154. * @param {string} name Value name
  1155. * @param {number} id Value id
  1156. * @param {string} [comment] Comment, if any
  1157. * @param {Object.<string, *>|undefined} [options] Options, if any
  1158. * @returns {Enum} `this`
  1159. * @throws {TypeError} If arguments are invalid
  1160. * @throws {Error} If there is already a value with this name or id
  1161. */
  1162. Enum.prototype.add = function add(name, id, comment, options) {
  1163. // utilized by the parser but not by .fromJSON
  1164. if (!util.isString(name))
  1165. throw TypeError("name must be a string");
  1166. if (!util.isInteger(id))
  1167. throw TypeError("id must be an integer");
  1168. if (name === "__proto__")
  1169. return this;
  1170. if (this.values[name] !== undefined)
  1171. throw Error("duplicate name '" + name + "' in " + this);
  1172. if (this.isReservedId(id))
  1173. throw Error("id " + id + " is reserved in " + this);
  1174. if (this.isReservedName(name))
  1175. throw Error("name '" + name + "' is reserved in " + this);
  1176. if (this.valuesById[id] !== undefined) {
  1177. if (!(this.options && this.options.allow_alias))
  1178. throw Error("duplicate id " + id + " in " + this);
  1179. this.values[name] = id;
  1180. } else
  1181. this.valuesById[this.values[name] = id] = name;
  1182. if (options) {
  1183. if (this.valuesOptions === undefined)
  1184. this.valuesOptions = {};
  1185. this.valuesOptions[name] = options || null;
  1186. }
  1187. this.comments[name] = comment || null;
  1188. return this;
  1189. };
  1190. /**
  1191. * Removes a value from this enum
  1192. * @param {string} name Value name
  1193. * @returns {Enum} `this`
  1194. * @throws {TypeError} If arguments are invalid
  1195. * @throws {Error} If `name` is not a name of this enum
  1196. */
  1197. Enum.prototype.remove = function remove(name) {
  1198. if (!util.isString(name))
  1199. throw TypeError("name must be a string");
  1200. var val = this.values[name];
  1201. if (val == null)
  1202. throw Error("name '" + name + "' does not exist in " + this);
  1203. delete this.valuesById[val];
  1204. delete this.values[name];
  1205. delete this.comments[name];
  1206. if (this.valuesOptions)
  1207. delete this.valuesOptions[name];
  1208. return this;
  1209. };
  1210. /**
  1211. * Tests if the specified id is reserved.
  1212. * @param {number} id Id to test
  1213. * @returns {boolean} `true` if reserved, otherwise `false`
  1214. */
  1215. Enum.prototype.isReservedId = function isReservedId(id) {
  1216. return Namespace.isReservedId(this.reserved, id);
  1217. };
  1218. /**
  1219. * Tests if the specified name is reserved.
  1220. * @param {string} name Name to test
  1221. * @returns {boolean} `true` if reserved, otherwise `false`
  1222. */
  1223. Enum.prototype.isReservedName = function isReservedName(name) {
  1224. return Namespace.isReservedName(this.reserved, name);
  1225. };
  1226. },{"14":14,"15":15,"28":28}],7:[function(require,module,exports){
  1227. "use strict";
  1228. module.exports = Field;
  1229. // extends ReflectionObject
  1230. var ReflectionObject = require(15);
  1231. ((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field";
  1232. var Enum = require(6),
  1233. types = require(27),
  1234. util = require(28);
  1235. var Type; // cyclic
  1236. var ruleRe = /^(?:required|optional|repeated)$/;
  1237. /**
  1238. * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.
  1239. * @name Field
  1240. * @classdesc Reflected message field.
  1241. * @extends FieldBase
  1242. * @constructor
  1243. * @param {string} name Unique name within its namespace
  1244. * @param {number} id Unique id within its namespace
  1245. * @param {string} type Value type
  1246. * @param {string|Object.<string,*>} [rule="optional"] Field rule
  1247. * @param {string|Object.<string,*>} [extend] Extended type if different from parent
  1248. * @param {Object.<string,*>} [options] Declared options
  1249. */
  1250. /**
  1251. * Constructs a field from a field descriptor.
  1252. * @param {string} name Field name
  1253. * @param {IField} json Field descriptor
  1254. * @returns {Field} Created field
  1255. * @throws {TypeError} If arguments are invalid
  1256. */
  1257. Field.fromJSON = function fromJSON(name, json) {
  1258. var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);
  1259. if (json.edition)
  1260. field._edition = json.edition;
  1261. if (json.protoName)
  1262. field.protoName = json.protoName;
  1263. if (json.jsonName !== undefined)
  1264. field.jsonName = json.jsonName;
  1265. else if (json.options && json.options.json_name !== undefined)
  1266. field.jsonName = json.options.json_name;
  1267. field._defaultEdition = "proto3"; // For backwards-compatibility.
  1268. return field;
  1269. };
  1270. /**
  1271. * Not an actual constructor. Use {@link Field} instead.
  1272. * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.
  1273. * @exports FieldBase
  1274. * @extends ReflectionObject
  1275. * @constructor
  1276. * @param {string} name Unique name within its namespace
  1277. * @param {number} id Unique id within its namespace
  1278. * @param {string} type Value type
  1279. * @param {string|Object.<string,*>} [rule="optional"] Field rule
  1280. * @param {string|Object.<string,*>} [extend] Extended type if different from parent
  1281. * @param {Object.<string,*>} [options] Declared options
  1282. * @param {string} [comment] Comment associated with this field
  1283. */
  1284. function Field(name, id, type, rule, extend, options, comment) {
  1285. if (util.isObject(rule)) {
  1286. comment = extend;
  1287. options = rule;
  1288. rule = extend = undefined;
  1289. } else if (util.isObject(extend)) {
  1290. comment = options;
  1291. options = extend;
  1292. extend = undefined;
  1293. }
  1294. ReflectionObject.call(this, name, options);
  1295. if (!util.isInteger(id) || id < 0)
  1296. throw TypeError("id must be a non-negative integer");
  1297. if (!util.isString(type))
  1298. throw TypeError("type must be a string");
  1299. if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))
  1300. throw TypeError("rule must be a string rule");
  1301. if (extend !== undefined && !util.isString(extend))
  1302. throw TypeError("extend must be a string");
  1303. /**
  1304. * Field rule, if any.
  1305. * @type {string|undefined}
  1306. */
  1307. this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON
  1308. /**
  1309. * Field type.
  1310. * @type {string}
  1311. */
  1312. this.type = type; // toJSON
  1313. /**
  1314. * Unique field id.
  1315. * @type {number}
  1316. */
  1317. this.id = id; // toJSON, marker
  1318. /**
  1319. * Extended type if different from parent.
  1320. * @type {string|undefined}
  1321. */
  1322. this.extend = extend || undefined; // toJSON
  1323. /**
  1324. * Whether this field is repeated.
  1325. * @type {boolean}
  1326. */
  1327. this.repeated = rule === "repeated";
  1328. /**
  1329. * Whether this field is a map or not.
  1330. * @type {boolean}
  1331. */
  1332. this.map = false;
  1333. /**
  1334. * Message this field belongs to.
  1335. * @type {Type|null}
  1336. */
  1337. this.message = null;
  1338. /**
  1339. * OneOf this field belongs to, if any,
  1340. * @type {OneOf|null}
  1341. */
  1342. this.partOf = null;
  1343. /**
  1344. * The field type's default value.
  1345. * @type {*}
  1346. */
  1347. this.typeDefault = null;
  1348. /**
  1349. * The field's default value on prototypes.
  1350. * @type {*}
  1351. */
  1352. this.defaultValue = null;
  1353. /**
  1354. * Whether this field's value should be treated as a long.
  1355. * @type {boolean}
  1356. */
  1357. this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;
  1358. /**
  1359. * Whether this field's value is a buffer.
  1360. * @type {boolean}
  1361. */
  1362. this.bytes = type === "bytes";
  1363. /**
  1364. * Resolved type if not a basic type.
  1365. * @type {Type|Enum|null}
  1366. */
  1367. this.resolvedType = null;
  1368. /**
  1369. * Sister-field within the extended type if a declaring extension field.
  1370. * @type {Field|null}
  1371. */
  1372. this.extensionField = null;
  1373. /**
  1374. * Sister-field within the declaring namespace if an extended field.
  1375. * @type {Field|null}
  1376. */
  1377. this.declaringField = null;
  1378. /**
  1379. * Comment for this field.
  1380. * @type {string|null}
  1381. */
  1382. this.comment = comment;
  1383. /**
  1384. * Field name as declared in the .proto source, if different from `name`.
  1385. * @type {string|undefined}
  1386. */
  1387. this.protoName = undefined;
  1388. /**
  1389. * JSON name, if different from the derived default.
  1390. * @type {string|undefined}
  1391. */
  1392. this.jsonName = undefined;
  1393. }
  1394. /**
  1395. * Determines whether this field is required.
  1396. * @name Field#required
  1397. * @type {boolean}
  1398. * @readonly
  1399. */
  1400. Object.defineProperty(Field.prototype, "required", {
  1401. get: function() {
  1402. return this._features.field_presence === "LEGACY_REQUIRED";
  1403. }
  1404. });
  1405. /**
  1406. * Determines whether this field is not required.
  1407. * @name Field#optional
  1408. * @type {boolean}
  1409. * @readonly
  1410. */
  1411. Object.defineProperty(Field.prototype, "optional", {
  1412. get: function() {
  1413. return !this.required;
  1414. }
  1415. });
  1416. /**
  1417. * Determines whether this field uses tag-delimited encoding. In proto2 this
  1418. * corresponded to group syntax.
  1419. * @name Field#delimited
  1420. * @type {boolean}
  1421. * @readonly
  1422. */
  1423. Object.defineProperty(Field.prototype, "delimited", {
  1424. get: function() {
  1425. return this.resolvedType instanceof Type &&
  1426. this._features.message_encoding === "DELIMITED";
  1427. }
  1428. });
  1429. /**
  1430. * Determines whether this field is packed. Only relevant when repeated.
  1431. * @name Field#packed
  1432. * @type {boolean}
  1433. * @readonly
  1434. */
  1435. Object.defineProperty(Field.prototype, "packed", {
  1436. get: function() {
  1437. return this._features.repeated_field_encoding === "PACKED";
  1438. }
  1439. });
  1440. /**
  1441. * Determines whether this field tracks presence.
  1442. * @name Field#hasPresence
  1443. * @type {boolean}
  1444. * @readonly
  1445. */
  1446. Object.defineProperty(Field.prototype, "hasPresence", {
  1447. get: function() {
  1448. if (this.repeated || this.map) {
  1449. return false;
  1450. }
  1451. return this.partOf || // oneofs
  1452. this.declaringField || this.extensionField || // extensions
  1453. this._features.field_presence !== "IMPLICIT";
  1454. }
  1455. });
  1456. /**
  1457. * The field name as declared in the .proto source (snake_case). Populated on resolve,
  1458. * falling back to `name`. Mirrors `FieldDescriptorProto.name`.
  1459. * @name Field#protoName
  1460. * @type {string}
  1461. * @readonly
  1462. */
  1463. /**
  1464. * The JSON name of this field (lowerCamelCase per protoc's `ToJsonName`, or an
  1465. * explicit `[json_name]`). Populated on resolve. This is the key used on ProtoJSON output.
  1466. * @name Field#jsonName
  1467. * @type {string}
  1468. * @readonly
  1469. */
  1470. /**
  1471. * @override
  1472. */
  1473. Field.prototype.setOption = function setOption(name, value, ifNotSet) {
  1474. return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);
  1475. };
  1476. /**
  1477. * Field descriptor.
  1478. * @interface IField
  1479. * @property {string} [edition] Edition
  1480. * @property {string} [rule="optional"] Field rule
  1481. * @property {string} type Field type
  1482. * @property {number} id Field id
  1483. * @property {Object.<string,*>} [options] Field options
  1484. * @property {string|null} [comment] Field comment
  1485. */
  1486. /**
  1487. * Extension field descriptor.
  1488. * @interface IExtensionField
  1489. * @extends IField
  1490. * @property {string} extend Extended type
  1491. */
  1492. /**
  1493. * Converts this field to a field descriptor.
  1494. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  1495. * @returns {IField} Field descriptor
  1496. */
  1497. Field.prototype.toJSON = function toJSON(toJSONOptions) {
  1498. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  1499. return util.toObject([
  1500. "edition" , this._editionToJSON(),
  1501. "rule" , this.rule !== "optional" && this.rule || undefined,
  1502. "type" , this.type,
  1503. "id" , this.id,
  1504. "extend" , this.extend,
  1505. "protoName" , this.protoName !== this.name ? this.protoName : undefined,
  1506. "jsonName" , this.jsonName !== util.jsonName(this.protoName || this.name) ? this.jsonName : undefined,
  1507. "options" , this.options,
  1508. "comment" , keepComments ? this.comment : undefined
  1509. ]);
  1510. };
  1511. /**
  1512. * Resolves this field's type references.
  1513. * @returns {Field} `this`
  1514. * @throws {Error} If any reference cannot be resolved
  1515. */
  1516. Field.prototype.resolve = function resolve() {
  1517. if (this.resolved)
  1518. return this;
  1519. if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it
  1520. this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);
  1521. if (this.resolvedType instanceof Type)
  1522. this.typeDefault = null;
  1523. else // instanceof Enum
  1524. this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined
  1525. } else if (this.options && this.options.proto3_optional) {
  1526. // proto3 scalar value marked optional; should default to null
  1527. this.typeDefault = null;
  1528. }
  1529. // use explicitly set default value if present
  1530. if (this.options && this.options["default"] != null) {
  1531. this.typeDefault = this.options["default"];
  1532. if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string")
  1533. this.typeDefault = this.resolvedType.values[this.typeDefault];
  1534. }
  1535. // remove unnecessary options
  1536. if (this.options) {
  1537. if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))
  1538. delete this.options.packed;
  1539. if (!Object.keys(this.options).length)
  1540. this.options = undefined;
  1541. }
  1542. // convert to internal data type if necesssary
  1543. if (this.long) {
  1544. this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type === "uint64" || this.type === "fixed64");
  1545. /* istanbul ignore else */
  1546. if (Object.freeze)
  1547. Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)
  1548. } else if (this.bytes && typeof this.typeDefault === "string") {
  1549. var buf;
  1550. if (util.base64.test(this.typeDefault))
  1551. util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);
  1552. else
  1553. util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);
  1554. this.typeDefault = buf;
  1555. }
  1556. // take special care of maps and repeated fields
  1557. if (this.map)
  1558. this.defaultValue = util.emptyObject;
  1559. else if (this.repeated)
  1560. this.defaultValue = util.emptyArray;
  1561. else
  1562. this.defaultValue = this.typeDefault;
  1563. // ensure proper value on prototype
  1564. if (this.parent instanceof Type && this.parent._ctor)
  1565. this.parent._ctor.prototype[this.name] = this.defaultValue;
  1566. // derive the proto/JSON names
  1567. if (this.protoName === undefined)
  1568. this.protoName = this.name;
  1569. if (this.jsonName === undefined)
  1570. this.jsonName = util.jsonName(this.protoName);
  1571. return ReflectionObject.prototype.resolve.call(this);
  1572. };
  1573. /**
  1574. * Infers field features from legacy syntax that may have been specified differently.
  1575. * in older editions.
  1576. * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions
  1577. * @returns {object} The feature values to override
  1578. */
  1579. Field.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) {
  1580. if (edition !== "proto2" && edition !== "proto3") {
  1581. return {};
  1582. }
  1583. var features = {};
  1584. if (this.rule === "required") {
  1585. features.field_presence = "LEGACY_REQUIRED";
  1586. }
  1587. if (this.parent && types.defaults[this.type] === undefined) {
  1588. // We can't use resolvedType because types may not have been resolved yet. However,
  1589. // legacy groups are always in the same scope as the field so we don't have to do a
  1590. // full scan of the tree.
  1591. var type = this.parent.get(this.type.split(".").pop());
  1592. if (type && type instanceof Type && type.group) {
  1593. features.message_encoding = "DELIMITED";
  1594. }
  1595. }
  1596. if (this.getOption("packed") === true) {
  1597. features.repeated_field_encoding = "PACKED";
  1598. } else if (this.getOption("packed") === false) {
  1599. features.repeated_field_encoding = "EXPANDED";
  1600. }
  1601. return features;
  1602. };
  1603. /**
  1604. * @override
  1605. */
  1606. Field.prototype._resolveFeatures = function _resolveFeatures(edition) {
  1607. return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition);
  1608. };
  1609. /**
  1610. * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).
  1611. * @typedef FieldDecorator
  1612. * @type {function}
  1613. * @param {Object} prototype Target prototype
  1614. * @param {string} fieldName Field name
  1615. * @returns {undefined}
  1616. * @deprecated Legacy TypeScript decorator support. Will be removed in a future release.
  1617. */
  1618. /**
  1619. * Field decorator (TypeScript).
  1620. * @name Field.d
  1621. * @function
  1622. * @param {number} fieldId Field id
  1623. * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type
  1624. * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule
  1625. * @param {T} [defaultValue] Default value
  1626. * @returns {FieldDecorator} Decorator function
  1627. * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]
  1628. * @deprecated Legacy TypeScript decorator support. Will be removed in a future release.
  1629. */
  1630. Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {
  1631. // submessage: decorate the submessage and use its name as the type
  1632. if (typeof fieldType === "function")
  1633. fieldType = util.decorateType(fieldType).name;
  1634. // enum reference: create a reflected copy of the enum and keep reuseing it
  1635. else if (fieldType && typeof fieldType === "object")
  1636. fieldType = util.decorateEnum(fieldType).name;
  1637. return function fieldDecorator(prototype, fieldName) {
  1638. util.decorateType(prototype.constructor)
  1639. .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue }));
  1640. };
  1641. };
  1642. // Sets up cyclic dependencies (called in index-light)
  1643. Field._configure = function configure(Type_) {
  1644. Type = Type_;
  1645. };
  1646. /**
  1647. * Field decorator (TypeScript).
  1648. * @name Field.d
  1649. * @function
  1650. * @param {number} fieldId Field id
  1651. * @param {Constructor<T>|string} fieldType Field type
  1652. * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule
  1653. * @returns {FieldDecorator} Decorator function
  1654. * @template T extends Message<T>
  1655. * @variation 2
  1656. * @deprecated Legacy TypeScript decorator support. Will be removed in a future release.
  1657. */
  1658. // like Field.d but without a default value
  1659. },{"15":15,"27":27,"28":28,"6":6}],8:[function(require,module,exports){
  1660. "use strict";
  1661. exports = module.exports = require(9);
  1662. exports.build = "light";
  1663. /**
  1664. * A node-style callback as used by {@link load} and {@link Root#load}.
  1665. * @typedef LoadCallback
  1666. * @type {function}
  1667. * @param {Error|null} error Error, if any, otherwise `null`
  1668. * @param {Root} [root] Root, if there hasn't been an error
  1669. * @returns {undefined}
  1670. */
  1671. /**
  1672. * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
  1673. * @param {string|string[]} filename One or multiple files to load
  1674. * @param {Root} root Root namespace, defaults to create a new one if omitted.
  1675. * @param {LoadCallback} callback Callback function
  1676. * @returns {undefined}
  1677. * @see {@link Root#load}
  1678. */
  1679. function load(filename, root, callback) {
  1680. if (typeof root === "function") {
  1681. callback = root;
  1682. root = new exports.Root();
  1683. } else if (!root)
  1684. root = new exports.Root();
  1685. return root.load(filename, callback);
  1686. }
  1687. /**
  1688. * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
  1689. * @name load
  1690. * @function
  1691. * @param {string|string[]} filename One or multiple files to load
  1692. * @param {LoadCallback} callback Callback function
  1693. * @returns {undefined}
  1694. * @see {@link Root#load}
  1695. * @variation 2
  1696. */
  1697. // function load(filename:string, callback:LoadCallback):undefined
  1698. /**
  1699. * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.
  1700. * @name load
  1701. * @function
  1702. * @param {string|string[]} filename One or multiple files to load
  1703. * @param {Root} [root] Root namespace, defaults to create a new one if omitted.
  1704. * @returns {Promise<Root>} Promise
  1705. * @see {@link Root#load}
  1706. * @variation 3
  1707. */
  1708. // function load(filename:string, [root:Root]):Promise<Root>
  1709. exports.load = load;
  1710. /**
  1711. * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).
  1712. * @param {string|string[]} filename One or multiple files to load
  1713. * @param {Root} [root] Root namespace, defaults to create a new one if omitted.
  1714. * @returns {Root} Root namespace
  1715. * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
  1716. * @see {@link Root#loadSync}
  1717. */
  1718. function loadSync(filename, root) {
  1719. if (!root)
  1720. root = new exports.Root();
  1721. return root.loadSync(filename);
  1722. }
  1723. exports.loadSync = loadSync;
  1724. // Serialization
  1725. exports.encoder = require(5);
  1726. exports.decoder = require(4);
  1727. exports.verifier = require(42);
  1728. exports.converter = require(3);
  1729. // Reflection
  1730. exports.ReflectionObject = require(15);
  1731. exports.Namespace = require(14);
  1732. exports.Root = require(20);
  1733. exports.Enum = require(6);
  1734. exports.Type = require(26);
  1735. exports.Field = require(7);
  1736. exports.OneOf = require(16);
  1737. exports.MapField = require(11);
  1738. exports.Service = require(24);
  1739. exports.Method = require(13);
  1740. // Runtime
  1741. exports.Message = require(12);
  1742. exports.wrappers = require(43);
  1743. // Utility
  1744. exports.types = require(27);
  1745. exports.util = require(28);
  1746. // Set up possibly cyclic reflection dependencies
  1747. exports.ReflectionObject._configure(exports.Root);
  1748. exports.Namespace._configure(exports.Type, exports.Service, exports.Enum);
  1749. exports.Root._configure(exports.Type, undefined, {});
  1750. exports.Field._configure(exports.Type);
  1751. },{"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"20":20,"24":24,"26":26,"27":27,"28":28,"3":3,"4":4,"42":42,"43":43,"5":5,"6":6,"7":7,"9":9}],9:[function(require,module,exports){
  1752. "use strict";
  1753. /**
  1754. * Build type, one of `"full"`, `"light"` or `"minimal"`.
  1755. * @name build
  1756. * @type {string}
  1757. * @const
  1758. */
  1759. exports.build = "minimal";
  1760. // Serialization
  1761. exports.Writer = require(44);
  1762. exports.BufferWriter = require(45);
  1763. exports.Reader = require(18);
  1764. exports.BufferReader = require(19);
  1765. // Utility
  1766. exports.util = require(37);
  1767. exports.rpc = require(22);
  1768. exports.roots = require(21);
  1769. exports.configure = configure;
  1770. /* istanbul ignore next */
  1771. /**
  1772. * Reconfigures the library according to the environment.
  1773. * @returns {undefined}
  1774. */
  1775. function configure() {
  1776. exports.util._configure();
  1777. exports.Writer._configure(exports.BufferWriter);
  1778. exports.Reader._configure(exports.BufferReader);
  1779. }
  1780. // Set up buffer utility according to the environment
  1781. configure();
  1782. },{"18":18,"19":19,"21":21,"22":22,"37":37,"44":44,"45":45}],10:[function(require,module,exports){
  1783. "use strict";
  1784. exports = module.exports = require(8);
  1785. exports.build = "full";
  1786. // Parser
  1787. exports.tokenize = require(25);
  1788. exports.parse = require(17);
  1789. exports.common = require(2);
  1790. // Configure parser
  1791. exports.Root._configure(exports.Type, exports.parse, exports.common);
  1792. },{"17":17,"2":2,"25":25,"8":8}],11:[function(require,module,exports){
  1793. "use strict";
  1794. module.exports = MapField;
  1795. // extends Field
  1796. var Field = require(7);
  1797. ((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";
  1798. var types = require(27),
  1799. util = require(28);
  1800. /**
  1801. * Constructs a new map field instance.
  1802. * @classdesc Reflected map field.
  1803. * @extends FieldBase
  1804. * @constructor
  1805. * @param {string} name Unique name within its namespace
  1806. * @param {number} id Unique id within its namespace
  1807. * @param {string} keyType Key type
  1808. * @param {string} type Value type
  1809. * @param {Object.<string,*>} [options] Declared options
  1810. * @param {string} [comment] Comment associated with this field
  1811. */
  1812. function MapField(name, id, keyType, type, options, comment) {
  1813. Field.call(this, name, id, type, undefined, undefined, options, comment);
  1814. /* istanbul ignore if */
  1815. if (!util.isString(keyType))
  1816. throw TypeError("keyType must be a string");
  1817. /**
  1818. * Key type.
  1819. * @type {string}
  1820. */
  1821. this.keyType = keyType; // toJSON, marker
  1822. /**
  1823. * Resolved key type if not a basic type.
  1824. * @type {ReflectionObject|null}
  1825. */
  1826. this.resolvedKeyType = null;
  1827. // Overrides Field#map
  1828. this.map = true;
  1829. }
  1830. /**
  1831. * Map field descriptor.
  1832. * @interface IMapField
  1833. * @extends {IField}
  1834. * @property {string} keyType Key type
  1835. */
  1836. /**
  1837. * Extension map field descriptor.
  1838. * @interface IExtensionMapField
  1839. * @extends IMapField
  1840. * @property {string} extend Extended type
  1841. */
  1842. /**
  1843. * Constructs a map field from a map field descriptor.
  1844. * @param {string} name Field name
  1845. * @param {IMapField} json Map field descriptor
  1846. * @returns {MapField} Created map field
  1847. * @throws {TypeError} If arguments are invalid
  1848. */
  1849. MapField.fromJSON = function fromJSON(name, json) {
  1850. var field = new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);
  1851. if (json.protoName)
  1852. field.protoName = json.protoName;
  1853. if (json.jsonName !== undefined)
  1854. field.jsonName = json.jsonName;
  1855. else if (json.options && json.options.json_name !== undefined)
  1856. field.jsonName = json.options.json_name;
  1857. return field;
  1858. };
  1859. /**
  1860. * Converts this map field to a map field descriptor.
  1861. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  1862. * @returns {IMapField} Map field descriptor
  1863. */
  1864. MapField.prototype.toJSON = function toJSON(toJSONOptions) {
  1865. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  1866. return util.toObject([
  1867. "keyType" , this.keyType,
  1868. "type" , this.type,
  1869. "id" , this.id,
  1870. "extend" , this.extend,
  1871. "protoName" , this.protoName !== this.name ? this.protoName : undefined,
  1872. "jsonName" , this.jsonName !== util.jsonName(this.protoName || this.name) ? this.jsonName : undefined,
  1873. "options" , this.options,
  1874. "comment" , keepComments ? this.comment : undefined
  1875. ]);
  1876. };
  1877. /**
  1878. * @override
  1879. */
  1880. MapField.prototype.resolve = function resolve() {
  1881. if (this.resolved)
  1882. return this;
  1883. // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes"
  1884. if (types.mapKey[this.keyType] === undefined)
  1885. throw Error("invalid key type: " + this.keyType);
  1886. return Field.prototype.resolve.call(this);
  1887. };
  1888. /**
  1889. * Map field decorator (TypeScript).
  1890. * @name MapField.d
  1891. * @function
  1892. * @param {number} fieldId Field id
  1893. * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type
  1894. * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type
  1895. * @returns {FieldDecorator} Decorator function
  1896. * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }
  1897. * @deprecated Legacy TypeScript decorator support. Will be removed in a future release.
  1898. */
  1899. MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {
  1900. // submessage value: decorate the submessage and use its name as the type
  1901. if (typeof fieldValueType === "function")
  1902. fieldValueType = util.decorateType(fieldValueType).name;
  1903. // enum reference value: create a reflected copy of the enum and keep reuseing it
  1904. else if (fieldValueType && typeof fieldValueType === "object")
  1905. fieldValueType = util.decorateEnum(fieldValueType).name;
  1906. return function mapFieldDecorator(prototype, fieldName) {
  1907. util.decorateType(prototype.constructor)
  1908. .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));
  1909. };
  1910. };
  1911. },{"27":27,"28":28,"7":7}],12:[function(require,module,exports){
  1912. "use strict";
  1913. module.exports = Message;
  1914. var util = require(37);
  1915. /**
  1916. * Constructs a new message instance.
  1917. * @classdesc Abstract runtime message.
  1918. * @constructor
  1919. * @param {Properties<T>} [properties] Properties to set
  1920. * @property {Array.<Uint8Array>} [$unknowns] Unknown fields preserved while decoding when enabled
  1921. * @template T extends object = object
  1922. */
  1923. function Message(properties) {
  1924. // not used internally
  1925. if (properties)
  1926. for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
  1927. if (properties[keys[i]] != null && keys[i] !== "__proto__")
  1928. this[keys[i]] = properties[keys[i]];
  1929. }
  1930. /**
  1931. * Reference to the reflected type.
  1932. * @name Message.$type
  1933. * @type {Type}
  1934. * @readonly
  1935. */
  1936. /**
  1937. * Reference to the reflected type.
  1938. * @name Message#$type
  1939. * @type {Type}
  1940. * @readonly
  1941. */
  1942. /**
  1943. * Creates a new message of this type using the specified properties.
  1944. * @param {Object.<string,*>} [properties] Properties to set
  1945. * @returns {T} Message instance
  1946. * @template T extends Message<T>
  1947. * @this Constructor<T>
  1948. */
  1949. Message.create = function create(properties) {
  1950. return this.$type.create(properties);
  1951. };
  1952. /**
  1953. * Encodes a message of this type.
  1954. * @param {T|Object.<string,*>} message Message to encode
  1955. * @param {Writer} [writer] Writer to use
  1956. * @returns {Writer} Writer
  1957. * @template T extends Message<T>
  1958. * @this Constructor<T>
  1959. */
  1960. Message.encode = function encode(message, writer) {
  1961. return this.$type.encode(message, writer);
  1962. };
  1963. /**
  1964. * Encodes a message of this type preceeded by its length as a varint.
  1965. * @param {T|Object.<string,*>} message Message to encode
  1966. * @param {Writer} [writer] Writer to use
  1967. * @returns {Writer} Writer
  1968. * @template T extends Message<T>
  1969. * @this Constructor<T>
  1970. */
  1971. Message.encodeDelimited = function encodeDelimited(message, writer) {
  1972. return this.$type.encodeDelimited(message, writer);
  1973. };
  1974. /**
  1975. * Decodes a message of this type.
  1976. * @name Message.decode
  1977. * @function
  1978. * @param {Reader|Uint8Array} reader Reader or buffer to decode
  1979. * @returns {T} Decoded message
  1980. * @template T extends Message<T>
  1981. * @this Constructor<T>
  1982. */
  1983. Message.decode = function decode(reader) {
  1984. return this.$type.decode(reader);
  1985. };
  1986. /**
  1987. * Decodes a message of this type preceeded by its length as a varint.
  1988. * @name Message.decodeDelimited
  1989. * @function
  1990. * @param {Reader|Uint8Array} reader Reader or buffer to decode
  1991. * @returns {T} Decoded message
  1992. * @template T extends Message<T>
  1993. * @this Constructor<T>
  1994. */
  1995. Message.decodeDelimited = function decodeDelimited(reader) {
  1996. return this.$type.decodeDelimited(reader);
  1997. };
  1998. /**
  1999. * Verifies a message of this type.
  2000. * @name Message.verify
  2001. * @function
  2002. * @param {Object.<string,*>} message Plain object to verify
  2003. * @returns {string|null} `null` if valid, otherwise the reason why it is not
  2004. */
  2005. Message.verify = function verify(message) {
  2006. return this.$type.verify(message);
  2007. };
  2008. /**
  2009. * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
  2010. * @param {Object.<string,*>} object Plain object
  2011. * @returns {T} Message instance
  2012. * @template T extends Message<T>
  2013. * @this Constructor<T>
  2014. */
  2015. Message.fromObject = function fromObject(object) {
  2016. return this.$type.fromObject(object);
  2017. };
  2018. /**
  2019. * Creates a plain object from a message of this type. Also converts values to other types if specified.
  2020. * @param {T} message Message instance
  2021. * @param {IConversionOptions} [options] Conversion options
  2022. * @returns {Object.<string,*>} Plain object
  2023. * @template T extends Message<T>
  2024. * @this Constructor<T>
  2025. */
  2026. Message.toObject = function toObject(message, options) {
  2027. return this.$type.toObject(message, options);
  2028. };
  2029. /**
  2030. * Converts this message to JSON.
  2031. * @returns {Object.<string,*>} JSON object
  2032. */
  2033. Message.prototype.toJSON = function toJSON() {
  2034. return this.$type.toObject(this, util.toJSONOptions);
  2035. };
  2036. },{"37":37}],13:[function(require,module,exports){
  2037. "use strict";
  2038. module.exports = Method;
  2039. // extends ReflectionObject
  2040. var ReflectionObject = require(15);
  2041. ((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method";
  2042. var util = require(28);
  2043. /**
  2044. * Constructs a new service method instance.
  2045. * @classdesc Reflected service method.
  2046. * @extends ReflectionObject
  2047. * @constructor
  2048. * @param {string} name Method name
  2049. * @param {string|undefined} type Method type, usually `"rpc"`
  2050. * @param {string} requestType Request message type
  2051. * @param {string} responseType Response message type
  2052. * @param {boolean|Object.<string,*>} [requestStream] Whether the request is streamed
  2053. * @param {boolean|Object.<string,*>} [responseStream] Whether the response is streamed
  2054. * @param {Object.<string,*>} [options] Declared options
  2055. * @param {string} [comment] The comment for this method
  2056. * @param {Array.<Object.<string,*>>} [parsedOptions] Declared options, properly parsed into objects
  2057. */
  2058. function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {
  2059. /* istanbul ignore next */
  2060. if (util.isObject(requestStream)) {
  2061. options = requestStream;
  2062. requestStream = responseStream = undefined;
  2063. } else if (util.isObject(responseStream)) {
  2064. options = responseStream;
  2065. responseStream = undefined;
  2066. }
  2067. /* istanbul ignore if */
  2068. if (!(type === undefined || util.isString(type)))
  2069. throw TypeError("type must be a string");
  2070. /* istanbul ignore if */
  2071. if (!util.isString(requestType))
  2072. throw TypeError("requestType must be a string");
  2073. /* istanbul ignore if */
  2074. if (!util.isString(responseType))
  2075. throw TypeError("responseType must be a string");
  2076. ReflectionObject.call(this, name, options);
  2077. /**
  2078. * Method type.
  2079. * @type {string}
  2080. */
  2081. this.type = type || "rpc"; // toJSON
  2082. /**
  2083. * Request type.
  2084. * @type {string}
  2085. */
  2086. this.requestType = requestType; // toJSON, marker
  2087. /**
  2088. * Whether requests are streamed or not.
  2089. * @type {true|undefined}
  2090. */
  2091. this.requestStream = requestStream ? true : undefined; // toJSON
  2092. /**
  2093. * Response type.
  2094. * @type {string}
  2095. */
  2096. this.responseType = responseType; // toJSON
  2097. /**
  2098. * Whether responses are streamed or not.
  2099. * @type {true|undefined}
  2100. */
  2101. this.responseStream = responseStream ? true : undefined; // toJSON
  2102. /**
  2103. * gRPC-style method path.
  2104. * @type {string}
  2105. */
  2106. this.path = "/" + this.name;
  2107. /**
  2108. * Resolved request type.
  2109. * @type {Type|null}
  2110. */
  2111. this.resolvedRequestType = null;
  2112. /**
  2113. * Resolved response type.
  2114. * @type {Type|null}
  2115. */
  2116. this.resolvedResponseType = null;
  2117. /**
  2118. * Comment for this method
  2119. * @type {string|null}
  2120. */
  2121. this.comment = comment;
  2122. /**
  2123. * Options properly parsed into objects
  2124. * @type {Array.<Object.<string,*>>|undefined}
  2125. */
  2126. this.parsedOptions = parsedOptions;
  2127. }
  2128. /**
  2129. * Method descriptor.
  2130. * @interface IMethod
  2131. * @property {string} [type="rpc"] Method type
  2132. * @property {string} requestType Request type
  2133. * @property {string} responseType Response type
  2134. * @property {boolean} [requestStream=false] Whether requests are streamed
  2135. * @property {boolean} [responseStream=false] Whether responses are streamed
  2136. * @property {Object.<string,*>} [options] Method options
  2137. * @property {string|null} [comment] Method comment
  2138. * @property {Array.<Object.<string,*>>} [parsedOptions] Method options properly parsed into objects
  2139. */
  2140. /**
  2141. * Constructs a method from a method descriptor.
  2142. * @param {string} name Method name
  2143. * @param {IMethod} json Method descriptor
  2144. * @returns {Method} Created method
  2145. * @throws {TypeError} If arguments are invalid
  2146. */
  2147. Method.fromJSON = function fromJSON(name, json) {
  2148. return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);
  2149. };
  2150. /**
  2151. * Converts this method to a method descriptor.
  2152. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2153. * @returns {IMethod} Method descriptor
  2154. */
  2155. Method.prototype.toJSON = function toJSON(toJSONOptions) {
  2156. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  2157. return util.toObject([
  2158. "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined,
  2159. "requestType" , this.requestType,
  2160. "requestStream" , this.requestStream,
  2161. "responseType" , this.responseType,
  2162. "responseStream" , this.responseStream,
  2163. "options" , this.options,
  2164. "comment" , keepComments ? this.comment : undefined,
  2165. "parsedOptions" , this.parsedOptions,
  2166. ]);
  2167. };
  2168. /**
  2169. * @override
  2170. */
  2171. Method.prototype.resolve = function resolve() {
  2172. /* istanbul ignore if */
  2173. if (this.resolved)
  2174. return this;
  2175. if (this.parent) {
  2176. var serviceName = this.parent.fullName;
  2177. if (serviceName.charAt(0) === ".")
  2178. serviceName = serviceName.substring(1);
  2179. this.path = "/" + serviceName + "/" + this.name;
  2180. } else
  2181. this.path = "/" + this.name;
  2182. this.resolvedRequestType = this.parent.lookupType(this.requestType);
  2183. this.resolvedResponseType = this.parent.lookupType(this.responseType);
  2184. return ReflectionObject.prototype.resolve.call(this);
  2185. };
  2186. },{"15":15,"28":28}],14:[function(require,module,exports){
  2187. "use strict";
  2188. module.exports = Namespace;
  2189. // extends ReflectionObject
  2190. var ReflectionObject = require(15);
  2191. ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace";
  2192. var Field = require(7),
  2193. util = require(28),
  2194. OneOf = require(16);
  2195. var Type, // cyclic
  2196. Service,
  2197. Enum;
  2198. /**
  2199. * Constructs a new namespace instance.
  2200. * @name Namespace
  2201. * @classdesc Reflected namespace.
  2202. * @extends NamespaceBase
  2203. * @constructor
  2204. * @param {string} name Namespace name
  2205. * @param {Object.<string,*>} [options] Declared options
  2206. */
  2207. /**
  2208. * Constructs a namespace from JSON.
  2209. * @memberof Namespace
  2210. * @function
  2211. * @param {string} name Namespace name
  2212. * @param {Object.<string,*>} json JSON object
  2213. * @param {number} [depth] Current nesting depth, defaults to `0`
  2214. * @returns {Namespace} Created namespace
  2215. * @throws {TypeError} If arguments are invalid
  2216. */
  2217. Namespace.fromJSON = function fromJSON(name, json, depth) {
  2218. if (depth === undefined)
  2219. depth = 0;
  2220. if (depth > util.recursionLimit)
  2221. throw Error("max depth exceeded");
  2222. return new Namespace(name, json.options).addJSON(json.nested, depth);
  2223. };
  2224. /**
  2225. * Converts an array of reflection objects to JSON.
  2226. * @memberof Namespace
  2227. * @param {ReflectionObject[]} array Object array
  2228. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2229. * @returns {Object.<string,*>|undefined} JSON object or `undefined` when array is empty
  2230. */
  2231. function arrayToJSON(array, toJSONOptions) {
  2232. if (!(array && array.length))
  2233. return undefined;
  2234. var obj = {};
  2235. for (var i = 0; i < array.length; ++i)
  2236. obj[array[i].name] = array[i].toJSON(toJSONOptions);
  2237. return obj;
  2238. }
  2239. Namespace.arrayToJSON = arrayToJSON;
  2240. /**
  2241. * Tests if the specified id is reserved.
  2242. * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names
  2243. * @param {number} id Id to test
  2244. * @returns {boolean} `true` if reserved, otherwise `false`
  2245. */
  2246. Namespace.isReservedId = function isReservedId(reserved, id) {
  2247. if (reserved)
  2248. for (var i = 0; i < reserved.length; ++i)
  2249. if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] >= id)
  2250. return true;
  2251. return false;
  2252. };
  2253. /**
  2254. * Tests if the specified name is reserved.
  2255. * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names
  2256. * @param {string} name Name to test
  2257. * @returns {boolean} `true` if reserved, otherwise `false`
  2258. */
  2259. Namespace.isReservedName = function isReservedName(reserved, name) {
  2260. if (reserved)
  2261. for (var i = 0; i < reserved.length; ++i)
  2262. if (reserved[i] === name)
  2263. return true;
  2264. return false;
  2265. };
  2266. /**
  2267. * Not an actual constructor. Use {@link Namespace} instead.
  2268. * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.
  2269. * @exports NamespaceBase
  2270. * @extends ReflectionObject
  2271. * @abstract
  2272. * @constructor
  2273. * @param {string} name Namespace name
  2274. * @param {Object.<string,*>} [options] Declared options
  2275. * @see {@link Namespace}
  2276. */
  2277. function Namespace(name, options) {
  2278. ReflectionObject.call(this, name, options);
  2279. /**
  2280. * Nested objects by name.
  2281. * @type {Object.<string,ReflectionObject>|undefined}
  2282. */
  2283. this.nested = undefined; // toJSON
  2284. /**
  2285. * Cached nested objects as an array.
  2286. * @type {ReflectionObject[]|null}
  2287. * @private
  2288. */
  2289. this._nestedArray = null;
  2290. /**
  2291. * Cache lookup calls for any objects contains anywhere under this namespace.
  2292. * This drastically speeds up resolve for large cross-linked protos where the same
  2293. * types are looked up repeatedly.
  2294. * @type {Object.<string,ReflectionObject|null>}
  2295. * @private
  2296. */
  2297. this._lookupCache = Object.create(null);
  2298. /**
  2299. * Whether or not objects contained in this namespace need feature resolution.
  2300. * @type {boolean}
  2301. * @protected
  2302. */
  2303. this._needsRecursiveFeatureResolution = true;
  2304. /**
  2305. * Whether or not objects contained in this namespace need a resolve.
  2306. * @type {boolean}
  2307. * @protected
  2308. */
  2309. this._needsRecursiveResolve = true;
  2310. }
  2311. function clearCache(namespace) {
  2312. namespace._nestedArray = null;
  2313. namespace._lookupCache = Object.create(null);
  2314. // Also clear parent caches, since they include nested lookups.
  2315. var parent = namespace;
  2316. while(parent = parent.parent) {
  2317. parent._lookupCache = Object.create(null);
  2318. }
  2319. return namespace;
  2320. }
  2321. /**
  2322. * Nested objects of this namespace as an array for iteration.
  2323. * @name NamespaceBase#nestedArray
  2324. * @type {ReflectionObject[]}
  2325. * @readonly
  2326. */
  2327. Object.defineProperty(Namespace.prototype, "nestedArray", {
  2328. get: function() {
  2329. return this._nestedArray || (this._nestedArray = util.toArray(this.nested));
  2330. }
  2331. });
  2332. /**
  2333. * Namespace descriptor.
  2334. * @interface INamespace
  2335. * @property {Object.<string,*>} [options] Namespace options
  2336. * @property {Object.<string,AnyNestedObject>} [nested] Nested object descriptors
  2337. */
  2338. /**
  2339. * Any extension field descriptor.
  2340. * @typedef AnyExtensionField
  2341. * @type {IExtensionField|IExtensionMapField}
  2342. */
  2343. /**
  2344. * Any nested object descriptor.
  2345. * @typedef AnyNestedObject
  2346. * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}
  2347. */
  2348. /**
  2349. * Converts this namespace to a namespace descriptor.
  2350. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2351. * @returns {INamespace} Namespace descriptor
  2352. */
  2353. Namespace.prototype.toJSON = function toJSON(toJSONOptions) {
  2354. return util.toObject([
  2355. "options" , this.options,
  2356. "nested" , arrayToJSON(this.nestedArray, toJSONOptions)
  2357. ]);
  2358. };
  2359. /**
  2360. * Adds nested objects to this namespace from nested object descriptors.
  2361. * @param {Object.<string,AnyNestedObject>} nestedJson Any nested object descriptors
  2362. * @param {number} [depth] Current nesting depth, defaults to `0`
  2363. * @returns {Namespace} `this`
  2364. */
  2365. Namespace.prototype.addJSON = function addJSON(nestedJson, depth) {
  2366. if (depth === undefined)
  2367. depth = 0;
  2368. if (depth > util.recursionLimit)
  2369. throw Error("max depth exceeded");
  2370. var ns = this;
  2371. /* istanbul ignore else */
  2372. if (nestedJson) {
  2373. for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {
  2374. nested = nestedJson[names[i]];
  2375. ns.add( // most to least likely
  2376. ( nested.fields !== undefined
  2377. ? Type.fromJSON
  2378. : nested.values !== undefined
  2379. ? Enum.fromJSON
  2380. : nested.methods !== undefined
  2381. ? Service.fromJSON
  2382. : nested.id !== undefined
  2383. ? Field.fromJSON
  2384. : Namespace.fromJSON )(names[i], nested, depth + 1)
  2385. );
  2386. }
  2387. }
  2388. return this;
  2389. };
  2390. /**
  2391. * Gets the nested object of the specified name.
  2392. * @param {string} name Nested object name
  2393. * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist
  2394. */
  2395. Namespace.prototype.get = function get(name) {
  2396. return this.nested && Object.prototype.hasOwnProperty.call(this.nested, name)
  2397. ? this.nested[name]
  2398. : null;
  2399. };
  2400. /**
  2401. * Gets the values of the nested {@link Enum|enum} of the specified name.
  2402. * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.
  2403. * @param {string} name Nested enum name
  2404. * @returns {Object.<string,number>} Enum values
  2405. * @throws {Error} If there is no such enum
  2406. */
  2407. Namespace.prototype.getEnum = function getEnum(name) {
  2408. if (this.nested && Object.prototype.hasOwnProperty.call(this.nested, name) && this.nested[name] instanceof Enum)
  2409. return this.nested[name].values;
  2410. throw Error("no such enum: " + name);
  2411. };
  2412. /**
  2413. * Adds a nested object to this namespace.
  2414. * @param {ReflectionObject} object Nested object to add
  2415. * @returns {Namespace} `this`
  2416. * @throws {TypeError} If arguments are invalid
  2417. * @throws {Error} If there is already a nested object with this name
  2418. */
  2419. Namespace.prototype.add = function add(object) {
  2420. if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))
  2421. throw TypeError("object must be a valid nested object");
  2422. if (object.name === "__proto__")
  2423. return this;
  2424. if (!this.nested)
  2425. this.nested = {};
  2426. else {
  2427. var prev = this.get(object.name);
  2428. if (prev) {
  2429. if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {
  2430. // replace plain namespace but keep existing nested elements and options
  2431. var nested = prev.nestedArray;
  2432. for (var i = 0; i < nested.length; ++i)
  2433. object.add(nested[i]);
  2434. this.remove(prev);
  2435. if (!this.nested)
  2436. this.nested = {};
  2437. object.setOptions(prev.options, true);
  2438. } else
  2439. throw Error("duplicate name '" + object.name + "' in " + this);
  2440. }
  2441. }
  2442. this.nested[object.name] = object;
  2443. if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) {
  2444. // This is a package or a root namespace.
  2445. if (!object._edition) {
  2446. // Make sure that some edition is set if it hasn't already been specified.
  2447. object._edition = object._defaultEdition;
  2448. }
  2449. }
  2450. this._needsRecursiveFeatureResolution = true;
  2451. this._needsRecursiveResolve = true;
  2452. // Also clear parent caches, since they need to recurse down.
  2453. var parent = this;
  2454. while(parent = parent.parent) {
  2455. parent._needsRecursiveFeatureResolution = true;
  2456. parent._needsRecursiveResolve = true;
  2457. }
  2458. object.onAdd(this);
  2459. return clearCache(this);
  2460. };
  2461. /**
  2462. * Removes a nested object from this namespace.
  2463. * @param {ReflectionObject} object Nested object to remove
  2464. * @returns {Namespace} `this`
  2465. * @throws {TypeError} If arguments are invalid
  2466. * @throws {Error} If `object` is not a member of this namespace
  2467. */
  2468. Namespace.prototype.remove = function remove(object) {
  2469. if (!(object instanceof ReflectionObject))
  2470. throw TypeError("object must be a ReflectionObject");
  2471. if (object.parent !== this)
  2472. throw Error(object + " is not a member of " + this);
  2473. if (!util.remove(this.nested, object, object.name))
  2474. throw Error(object + " is not a member of " + this);
  2475. if (!Object.keys(this.nested).length)
  2476. this.nested = undefined;
  2477. object.onRemove(this);
  2478. return clearCache(this);
  2479. };
  2480. /**
  2481. * Defines additial namespaces within this one if not yet existing.
  2482. * @param {string|string[]} path Path to create
  2483. * @param {*} [json] Nested types to create from JSON
  2484. * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty
  2485. */
  2486. Namespace.prototype.define = function define(path, json) {
  2487. if (util.isString(path))
  2488. path = path.split(".");
  2489. else if (!Array.isArray(path))
  2490. throw TypeError("illegal path");
  2491. if (path && path.length && path[0] === "")
  2492. throw Error("path must be relative");
  2493. if (path.length > util.recursionLimit)
  2494. throw Error("max depth exceeded");
  2495. var ptr = this;
  2496. while (path.length > 0) {
  2497. var part = path.shift();
  2498. if (ptr.nested && ptr.nested[part]) {
  2499. ptr = ptr.nested[part];
  2500. if (!(ptr instanceof Namespace))
  2501. throw Error("path conflicts with non-namespace objects");
  2502. } else
  2503. ptr.add(ptr = new Namespace(part));
  2504. }
  2505. if (json)
  2506. ptr.addJSON(json);
  2507. return ptr;
  2508. };
  2509. /**
  2510. * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.
  2511. * @returns {Namespace} `this`
  2512. */
  2513. Namespace.prototype.resolveAll = function resolveAll() {
  2514. if (!this._needsRecursiveResolve) return this;
  2515. if (this._needsRecursiveFeatureResolution)
  2516. this._resolveFeaturesRecursive(this._edition);
  2517. var nested = this.nestedArray, i = 0;
  2518. this.resolve();
  2519. while (i < nested.length)
  2520. if (nested[i] instanceof Namespace)
  2521. nested[i++].resolveAll();
  2522. else
  2523. nested[i++].resolve();
  2524. this._needsRecursiveResolve = false;
  2525. return this;
  2526. };
  2527. /**
  2528. * @override
  2529. */
  2530. Namespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {
  2531. if (!this._needsRecursiveFeatureResolution) return this;
  2532. this._needsRecursiveFeatureResolution = false;
  2533. edition = this._edition || edition;
  2534. ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition);
  2535. this.nestedArray.forEach(nested => {
  2536. nested._resolveFeaturesRecursive(edition);
  2537. });
  2538. return this;
  2539. };
  2540. /**
  2541. * Recursively looks up the reflection object matching the specified path in the scope of this namespace.
  2542. * @param {string|string[]} path Path to look up
  2543. * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.
  2544. * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked
  2545. * @returns {ReflectionObject|null} Looked up object or `null` if none could be found
  2546. */
  2547. Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {
  2548. /* istanbul ignore next */
  2549. if (typeof filterTypes === "boolean") {
  2550. parentAlreadyChecked = filterTypes;
  2551. filterTypes = undefined;
  2552. } else if (filterTypes && !Array.isArray(filterTypes))
  2553. filterTypes = [ filterTypes ];
  2554. if (util.isString(path) && path.length) {
  2555. if (path === ".")
  2556. return this.root;
  2557. path = path.split(".");
  2558. } else if (!path.length)
  2559. return this;
  2560. var flatPath = path.join(".");
  2561. // Start at root if path is absolute
  2562. if (path[0] === "")
  2563. return this.root.lookup(path.slice(1), filterTypes);
  2564. // Lookup at this namespace and below
  2565. var found = this._lookupImpl(path, flatPath);
  2566. if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
  2567. return found;
  2568. }
  2569. // Fall back to respective absolute path once relative scope has been checked (non-standard)
  2570. found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + flatPath];
  2571. if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
  2572. return found;
  2573. }
  2574. if (parentAlreadyChecked)
  2575. return null;
  2576. // If there hasn't been a match, walk up the tree and look more broadly
  2577. var current = this;
  2578. while (current.parent) {
  2579. found = current.parent._lookupImpl(path, flatPath);
  2580. if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
  2581. return found;
  2582. }
  2583. current = current.parent;
  2584. }
  2585. return null;
  2586. };
  2587. /**
  2588. * Internal helper for lookup that handles searching just at this namespace and below along with caching.
  2589. * @param {string[]} path Path to look up
  2590. * @param {string} flatPath Flattened version of the path to use as a cache key
  2591. * @returns {ReflectionObject|null} Looked up object or `null` if none could be found
  2592. * @private
  2593. */
  2594. Namespace.prototype._lookupImpl = function lookup(path, flatPath) {
  2595. if(Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) {
  2596. return this._lookupCache[flatPath];
  2597. }
  2598. // Test if the first part matches any nested object, and if so, traverse if path contains more
  2599. var found = this.get(path[0]);
  2600. var exact = null;
  2601. if (found) {
  2602. if (path.length === 1) {
  2603. exact = found;
  2604. } else if (found instanceof Namespace) {
  2605. path = path.slice(1);
  2606. exact = found._lookupImpl(path, path.join("."));
  2607. }
  2608. // Otherwise try each nested namespace
  2609. } else {
  2610. for (var i = 0; i < this.nestedArray.length; ++i)
  2611. if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath))) {
  2612. exact = found;
  2613. break;
  2614. }
  2615. }
  2616. // Set this even when null, so that when we walk up the tree we can quickly bail on repeated checks back down.
  2617. this._lookupCache[flatPath] = exact;
  2618. return exact;
  2619. };
  2620. /**
  2621. * Looks up the reflection object at the specified path, relative to this namespace.
  2622. * @name NamespaceBase#lookup
  2623. * @function
  2624. * @param {string|string[]} path Path to look up
  2625. * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked
  2626. * @returns {ReflectionObject|null} Looked up object or `null` if none could be found
  2627. * @variation 2
  2628. */
  2629. // lookup(path: string, [parentAlreadyChecked: boolean])
  2630. /**
  2631. * Looks up the {@link Type|type} at the specified path, relative to this namespace.
  2632. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  2633. * @param {string|string[]} path Path to look up
  2634. * @returns {Type} Looked up type
  2635. * @throws {Error} If `path` does not point to a type
  2636. */
  2637. Namespace.prototype.lookupType = function lookupType(path) {
  2638. var found = this.lookup(path, [ Type ]);
  2639. if (!found)
  2640. throw Error("no such type: " + path);
  2641. return found;
  2642. };
  2643. /**
  2644. * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.
  2645. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  2646. * @param {string|string[]} path Path to look up
  2647. * @returns {Enum} Looked up enum
  2648. * @throws {Error} If `path` does not point to an enum
  2649. */
  2650. Namespace.prototype.lookupEnum = function lookupEnum(path) {
  2651. var found = this.lookup(path, [ Enum ]);
  2652. if (!found)
  2653. throw Error("no such Enum '" + path + "' in " + this);
  2654. return found;
  2655. };
  2656. /**
  2657. * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.
  2658. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  2659. * @param {string|string[]} path Path to look up
  2660. * @returns {Type} Looked up type or enum
  2661. * @throws {Error} If `path` does not point to a type or enum
  2662. */
  2663. Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {
  2664. var found = this.lookup(path, [ Type, Enum ]);
  2665. if (!found)
  2666. throw Error("no such Type or Enum '" + path + "' in " + this);
  2667. return found;
  2668. };
  2669. /**
  2670. * Looks up the {@link Service|service} at the specified path, relative to this namespace.
  2671. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  2672. * @param {string|string[]} path Path to look up
  2673. * @returns {Service} Looked up service
  2674. * @throws {Error} If `path` does not point to a service
  2675. */
  2676. Namespace.prototype.lookupService = function lookupService(path) {
  2677. var found = this.lookup(path, [ Service ]);
  2678. if (!found)
  2679. throw Error("no such Service '" + path + "' in " + this);
  2680. return found;
  2681. };
  2682. // Sets up cyclic dependencies (called in index-light)
  2683. Namespace._configure = function(Type_, Service_, Enum_) {
  2684. Type = Type_;
  2685. Service = Service_;
  2686. Enum = Enum_;
  2687. };
  2688. },{"15":15,"16":16,"28":28,"7":7}],15:[function(require,module,exports){
  2689. "use strict";
  2690. module.exports = ReflectionObject;
  2691. ReflectionObject.className = "ReflectionObject";
  2692. const OneOf = require(16);
  2693. var util = require(28);
  2694. var Root; // cyclic
  2695. /* eslint-disable no-warning-comments */
  2696. // TODO: Replace with embedded proto.
  2697. var editions2024Defaults = {enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY", enforce_naming_style: "STYLE2024", default_symbol_visibility: "EXPORT_TOP_LEVEL" };
  2698. var editions2023Defaults = {enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY", enforce_naming_style: "STYLE_LEGACY", default_symbol_visibility: "EXPORT_ALL" };
  2699. var proto2Defaults = {enum_type: "CLOSED", field_presence: "EXPLICIT", json_format: "LEGACY_BEST_EFFORT", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "EXPANDED", utf8_validation: "NONE", enforce_naming_style: "STYLE_LEGACY", default_symbol_visibility: "EXPORT_ALL" };
  2700. var proto3Defaults = {enum_type: "OPEN", field_presence: "IMPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY", enforce_naming_style: "STYLE_LEGACY", default_symbol_visibility: "EXPORT_ALL" };
  2701. /**
  2702. * Constructs a new reflection object instance.
  2703. * @classdesc Base class of all reflection objects.
  2704. * @constructor
  2705. * @param {string} name Object name
  2706. * @param {Object.<string,*>} [options] Declared options
  2707. * @abstract
  2708. */
  2709. function ReflectionObject(name, options) {
  2710. if (!util.isString(name))
  2711. throw TypeError("name must be a string");
  2712. if (options && !util.isObject(options))
  2713. throw TypeError("options must be an object");
  2714. /**
  2715. * Options.
  2716. * @type {Object.<string,*>|undefined}
  2717. */
  2718. this.options = options; // toJSON
  2719. /**
  2720. * Parsed Options.
  2721. * @type {Array.<Object.<string,*>>|undefined}
  2722. */
  2723. this.parsedOptions = null;
  2724. /**
  2725. * Unique name within its namespace.
  2726. * @type {string}
  2727. */
  2728. this.name = name;
  2729. /**
  2730. * The edition specified for this object. Only relevant for top-level objects.
  2731. * @type {string}
  2732. * @private
  2733. */
  2734. this._edition = null;
  2735. /**
  2736. * The default edition to use for this object if none is specified. For legacy reasons,
  2737. * this is proto2 except in the JSON parsing case where it was proto3.
  2738. * @type {string}
  2739. * @private
  2740. */
  2741. this._defaultEdition = "proto2";
  2742. /**
  2743. * Resolved Features.
  2744. * @type {object}
  2745. * @private
  2746. */
  2747. this._features = {};
  2748. /**
  2749. * Whether or not features have been resolved.
  2750. * @type {boolean}
  2751. * @private
  2752. */
  2753. this._featuresResolved = false;
  2754. /**
  2755. * Parent namespace.
  2756. * @type {Namespace|null}
  2757. */
  2758. this.parent = null;
  2759. /**
  2760. * Whether already resolved or not.
  2761. * @type {boolean}
  2762. */
  2763. this.resolved = false;
  2764. /**
  2765. * Comment text, if any.
  2766. * @type {string|null}
  2767. */
  2768. this.comment = null;
  2769. /**
  2770. * Defining file name.
  2771. * @type {string|null}
  2772. */
  2773. this.filename = null;
  2774. }
  2775. Object.defineProperties(ReflectionObject.prototype, {
  2776. /**
  2777. * Reference to the root namespace.
  2778. * @name ReflectionObject#root
  2779. * @type {Root}
  2780. * @readonly
  2781. */
  2782. root: {
  2783. get: function() {
  2784. var ptr = this;
  2785. while (ptr.parent !== null)
  2786. ptr = ptr.parent;
  2787. return ptr;
  2788. }
  2789. },
  2790. /**
  2791. * Full name including leading dot.
  2792. * @name ReflectionObject#fullName
  2793. * @type {string}
  2794. * @readonly
  2795. */
  2796. fullName: {
  2797. get: function() {
  2798. var path = [ this.name ],
  2799. ptr = this.parent;
  2800. while (ptr) {
  2801. path.unshift(ptr.name);
  2802. ptr = ptr.parent;
  2803. }
  2804. return path.join(".");
  2805. }
  2806. }
  2807. });
  2808. /**
  2809. * Converts this reflection object to its descriptor representation.
  2810. * @returns {Object.<string,*>} Descriptor
  2811. */
  2812. ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {
  2813. throw Error(); // not implemented, shouldn't happen
  2814. };
  2815. /**
  2816. * Called when this object is added to a parent.
  2817. * @param {ReflectionObject} parent Parent added to
  2818. * @returns {undefined}
  2819. */
  2820. ReflectionObject.prototype.onAdd = function onAdd(parent) {
  2821. if (this.parent && this.parent !== parent)
  2822. this.parent.remove(this);
  2823. this.parent = parent;
  2824. this.resolved = false;
  2825. var root = parent.root;
  2826. if (root instanceof Root)
  2827. root._handleAdd(this);
  2828. };
  2829. /**
  2830. * Called when this object is removed from a parent.
  2831. * @param {ReflectionObject} parent Parent removed from
  2832. * @returns {undefined}
  2833. */
  2834. ReflectionObject.prototype.onRemove = function onRemove(parent) {
  2835. var root = parent.root;
  2836. if (root instanceof Root)
  2837. root._handleRemove(this);
  2838. this.parent = null;
  2839. this.resolved = false;
  2840. };
  2841. /**
  2842. * Resolves this objects type references.
  2843. * @returns {ReflectionObject} `this`
  2844. */
  2845. ReflectionObject.prototype.resolve = function resolve() {
  2846. if (this.resolved)
  2847. return this;
  2848. if (this.root instanceof Root)
  2849. this.resolved = true; // only if part of a root
  2850. return this;
  2851. };
  2852. /**
  2853. * Resolves this objects editions features.
  2854. * @param {string} edition The edition we're currently resolving for.
  2855. * @returns {ReflectionObject} `this`
  2856. */
  2857. ReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {
  2858. return this._resolveFeatures(this._edition || edition);
  2859. };
  2860. /**
  2861. * Resolves child features from parent features
  2862. * @param {string} edition The edition we're currently resolving for.
  2863. * @returns {undefined}
  2864. */
  2865. ReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) {
  2866. if (this._featuresResolved) {
  2867. return;
  2868. }
  2869. var defaults = {};
  2870. /* istanbul ignore if */
  2871. if (!edition) {
  2872. throw new Error("Unknown edition for " + this.fullName);
  2873. }
  2874. var protoFeatures = util.merge({}, this.options && this.options.features,
  2875. this._inferLegacyProtoFeatures(edition));
  2876. if (this._edition) {
  2877. // For a namespace marked with a specific edition, reset defaults.
  2878. /* istanbul ignore else */
  2879. if (edition === "proto2") {
  2880. defaults = Object.assign({}, proto2Defaults);
  2881. } else if (edition === "proto3") {
  2882. defaults = Object.assign({}, proto3Defaults);
  2883. } else if (edition === "2023") {
  2884. defaults = Object.assign({}, editions2023Defaults);
  2885. } else if (edition === "2024") {
  2886. defaults = Object.assign({}, editions2024Defaults);
  2887. } else {
  2888. throw new Error("Unknown edition: " + edition);
  2889. }
  2890. this._features = util.merge(defaults, protoFeatures);
  2891. } else {
  2892. // fields in Oneofs aren't actually children of them, so we have to
  2893. // special-case it
  2894. /* istanbul ignore else */
  2895. if (this.partOf instanceof OneOf) {
  2896. var lexicalParentFeaturesCopy = util.merge({}, this.partOf._features);
  2897. this._features = util.merge(lexicalParentFeaturesCopy, protoFeatures);
  2898. } else if (this.declaringField) {
  2899. // Skip feature resolution of sister fields.
  2900. } else if (this.parent) {
  2901. var parentFeaturesCopy = util.merge({}, this.parent._features);
  2902. this._features = util.merge(parentFeaturesCopy, protoFeatures);
  2903. } else {
  2904. throw new Error("Unable to find a parent for " + this.fullName);
  2905. }
  2906. }
  2907. if (this.extensionField) {
  2908. // Sister fields should have the same features as their extensions.
  2909. this.extensionField._features = this._features;
  2910. }
  2911. this._featuresResolved = true;
  2912. };
  2913. /**
  2914. * Infers features from legacy syntax that may have been specified differently.
  2915. * in older editions.
  2916. * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions
  2917. * @returns {object} The feature values to override
  2918. */
  2919. ReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(/*edition*/) {
  2920. return {};
  2921. };
  2922. /**
  2923. * Gets an option value.
  2924. * @param {string} name Option name
  2925. * @returns {*} Option value or `undefined` if not set
  2926. */
  2927. ReflectionObject.prototype.getOption = function getOption(name) {
  2928. if (this.options)
  2929. return this.options[name];
  2930. return undefined;
  2931. };
  2932. /**
  2933. * Sets an option.
  2934. * @param {string} name Option name
  2935. * @param {*} value Option value
  2936. * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set
  2937. * @returns {ReflectionObject} `this`
  2938. */
  2939. ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {
  2940. if (name === "__proto__")
  2941. return this;
  2942. if (!this.options)
  2943. this.options = {};
  2944. if (/^features\./.test(name)) {
  2945. util.setProperty(this.options, name, value, ifNotSet);
  2946. } else if (!ifNotSet || this.options[name] === undefined) {
  2947. if (this.getOption(name) !== value) this.resolved = false;
  2948. this.options[name] = value;
  2949. }
  2950. return this;
  2951. };
  2952. /**
  2953. * Sets a parsed option.
  2954. * @param {string} name parsed Option name
  2955. * @param {*} value Option value
  2956. * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value
  2957. * @returns {ReflectionObject} `this`
  2958. */
  2959. ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {
  2960. if (name === "__proto__")
  2961. return this;
  2962. if (!this.parsedOptions) {
  2963. this.parsedOptions = [];
  2964. }
  2965. var parsedOptions = this.parsedOptions;
  2966. if (propName) {
  2967. // If setting a sub property of an option then try to merge it
  2968. // with an existing option
  2969. var opt = parsedOptions.find(function (opt) {
  2970. return Object.prototype.hasOwnProperty.call(opt, name);
  2971. });
  2972. if (opt) {
  2973. // If we found an existing option - just merge the property value
  2974. // (If it's a feature, will just write over)
  2975. var newValue = opt[name];
  2976. util.setProperty(newValue, propName, value);
  2977. } else {
  2978. // otherwise, create a new option, set its property and add it to the list
  2979. opt = {};
  2980. opt[name] = util.setProperty({}, propName, value);
  2981. parsedOptions.push(opt);
  2982. }
  2983. } else {
  2984. // Always create a new option when setting the value of the option itself
  2985. var newOpt = {};
  2986. newOpt[name] = value;
  2987. parsedOptions.push(newOpt);
  2988. }
  2989. return this;
  2990. };
  2991. /**
  2992. * Sets multiple options.
  2993. * @param {Object.<string,*>} options Options to set
  2994. * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set
  2995. * @returns {ReflectionObject} `this`
  2996. */
  2997. ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {
  2998. if (options)
  2999. for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)
  3000. this.setOption(keys[i], options[keys[i]], ifNotSet);
  3001. return this;
  3002. };
  3003. /**
  3004. * Converts this instance to its string representation.
  3005. * @returns {string} Class name[, space, full name]
  3006. */
  3007. ReflectionObject.prototype.toString = function toString() {
  3008. var className = this.constructor.className,
  3009. fullName = this.fullName;
  3010. if (fullName.length)
  3011. return className + " " + fullName;
  3012. return className;
  3013. };
  3014. /**
  3015. * Converts the edition this object is pinned to for JSON format.
  3016. * @returns {string|undefined} The edition string for JSON representation
  3017. */
  3018. ReflectionObject.prototype._editionToJSON = function _editionToJSON() {
  3019. if (!this._edition || this._edition === "proto3") {
  3020. // Avoid emitting proto3 since we need to default to it for backwards
  3021. // compatibility anyway.
  3022. return undefined;
  3023. }
  3024. return this._edition;
  3025. };
  3026. // Sets up cyclic dependencies (called in index-light)
  3027. ReflectionObject._configure = function(Root_) {
  3028. Root = Root_;
  3029. };
  3030. },{"16":16,"28":28}],16:[function(require,module,exports){
  3031. "use strict";
  3032. module.exports = OneOf;
  3033. // extends ReflectionObject
  3034. var ReflectionObject = require(15);
  3035. ((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf";
  3036. var Field = require(7),
  3037. util = require(28);
  3038. /**
  3039. * Constructs a new oneof instance.
  3040. * @classdesc Reflected oneof.
  3041. * @extends ReflectionObject
  3042. * @constructor
  3043. * @param {string} name Oneof name
  3044. * @param {string[]|Object.<string,*>} [fieldNames] Field names
  3045. * @param {Object.<string,*>} [options] Declared options
  3046. * @param {string} [comment] Comment associated with this field
  3047. */
  3048. function OneOf(name, fieldNames, options, comment) {
  3049. if (!Array.isArray(fieldNames)) {
  3050. options = fieldNames;
  3051. fieldNames = undefined;
  3052. }
  3053. ReflectionObject.call(this, name, options);
  3054. /* istanbul ignore if */
  3055. if (!(fieldNames === undefined || Array.isArray(fieldNames)))
  3056. throw TypeError("fieldNames must be an Array");
  3057. /**
  3058. * Field names that belong to this oneof.
  3059. * @type {string[]}
  3060. */
  3061. this.oneof = fieldNames || []; // toJSON, marker
  3062. /**
  3063. * Fields that belong to this oneof as an array for iteration.
  3064. * @type {Field[]}
  3065. * @readonly
  3066. */
  3067. this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent
  3068. /**
  3069. * Comment for this field.
  3070. * @type {string|null}
  3071. */
  3072. this.comment = comment;
  3073. }
  3074. /**
  3075. * Oneof descriptor.
  3076. * @interface IOneOf
  3077. * @property {Array.<string>} oneof Oneof field names
  3078. * @property {Object.<string,*>} [options] Oneof options
  3079. * @property {string|null} [comment] Oneof comment
  3080. */
  3081. /**
  3082. * Constructs a oneof from a oneof descriptor.
  3083. * @param {string} name Oneof name
  3084. * @param {IOneOf} json Oneof descriptor
  3085. * @returns {OneOf} Created oneof
  3086. * @throws {TypeError} If arguments are invalid
  3087. */
  3088. OneOf.fromJSON = function fromJSON(name, json) {
  3089. return new OneOf(name, json.oneof, json.options, json.comment);
  3090. };
  3091. /**
  3092. * Converts this oneof to a oneof descriptor.
  3093. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  3094. * @returns {IOneOf} Oneof descriptor
  3095. */
  3096. OneOf.prototype.toJSON = function toJSON(toJSONOptions) {
  3097. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  3098. return util.toObject([
  3099. "options" , this.options,
  3100. "oneof" , this.oneof,
  3101. "comment" , keepComments ? this.comment : undefined
  3102. ]);
  3103. };
  3104. /**
  3105. * Adds the fields of the specified oneof to the parent if not already done so.
  3106. * @param {OneOf} oneof The oneof
  3107. * @returns {undefined}
  3108. * @inner
  3109. * @ignore
  3110. */
  3111. function addFieldsToParent(oneof) {
  3112. if (oneof.parent)
  3113. for (var i = 0; i < oneof.fieldsArray.length; ++i)
  3114. if (!oneof.fieldsArray[i].parent)
  3115. oneof.parent.add(oneof.fieldsArray[i]);
  3116. }
  3117. /**
  3118. * Adds a field to this oneof and removes it from its current parent, if any.
  3119. * @param {Field} field Field to add
  3120. * @returns {OneOf} `this`
  3121. */
  3122. OneOf.prototype.add = function add(field) {
  3123. /* istanbul ignore if */
  3124. if (!(field instanceof Field))
  3125. throw TypeError("field must be a Field");
  3126. if (field.parent && field.parent !== this.parent)
  3127. field.parent.remove(field);
  3128. this.oneof.push(field.name);
  3129. this.fieldsArray.push(field);
  3130. field.partOf = this; // field.parent remains null
  3131. addFieldsToParent(this);
  3132. return this;
  3133. };
  3134. /**
  3135. * Removes a field from this oneof and puts it back to the oneof's parent.
  3136. * @param {Field} field Field to remove
  3137. * @returns {OneOf} `this`
  3138. */
  3139. OneOf.prototype.remove = function remove(field) {
  3140. /* istanbul ignore if */
  3141. if (!(field instanceof Field))
  3142. throw TypeError("field must be a Field");
  3143. var index = this.fieldsArray.indexOf(field);
  3144. /* istanbul ignore if */
  3145. if (index < 0)
  3146. throw Error(field + " is not a member of " + this);
  3147. this.fieldsArray.splice(index, 1);
  3148. index = this.oneof.indexOf(field.name);
  3149. /* istanbul ignore else */
  3150. if (index > -1) // theoretical
  3151. this.oneof.splice(index, 1);
  3152. field.partOf = null;
  3153. return this;
  3154. };
  3155. /**
  3156. * @override
  3157. */
  3158. OneOf.prototype.onAdd = function onAdd(parent) {
  3159. ReflectionObject.prototype.onAdd.call(this, parent);
  3160. var self = this;
  3161. // Collect present fields
  3162. for (var i = 0; i < this.oneof.length; ++i) {
  3163. var field = parent.get(this.oneof[i]);
  3164. if (field && !field.partOf) {
  3165. field.partOf = self;
  3166. self.fieldsArray.push(field);
  3167. }
  3168. }
  3169. // Add not yet present fields
  3170. addFieldsToParent(this);
  3171. };
  3172. /**
  3173. * @override
  3174. */
  3175. OneOf.prototype.onRemove = function onRemove(parent) {
  3176. for (var i = 0, field; i < this.fieldsArray.length; ++i)
  3177. if ((field = this.fieldsArray[i]).parent)
  3178. field.parent.remove(field);
  3179. ReflectionObject.prototype.onRemove.call(this, parent);
  3180. };
  3181. /**
  3182. * Determines whether this field corresponds to a synthetic oneof created for
  3183. * a proto3 optional field. No behavioral logic should depend on this, but it
  3184. * can be relevant for reflection.
  3185. * @name OneOf#isProto3Optional
  3186. * @type {boolean}
  3187. * @readonly
  3188. */
  3189. Object.defineProperty(OneOf.prototype, "isProto3Optional", {
  3190. get: function() {
  3191. if (this.fieldsArray == null || this.fieldsArray.length !== 1) {
  3192. return false;
  3193. }
  3194. var field = this.fieldsArray[0];
  3195. return field.options != null && field.options["proto3_optional"] === true;
  3196. }
  3197. });
  3198. /**
  3199. * Decorator function as returned by {@link OneOf.d} (TypeScript).
  3200. * @typedef OneOfDecorator
  3201. * @type {function}
  3202. * @param {Object} prototype Target prototype
  3203. * @param {string} oneofName OneOf name
  3204. * @returns {undefined}
  3205. * @deprecated Legacy TypeScript decorator support. Will be removed in a future release.
  3206. */
  3207. /**
  3208. * OneOf decorator (TypeScript).
  3209. * @function
  3210. * @param {...string} fieldNames Field names
  3211. * @returns {OneOfDecorator} Decorator function
  3212. * @template T extends string
  3213. * @deprecated Legacy TypeScript decorator support. Will be removed in a future release.
  3214. */
  3215. OneOf.d = function decorateOneOf() {
  3216. var fieldNames = new Array(arguments.length),
  3217. index = 0;
  3218. while (index < arguments.length)
  3219. fieldNames[index] = arguments[index++];
  3220. return function oneOfDecorator(prototype, oneofName) {
  3221. util.decorateType(prototype.constructor)
  3222. .add(new OneOf(oneofName, fieldNames));
  3223. Object.defineProperty(prototype, oneofName, {
  3224. get: util.oneOfGetter(fieldNames),
  3225. set: util.oneOfSetter(fieldNames)
  3226. });
  3227. };
  3228. };
  3229. },{"15":15,"28":28,"7":7}],17:[function(require,module,exports){
  3230. "use strict";
  3231. module.exports = parse;
  3232. parse.filename = null;
  3233. parse.defaults = { keepCase: false };
  3234. var tokenize = require(25),
  3235. Root = require(20),
  3236. Type = require(26),
  3237. Field = require(7),
  3238. MapField = require(11),
  3239. OneOf = require(16),
  3240. Enum = require(6),
  3241. Service = require(24),
  3242. Method = require(13),
  3243. ReflectionObject = require(15),
  3244. types = require(27),
  3245. util = require(28);
  3246. var base10Re = /^[1-9][0-9]*$/,
  3247. base10NegRe = /^-?[1-9][0-9]*$/,
  3248. base16Re = /^0[x][0-9a-fA-F]+$/,
  3249. base16NegRe = /^-?0[x][0-9a-fA-F]+$/,
  3250. base8Re = /^0[0-7]+$/,
  3251. base8NegRe = /^-?0[0-7]+$/,
  3252. numberRe = util.patterns.numberRe,
  3253. nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,
  3254. typeRefRe = util.patterns.typeRefRe;
  3255. var maxFieldId = 536870911, // 2^29 - 1
  3256. maxEnumId = 2147483647; // 2^31 - 1
  3257. /**
  3258. * Result object returned from {@link parse}.
  3259. * @interface IParserResult
  3260. * @property {string|undefined} package Package name, if declared
  3261. * @property {string[]|undefined} imports Imports, if any
  3262. * @property {string[]|undefined} weakImports Weak imports, if any
  3263. * @property {Root} root Populated root instance
  3264. */
  3265. /**
  3266. * Options modifying the behavior of {@link parse}.
  3267. * @interface IParseOptions
  3268. * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case
  3269. * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.
  3270. * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist.
  3271. */
  3272. /**
  3273. * Options modifying the behavior of JSON serialization.
  3274. * @interface IToJSONOptions
  3275. * @property {boolean} [keepComments=false] Serializes comments.
  3276. */
  3277. /**
  3278. * Parses the given .proto source and returns an object with the parsed contents.
  3279. * @param {string} source Source contents
  3280. * @param {Root} root Root to populate
  3281. * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
  3282. * @returns {IParserResult} Parser result
  3283. * @property {string} filename=null Currently processing file name for error reporting, if known
  3284. * @property {IParseOptions} defaults Default {@link IParseOptions}
  3285. */
  3286. function parse(source, root, options) {
  3287. /* eslint-disable callback-return */
  3288. if (!(root instanceof Root)) {
  3289. options = root;
  3290. root = new Root();
  3291. }
  3292. if (!options)
  3293. options = parse.defaults;
  3294. var preferTrailingComment = options.preferTrailingComment || false;
  3295. var tn = tokenize(source, options.alternateCommentMode || false),
  3296. next = tn.next,
  3297. push = tn.push,
  3298. peek = tn.peek,
  3299. skip = tn.skip,
  3300. cmnt = tn.cmnt;
  3301. var head = true,
  3302. pkg,
  3303. imports,
  3304. weakImports,
  3305. edition = "proto2";
  3306. var ptr = root;
  3307. var topLevelObjects = [];
  3308. var topLevelOptions = {};
  3309. var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;
  3310. function resolveFileFeatures() {
  3311. topLevelObjects.forEach(obj => {
  3312. obj._edition = edition;
  3313. Object.keys(topLevelOptions).forEach(opt => {
  3314. if (obj.getOption(opt) !== undefined) return;
  3315. obj.setOption(opt, topLevelOptions[opt], true);
  3316. });
  3317. });
  3318. }
  3319. /* istanbul ignore next */
  3320. function illegal(token, name, insideTryCatch) {
  3321. var filename = parse.filename;
  3322. if (!insideTryCatch)
  3323. parse.filename = null;
  3324. return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")");
  3325. }
  3326. function readString() {
  3327. var values = [],
  3328. token;
  3329. do {
  3330. /* istanbul ignore if */
  3331. if ((token = next()) !== "\"" && token !== "'")
  3332. throw illegal(token);
  3333. values.push(next());
  3334. skip(token);
  3335. token = peek();
  3336. } while (token === "\"" || token === "'");
  3337. return values.join("");
  3338. }
  3339. function readValue(acceptTypeRef) {
  3340. var token = next();
  3341. switch (token) {
  3342. case "'":
  3343. case "\"":
  3344. push(token);
  3345. return readString();
  3346. case "true": case "TRUE":
  3347. return true;
  3348. case "false": case "FALSE":
  3349. return false;
  3350. }
  3351. try {
  3352. return parseNumber(token, /* insideTryCatch */ true);
  3353. } catch (e) {
  3354. /* istanbul ignore else */
  3355. if (acceptTypeRef && typeRefRe.test(token))
  3356. return token;
  3357. /* istanbul ignore next */
  3358. throw illegal(token, "value");
  3359. }
  3360. }
  3361. function readRanges(target, acceptStrings, max, acceptNegative) {
  3362. var token, start;
  3363. do {
  3364. if (acceptStrings && ((token = peek()) === "\"" || token === "'")) {
  3365. var str = readString();
  3366. target.push(str);
  3367. if (edition >= 2023) {
  3368. throw illegal(str, "id");
  3369. }
  3370. } else {
  3371. try {
  3372. target.push([ start = parseId(next(), acceptNegative, max), skip("to", true) ? parseId(next(), acceptNegative, max) : start ]);
  3373. } catch (err) {
  3374. if (acceptStrings && typeRefRe.test(token) && edition >= 2023) {
  3375. target.push(token);
  3376. } else {
  3377. throw err;
  3378. }
  3379. }
  3380. }
  3381. } while (skip(",", true));
  3382. var dummy = {options: undefined};
  3383. dummy.setOption = function(name, value) {
  3384. if (this.options === undefined) this.options = {};
  3385. this.options[name] = value;
  3386. };
  3387. ifBlock(
  3388. dummy,
  3389. function parseRange_block(token) {
  3390. /* istanbul ignore else */
  3391. if (token === "option") {
  3392. parseOption(dummy, token); // skip
  3393. skip(";");
  3394. } else
  3395. throw illegal(token);
  3396. },
  3397. function parseRange_line() {
  3398. parseInlineOptions(dummy); // skip
  3399. });
  3400. }
  3401. function parseNumber(token, insideTryCatch) {
  3402. var sign = 1;
  3403. if (token.charAt(0) === "-") {
  3404. sign = -1;
  3405. token = token.substring(1);
  3406. }
  3407. switch (token) {
  3408. case "inf": case "INF": case "Inf":
  3409. return sign * Infinity;
  3410. case "nan": case "NAN": case "Nan": case "NaN":
  3411. return NaN;
  3412. case "0":
  3413. return 0;
  3414. }
  3415. if (base10Re.test(token))
  3416. return sign * parseInt(token, 10);
  3417. if (base16Re.test(token))
  3418. return sign * parseInt(token, 16);
  3419. if (base8Re.test(token))
  3420. return sign * parseInt(token, 8);
  3421. /* istanbul ignore else */
  3422. if (numberRe.test(token))
  3423. return sign * parseFloat(token);
  3424. /* istanbul ignore next */
  3425. throw illegal(token, "number", insideTryCatch);
  3426. }
  3427. function parseId(token, acceptNegative, max) {
  3428. switch (token) {
  3429. case "max": case "MAX": case "Max":
  3430. return max || maxFieldId;
  3431. case "0":
  3432. return 0;
  3433. }
  3434. /* istanbul ignore if */
  3435. if (!acceptNegative && token.charAt(0) === "-")
  3436. throw illegal(token, "id");
  3437. if (base10NegRe.test(token))
  3438. return parseInt(token, 10);
  3439. if (base16NegRe.test(token))
  3440. return parseInt(token, 16);
  3441. /* istanbul ignore else */
  3442. if (base8NegRe.test(token))
  3443. return parseInt(token, 8);
  3444. /* istanbul ignore next */
  3445. throw illegal(token, "id");
  3446. }
  3447. function parsePackage() {
  3448. /* istanbul ignore if */
  3449. if (pkg !== undefined)
  3450. throw illegal("package");
  3451. pkg = next();
  3452. /* istanbul ignore if */
  3453. if (!typeRefRe.test(pkg))
  3454. throw illegal(pkg, "name");
  3455. ptr = ptr.define(pkg);
  3456. skip(";");
  3457. }
  3458. function parseImport() {
  3459. var token = peek();
  3460. var whichImports;
  3461. switch (token) {
  3462. case "option":
  3463. if (edition < "2024") {
  3464. throw illegal("option");
  3465. }
  3466. // Import options are only used for resolving options, which we don't
  3467. // do. We can just throw them out.
  3468. next();
  3469. readString();
  3470. skip(";");
  3471. return;
  3472. case "weak":
  3473. whichImports = weakImports || (weakImports = []);
  3474. next();
  3475. break;
  3476. case "public":
  3477. next();
  3478. // eslint-disable-next-line no-fallthrough
  3479. default:
  3480. whichImports = imports || (imports = []);
  3481. break;
  3482. }
  3483. token = readString();
  3484. skip(";");
  3485. whichImports.push(token);
  3486. }
  3487. function parseSyntax() {
  3488. skip("=");
  3489. edition = readString();
  3490. /* istanbul ignore if */
  3491. if (edition < 2023)
  3492. throw illegal(edition, "syntax");
  3493. skip(";");
  3494. }
  3495. function parseEdition() {
  3496. skip("=");
  3497. edition = readString();
  3498. const supportedEditions = ["2023", "2024"];
  3499. /* istanbul ignore if */
  3500. if (!supportedEditions.includes(edition))
  3501. throw illegal(edition, "edition");
  3502. skip(";");
  3503. }
  3504. function parseCommon(parent, token, depth) {
  3505. if (depth === undefined)
  3506. depth = 0;
  3507. // depth is checked by dispatched functions
  3508. switch (token) {
  3509. case "option":
  3510. parseOption(parent, token);
  3511. skip(";");
  3512. return true;
  3513. case "message":
  3514. parseType(parent, token, depth + 1);
  3515. return true;
  3516. case "enum":
  3517. parseEnum(parent, token);
  3518. return true;
  3519. case "export":
  3520. case "local":
  3521. if (edition < "2024") {
  3522. return false;
  3523. }
  3524. token = next();
  3525. if (token === "export" || token === "local") {
  3526. return false;
  3527. }
  3528. if (token !== "message" && token !== "enum") {
  3529. return false;
  3530. }
  3531. /* eslint-disable no-warning-comments */
  3532. // TODO: actually enforce visiblity modifiers like protoc does.
  3533. return parseCommon(parent, token, depth);
  3534. case "service":
  3535. parseService(parent, token, depth + 1);
  3536. return true;
  3537. case "extend":
  3538. parseExtension(parent, token, depth);
  3539. return true;
  3540. }
  3541. return false;
  3542. }
  3543. function ifBlock(obj, fnIf, fnElse) {
  3544. var trailingLine = tn.line;
  3545. if (obj) {
  3546. if(typeof obj.comment !== "string") {
  3547. obj.comment = cmnt(); // try block-type comment
  3548. }
  3549. obj.filename = parse.filename;
  3550. }
  3551. if (skip("{", true)) {
  3552. var token;
  3553. while ((token = next()) !== "}")
  3554. fnIf(token);
  3555. skip(";", true);
  3556. } else {
  3557. if (fnElse)
  3558. fnElse();
  3559. skip(";");
  3560. if (obj && (typeof obj.comment !== "string" || preferTrailingComment))
  3561. obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment
  3562. }
  3563. }
  3564. function parseType(parent, token, depth) {
  3565. if (depth === undefined)
  3566. depth = 0;
  3567. if (depth > util.nestingLimit)
  3568. throw Error("max depth exceeded");
  3569. /* istanbul ignore if */
  3570. if (!nameRe.test(token = next()))
  3571. throw illegal(token, "type name");
  3572. var type = new Type(token);
  3573. ifBlock(type, function parseType_block(token) {
  3574. if (parseCommon(type, token, depth))
  3575. return;
  3576. switch (token) {
  3577. case ";":
  3578. break;
  3579. case "map":
  3580. parseMapField(type, token);
  3581. break;
  3582. case "required":
  3583. if (edition !== "proto2")
  3584. throw illegal(token);
  3585. /* eslint-disable no-fallthrough */
  3586. case "repeated":
  3587. parseField(type, token, undefined, depth + 1);
  3588. break;
  3589. case "optional":
  3590. /* istanbul ignore if */
  3591. if (edition === "proto3") {
  3592. parseField(type, "proto3_optional", undefined, depth + 1);
  3593. } else if (edition !== "proto2") {
  3594. throw illegal(token);
  3595. } else {
  3596. parseField(type, "optional", undefined, depth + 1);
  3597. }
  3598. break;
  3599. case "oneof":
  3600. parseOneOf(type, token, depth + 1);
  3601. break;
  3602. case "extensions":
  3603. readRanges(type.extensions || (type.extensions = []));
  3604. break;
  3605. case "reserved":
  3606. readRanges(type.reserved || (type.reserved = []), true);
  3607. break;
  3608. default:
  3609. /* istanbul ignore if */
  3610. if (edition === "proto2" || !typeRefRe.test(token)) {
  3611. throw illegal(token);
  3612. }
  3613. push(token);
  3614. parseField(type, "optional", undefined, depth + 1);
  3615. break;
  3616. }
  3617. });
  3618. parent.add(type);
  3619. if (parent === ptr) {
  3620. topLevelObjects.push(type);
  3621. }
  3622. }
  3623. function parseField(parent, rule, extend, depth) {
  3624. var type = next();
  3625. if (type === "group") {
  3626. parseGroup(parent, rule, extend, depth);
  3627. return;
  3628. }
  3629. // Type names can consume multiple tokens, in multiple variants:
  3630. // package.subpackage field tokens: "package.subpackage" [TYPE NAME ENDS HERE] "field"
  3631. // package . subpackage field tokens: "package" "." "subpackage" [TYPE NAME ENDS HERE] "field"
  3632. // package. subpackage field tokens: "package." "subpackage" [TYPE NAME ENDS HERE] "field"
  3633. // package .subpackage field tokens: "package" ".subpackage" [TYPE NAME ENDS HERE] "field"
  3634. // Keep reading tokens until we get a type name with no period at the end,
  3635. // and the next token does not start with a period.
  3636. while (type.endsWith(".") || peek().startsWith(".")) {
  3637. type += next();
  3638. }
  3639. /* istanbul ignore if */
  3640. if (!typeRefRe.test(type))
  3641. throw illegal(type, "type");
  3642. var name = next();
  3643. /* istanbul ignore if */
  3644. if (!nameRe.test(name))
  3645. throw illegal(name, "name");
  3646. var protoName = name;
  3647. name = applyCase(name);
  3648. skip("=");
  3649. var field = new Field(name, parseId(next()), type, rule === "proto3_optional" ? "optional" : rule, extend);
  3650. if (protoName !== name)
  3651. field.protoName = protoName;
  3652. ifBlock(field, function parseField_block(token) {
  3653. /* istanbul ignore else */
  3654. if (token === "option") {
  3655. parseOption(field, token);
  3656. skip(";");
  3657. } else
  3658. throw illegal(token);
  3659. }, function parseField_line() {
  3660. parseInlineOptions(field);
  3661. });
  3662. if (rule === "proto3_optional") {
  3663. // for proto3 optional fields, we create a single-member Oneof to mimic "optional" behavior
  3664. var oneof = new OneOf("_" + name);
  3665. field.setOption("proto3_optional", true);
  3666. oneof.add(field);
  3667. parent.add(oneof);
  3668. } else {
  3669. parent.add(field);
  3670. }
  3671. if (parent === ptr) {
  3672. topLevelObjects.push(field);
  3673. }
  3674. }
  3675. function parseGroup(parent, rule, extend, depth) {
  3676. if (depth === undefined)
  3677. depth = 0;
  3678. if (depth > util.nestingLimit)
  3679. throw Error("max depth exceeded");
  3680. if (edition >= 2023) {
  3681. throw illegal("group");
  3682. }
  3683. var name = next();
  3684. /* istanbul ignore if */
  3685. if (!nameRe.test(name))
  3686. throw illegal(name, "name");
  3687. var fieldName = util.lcFirst(name);
  3688. if (name === fieldName)
  3689. name = util.ucFirst(name);
  3690. skip("=");
  3691. var id = parseId(next());
  3692. var type = new Type(name);
  3693. type.group = true;
  3694. var field = new Field(fieldName, id, name, rule, extend);
  3695. field.filename = parse.filename;
  3696. ifBlock(type, function parseGroup_block(token) {
  3697. switch (token) {
  3698. case ";":
  3699. break;
  3700. case "option":
  3701. parseOption(type, token);
  3702. skip(";");
  3703. break;
  3704. case "required":
  3705. case "repeated":
  3706. parseField(type, token, undefined, depth + 1);
  3707. break;
  3708. case "optional":
  3709. /* istanbul ignore if */
  3710. if (edition === "proto3") {
  3711. parseField(type, "proto3_optional", undefined, depth + 1);
  3712. } else {
  3713. parseField(type, "optional", undefined, depth + 1);
  3714. }
  3715. break;
  3716. case "message":
  3717. parseType(type, token, depth + 1);
  3718. break;
  3719. case "enum":
  3720. parseEnum(type, token);
  3721. break;
  3722. case "reserved":
  3723. readRanges(type.reserved || (type.reserved = []), true);
  3724. break;
  3725. case "export":
  3726. case "local":
  3727. if (edition < "2024") {
  3728. throw illegal(token);
  3729. }
  3730. token = next();
  3731. switch (token) {
  3732. case "message":
  3733. parseType(type, token, depth + 1);
  3734. break;
  3735. case "enum":
  3736. parseType(type, token, depth + 1);
  3737. break;
  3738. default:
  3739. throw illegal(token);
  3740. }
  3741. break;
  3742. /* istanbul ignore next */
  3743. default:
  3744. throw illegal(token); // there are no groups with proto3 semantics
  3745. }
  3746. });
  3747. parent.add(type)
  3748. .add(field);
  3749. if (parent === ptr) {
  3750. topLevelObjects.push(type);
  3751. topLevelObjects.push(field);
  3752. }
  3753. }
  3754. function parseMapField(parent) {
  3755. skip("<");
  3756. var keyType = next();
  3757. /* istanbul ignore if */
  3758. if (types.mapKey[keyType] === undefined)
  3759. throw illegal(keyType, "type");
  3760. skip(",");
  3761. var valueType = next();
  3762. /* istanbul ignore if */
  3763. if (!typeRefRe.test(valueType))
  3764. throw illegal(valueType, "type");
  3765. skip(">");
  3766. var name = next();
  3767. /* istanbul ignore if */
  3768. if (!nameRe.test(name))
  3769. throw illegal(name, "name");
  3770. skip("=");
  3771. var protoName = name;
  3772. name = applyCase(name);
  3773. var field = new MapField(name, parseId(next()), keyType, valueType);
  3774. if (protoName !== name)
  3775. field.protoName = protoName;
  3776. ifBlock(field, function parseMapField_block(token) {
  3777. /* istanbul ignore else */
  3778. if (token === "option") {
  3779. parseOption(field, token);
  3780. skip(";");
  3781. } else
  3782. throw illegal(token);
  3783. }, function parseMapField_line() {
  3784. parseInlineOptions(field);
  3785. });
  3786. parent.add(field);
  3787. }
  3788. function parseOneOf(parent, token, depth) {
  3789. /* istanbul ignore if */
  3790. if (!nameRe.test(token = next()))
  3791. throw illegal(token, "name");
  3792. var oneof = new OneOf(applyCase(token));
  3793. ifBlock(oneof, function parseOneOf_block(token) {
  3794. if (token === "option") {
  3795. parseOption(oneof, token);
  3796. skip(";");
  3797. } else {
  3798. push(token);
  3799. parseField(oneof, "optional", undefined, depth);
  3800. }
  3801. });
  3802. parent.add(oneof);
  3803. }
  3804. function parseEnum(parent, token) {
  3805. /* istanbul ignore if */
  3806. if (!nameRe.test(token = next()))
  3807. throw illegal(token, "name");
  3808. var enm = new Enum(token);
  3809. ifBlock(enm, function parseEnum_block(token) {
  3810. switch(token) {
  3811. case ";":
  3812. break;
  3813. case "option":
  3814. parseOption(enm, token);
  3815. skip(";");
  3816. break;
  3817. case "reserved":
  3818. readRanges(enm.reserved || (enm.reserved = []), true, maxEnumId, true);
  3819. if(enm.reserved === undefined) enm.reserved = [];
  3820. break;
  3821. default:
  3822. parseEnumValue(enm, token);
  3823. }
  3824. });
  3825. parent.add(enm);
  3826. if (parent === ptr) {
  3827. topLevelObjects.push(enm);
  3828. }
  3829. }
  3830. function parseEnumValue(parent, token) {
  3831. /* istanbul ignore if */
  3832. if (!nameRe.test(token))
  3833. throw illegal(token, "name");
  3834. skip("=");
  3835. var value = parseId(next(), true),
  3836. dummy = {
  3837. options: undefined
  3838. };
  3839. dummy.getOption = function(name) {
  3840. return this.options[name];
  3841. };
  3842. dummy.setOption = function(name, value) {
  3843. ReflectionObject.prototype.setOption.call(dummy, name, value);
  3844. };
  3845. dummy.setParsedOption = function() {
  3846. return undefined;
  3847. };
  3848. ifBlock(dummy, function parseEnumValue_block(token) {
  3849. /* istanbul ignore else */
  3850. if (token === "option") {
  3851. parseOption(dummy, token); // skip
  3852. skip(";");
  3853. } else
  3854. throw illegal(token);
  3855. }, function parseEnumValue_line() {
  3856. parseInlineOptions(dummy); // skip
  3857. });
  3858. parent.add(token, value, dummy.comment, dummy.parsedOptions || dummy.options);
  3859. }
  3860. function parseOption(parent, token) {
  3861. var option;
  3862. var propName;
  3863. var isOption = true;
  3864. if (token === "option") {
  3865. token = next();
  3866. }
  3867. while (token !== "=") {
  3868. if (token === "(") {
  3869. var parensValue = next();
  3870. skip(")");
  3871. token = "(" + parensValue + ")";
  3872. }
  3873. if (isOption) {
  3874. isOption = false;
  3875. if (token.includes(".") && !token.includes("(")) {
  3876. var tokens = token.split(".");
  3877. option = tokens[0] + ".";
  3878. token = tokens[1];
  3879. continue;
  3880. }
  3881. option = token;
  3882. } else {
  3883. propName = propName ? propName += token : token;
  3884. }
  3885. token = next();
  3886. }
  3887. var name = propName ? option.concat(propName) : option;
  3888. var optionValue = parseOptionValue(parent, name);
  3889. propName = propName && propName[0] === "." ? propName.slice(1) : propName;
  3890. option = option && option[option.length - 1] === "." ? option.slice(0, -1) : option;
  3891. setParsedOption(parent, option, optionValue, propName);
  3892. }
  3893. function parseOptionValue(parent, name, depth) {
  3894. if (depth === undefined)
  3895. depth = 0;
  3896. if (depth > util.recursionLimit)
  3897. throw Error("max depth exceeded");
  3898. // { a: "foo" b { c: "bar" } }
  3899. if (skip("{", true)) {
  3900. var objectResult = {};
  3901. while (!skip("}", true)) {
  3902. /* istanbul ignore if */
  3903. if (!nameRe.test(token = next())) {
  3904. throw illegal(token, "name");
  3905. }
  3906. if (token === null) {
  3907. throw illegal(token, "end of input");
  3908. }
  3909. var value;
  3910. var propName = token;
  3911. skip(":", true);
  3912. if (peek() === "{") {
  3913. // option (my_option) = {
  3914. // repeated_value: [ "foo", "bar" ]
  3915. // };
  3916. value = parseOptionValue(parent, name + "." + token, depth + 1);
  3917. } else if (peek() === "[") {
  3918. value = [];
  3919. var lastValue;
  3920. if (skip("[", true)) {
  3921. if (!skip("]", true)) {
  3922. do {
  3923. lastValue = readValue(true);
  3924. value.push(lastValue);
  3925. } while (skip(",", true));
  3926. skip("]");
  3927. if (typeof lastValue !== "undefined") {
  3928. setOption(parent, name + "." + token, lastValue);
  3929. }
  3930. }
  3931. }
  3932. } else {
  3933. value = readValue(true);
  3934. setOption(parent, name + "." + token, value);
  3935. }
  3936. var prevValue = objectResult[propName];
  3937. if (prevValue)
  3938. value = [].concat(prevValue).concat(value);
  3939. if (propName !== "__proto__")
  3940. objectResult[propName] = value;
  3941. // Semicolons and commas can be optional
  3942. skip(",", true);
  3943. skip(";", true);
  3944. }
  3945. return objectResult;
  3946. }
  3947. var simpleValue = readValue(true);
  3948. setOption(parent, name, simpleValue);
  3949. return simpleValue;
  3950. // Does not enforce a delimiter to be universal
  3951. }
  3952. function setOption(parent, name, value) {
  3953. if (ptr === parent && /^features\./.test(name)) {
  3954. topLevelOptions[name] = value;
  3955. return;
  3956. }
  3957. // lift json_name onto Field
  3958. if (name === "json_name" && parent instanceof Field) {
  3959. parent.jsonName = value;
  3960. return;
  3961. }
  3962. if (parent.setOption)
  3963. parent.setOption(name, value);
  3964. }
  3965. function setParsedOption(parent, name, value, propName) {
  3966. if (name === "json_name" && parent instanceof Field)
  3967. return; // lifted onto Field#jsonName above
  3968. if (parent.setParsedOption)
  3969. parent.setParsedOption(name, value, propName);
  3970. }
  3971. function parseInlineOptions(parent) {
  3972. if (skip("[", true)) {
  3973. do {
  3974. parseOption(parent, "option");
  3975. } while (skip(",", true));
  3976. skip("]");
  3977. }
  3978. return parent;
  3979. }
  3980. function parseService(parent, token, depth) {
  3981. if (depth === undefined)
  3982. depth = 0;
  3983. if (depth > util.recursionLimit)
  3984. throw Error("max depth exceeded");
  3985. /* istanbul ignore if */
  3986. if (!nameRe.test(token = next()))
  3987. throw illegal(token, "service name");
  3988. var service = new Service(token);
  3989. ifBlock(service, function parseService_block(token) {
  3990. if (parseCommon(service, token, depth)) {
  3991. return;
  3992. }
  3993. /* istanbul ignore else */
  3994. if (token === ";")
  3995. return;
  3996. if (token === "rpc")
  3997. parseMethod(service, token);
  3998. else
  3999. throw illegal(token);
  4000. });
  4001. parent.add(service);
  4002. if (parent === ptr) {
  4003. topLevelObjects.push(service);
  4004. }
  4005. }
  4006. function parseMethod(parent, token) {
  4007. // Get the comment of the preceding line now (if one exists) in case the
  4008. // method is defined across multiple lines.
  4009. var commentText = cmnt();
  4010. var type = token;
  4011. /* istanbul ignore if */
  4012. if (!nameRe.test(token = next()))
  4013. throw illegal(token, "name");
  4014. var name = token,
  4015. requestType, requestStream,
  4016. responseType, responseStream;
  4017. skip("(");
  4018. if (skip("stream", true))
  4019. requestStream = true;
  4020. /* istanbul ignore if */
  4021. if (!typeRefRe.test(token = next()))
  4022. throw illegal(token);
  4023. requestType = token;
  4024. skip(")"); skip("returns"); skip("(");
  4025. if (skip("stream", true))
  4026. responseStream = true;
  4027. /* istanbul ignore if */
  4028. if (!typeRefRe.test(token = next()))
  4029. throw illegal(token);
  4030. responseType = token;
  4031. skip(")");
  4032. var method = new Method(name, type, requestType, responseType, requestStream, responseStream);
  4033. method.comment = commentText;
  4034. ifBlock(method, function parseMethod_block(token) {
  4035. /* istanbul ignore else */
  4036. if (token === ";")
  4037. return;
  4038. if (token === "option") {
  4039. parseOption(method, token);
  4040. skip(";");
  4041. } else
  4042. throw illegal(token);
  4043. });
  4044. parent.add(method);
  4045. }
  4046. function parseExtension(parent, token, depth) {
  4047. /* istanbul ignore if */
  4048. if (!typeRefRe.test(token = next()))
  4049. throw illegal(token, "reference");
  4050. var reference = token;
  4051. ifBlock(null, function parseExtension_block(token) {
  4052. switch (token) {
  4053. case "required":
  4054. case "repeated":
  4055. parseField(parent, token, reference, depth + 1);
  4056. break;
  4057. case "optional":
  4058. /* istanbul ignore if */
  4059. if (edition === "proto3") {
  4060. parseField(parent, "proto3_optional", reference, depth + 1);
  4061. } else {
  4062. parseField(parent, "optional", reference, depth + 1);
  4063. }
  4064. break;
  4065. default:
  4066. /* istanbul ignore if */
  4067. if (edition === "proto2" || !typeRefRe.test(token))
  4068. throw illegal(token);
  4069. push(token);
  4070. parseField(parent, "optional", reference, depth + 1);
  4071. break;
  4072. }
  4073. });
  4074. }
  4075. var token;
  4076. while ((token = next()) !== null) {
  4077. switch (token) {
  4078. case ";":
  4079. break;
  4080. case "package":
  4081. /* istanbul ignore if */
  4082. if (!head)
  4083. throw illegal(token);
  4084. parsePackage();
  4085. break;
  4086. case "import":
  4087. parseImport();
  4088. break;
  4089. case "syntax":
  4090. /* istanbul ignore if */
  4091. if (!head)
  4092. throw illegal(token);
  4093. parseSyntax();
  4094. break;
  4095. case "edition":
  4096. /* istanbul ignore if */
  4097. if (!head)
  4098. throw illegal(token);
  4099. parseEdition();
  4100. break;
  4101. case "option":
  4102. parseOption(ptr, token);
  4103. skip(";", true);
  4104. break;
  4105. default:
  4106. /* istanbul ignore else */
  4107. if (parseCommon(ptr, token, 0)) {
  4108. head = false;
  4109. continue;
  4110. }
  4111. /* istanbul ignore next */
  4112. throw illegal(token);
  4113. }
  4114. }
  4115. resolveFileFeatures();
  4116. parse.filename = null;
  4117. return {
  4118. "package" : pkg,
  4119. "imports" : imports,
  4120. weakImports : weakImports,
  4121. root : root
  4122. };
  4123. }
  4124. /**
  4125. * Parses the given .proto source and returns an object with the parsed contents.
  4126. * @name parse
  4127. * @function
  4128. * @param {string} source Source contents
  4129. * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
  4130. * @returns {IParserResult} Parser result
  4131. * @property {string} filename=null Currently processing file name for error reporting, if known
  4132. * @property {IParseOptions} defaults Default {@link IParseOptions}
  4133. * @variation 2
  4134. */
  4135. },{"11":11,"13":13,"15":15,"16":16,"20":20,"24":24,"25":25,"26":26,"27":27,"28":28,"6":6,"7":7}],18:[function(require,module,exports){
  4136. "use strict";
  4137. module.exports = Reader;
  4138. var util = require(37);
  4139. var BufferReader; // cyclic
  4140. var LongBits = util.LongBits,
  4141. utf8 = util.utf8;
  4142. /* istanbul ignore next */
  4143. function indexOutOfRange(reader, writeLength) {
  4144. return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
  4145. }
  4146. /**
  4147. * Constructs a new reader instance using the specified buffer.
  4148. * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.
  4149. * @constructor
  4150. * @param {Uint8Array} buffer Buffer to read from
  4151. */
  4152. function Reader(buffer) {
  4153. /**
  4154. * Read buffer.
  4155. * @type {Uint8Array}
  4156. */
  4157. this.buf = buffer;
  4158. /**
  4159. * Read buffer position.
  4160. * @type {number}
  4161. */
  4162. this.pos = 0;
  4163. /**
  4164. * Read buffer length.
  4165. * @type {number}
  4166. */
  4167. this.len = buffer.length;
  4168. /**
  4169. * Whether to discard unknown fields while decoding.
  4170. * @type {boolean}
  4171. */
  4172. this.discardUnknown = Reader.discardUnknown;
  4173. }
  4174. var create_array = typeof Uint8Array !== "undefined"
  4175. ? function create_typed_array(buffer) {
  4176. if (buffer instanceof Uint8Array || Array.isArray(buffer))
  4177. return new Reader(buffer);
  4178. throw Error("illegal buffer");
  4179. }
  4180. /* istanbul ignore next */
  4181. : function create_array(buffer) {
  4182. if (Array.isArray(buffer))
  4183. return new Reader(buffer);
  4184. throw Error("illegal buffer");
  4185. };
  4186. var create = function create() {
  4187. return util.Buffer
  4188. ? function create_buffer_setup(buffer) {
  4189. return (Reader.create = function create_buffer(buffer) {
  4190. return util.Buffer.isBuffer(buffer)
  4191. ? new BufferReader(buffer)
  4192. /* istanbul ignore next */
  4193. : create_array(buffer);
  4194. })(buffer);
  4195. }
  4196. /* istanbul ignore next */
  4197. : create_array;
  4198. };
  4199. /**
  4200. * Creates a new reader using the specified buffer.
  4201. * @function
  4202. * @param {Uint8Array|Buffer} buffer Buffer to read from
  4203. * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
  4204. * @throws {Error} If `buffer` is not a valid buffer
  4205. */
  4206. Reader.create = create();
  4207. Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;
  4208. /**
  4209. * Returns raw bytes from the backing buffer without advancing the reader.
  4210. * @param {number} start Start offset
  4211. * @param {number} end End offset
  4212. * @returns {Uint8Array} Raw bytes
  4213. */
  4214. Reader.prototype.raw = function read_raw(start, end) {
  4215. if (Array.isArray(this.buf)) // plain array
  4216. return this.buf.slice(start, end);
  4217. if (start === end) // fix for IE 10/Win8 and others' subarray returning array of size 1
  4218. return new this.buf.constructor(0);
  4219. return this._slice.call(this.buf, start, end);
  4220. };
  4221. /**
  4222. * Reads a varint as an unsigned 32 bit value.
  4223. * @function
  4224. * @returns {number} Value read
  4225. */
  4226. Reader.prototype.uint32 = function read_uint32() {
  4227. var buf = this.buf,
  4228. pos = this.pos,
  4229. value = (buf[pos] & 127) >>> 0;
  4230. if (buf[pos++] < 128) {
  4231. this.pos = pos;
  4232. return value;
  4233. }
  4234. value = (value | (buf[pos] & 127) << 7) >>> 0;
  4235. if (buf[pos++] < 128) {
  4236. this.pos = pos;
  4237. return value;
  4238. }
  4239. value = (value | (buf[pos] & 127) << 14) >>> 0;
  4240. if (buf[pos++] < 128) {
  4241. this.pos = pos;
  4242. return value;
  4243. }
  4244. value = (value | (buf[pos] & 127) << 21) >>> 0;
  4245. if (buf[pos++] < 128) {
  4246. this.pos = pos;
  4247. return value;
  4248. }
  4249. value = (value | (buf[pos] & 15) << 28) >>> 0;
  4250. if (buf[pos++] < 128) {
  4251. this.pos = pos;
  4252. return value;
  4253. }
  4254. for (var i = 0; i < 5; ++i) {
  4255. /* istanbul ignore if */
  4256. if (pos >= this.len) {
  4257. this.pos = pos;
  4258. throw indexOutOfRange(this);
  4259. }
  4260. if (buf[pos++] < 128) {
  4261. this.pos = pos;
  4262. return value;
  4263. }
  4264. }
  4265. /* istanbul ignore next */
  4266. this.pos = pos;
  4267. throw Error("invalid varint encoding");
  4268. };
  4269. /**
  4270. * Reads a field tag.
  4271. * @function
  4272. * @returns {number} Tag read
  4273. */
  4274. Reader.prototype.tag = function read_tag() {
  4275. var buf = this.buf,
  4276. pos = this.pos,
  4277. value = (buf[pos] & 127) >>> 0;
  4278. if (buf[pos++] < 128) {
  4279. this.pos = pos;
  4280. return value;
  4281. }
  4282. value = (value | (buf[pos] & 127) << 7) >>> 0;
  4283. if (buf[pos++] < 128) {
  4284. this.pos = pos;
  4285. return value;
  4286. }
  4287. value = (value | (buf[pos] & 127) << 14) >>> 0;
  4288. if (buf[pos++] < 128) {
  4289. this.pos = pos;
  4290. return value;
  4291. }
  4292. value = (value | (buf[pos] & 127) << 21) >>> 0;
  4293. if (buf[pos++] < 128) {
  4294. this.pos = pos;
  4295. return value;
  4296. }
  4297. value = (value | (buf[pos] & 15) << 28) >>> 0;
  4298. if (buf[pos] < 128 && (buf[pos] & 112) === 0) {
  4299. this.pos = pos + 1;
  4300. return value;
  4301. }
  4302. this.pos = pos + 1;
  4303. throw Error("invalid tag encoding");
  4304. };
  4305. /**
  4306. * Reads a varint as a signed 32 bit value.
  4307. * @returns {number} Value read
  4308. */
  4309. Reader.prototype.int32 = function read_int32() {
  4310. return this.uint32() | 0;
  4311. };
  4312. /**
  4313. * Reads a zig-zag encoded varint as a signed 32 bit value.
  4314. * @returns {number} Value read
  4315. */
  4316. Reader.prototype.sint32 = function read_sint32() {
  4317. var value = this.uint32();
  4318. return value >>> 1 ^ -(value & 1) | 0;
  4319. };
  4320. /* eslint-disable no-invalid-this */
  4321. function readLongVarint() {
  4322. // tends to deopt with local vars for octet etc.
  4323. var bits = new LongBits(0, 0);
  4324. var i = 0;
  4325. if (this.len - this.pos > 4) { // fast route (lo)
  4326. for (; i < 4; ++i) {
  4327. // 1st..4th
  4328. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
  4329. if (this.buf[this.pos++] < 128)
  4330. return bits;
  4331. }
  4332. // 5th
  4333. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
  4334. bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
  4335. if (this.buf[this.pos++] < 128)
  4336. return bits;
  4337. i = 0;
  4338. } else {
  4339. for (; i < 4; ++i) {
  4340. /* istanbul ignore if */
  4341. if (this.pos >= this.len)
  4342. throw indexOutOfRange(this);
  4343. // 1st..4th
  4344. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
  4345. if (this.buf[this.pos++] < 128)
  4346. return bits;
  4347. }
  4348. throw indexOutOfRange(this);
  4349. }
  4350. if (this.len - this.pos > 4) { // fast route (hi)
  4351. for (; i < 5; ++i) {
  4352. // 6th..10th
  4353. bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
  4354. if (this.buf[this.pos++] < 128)
  4355. return bits;
  4356. }
  4357. } else {
  4358. for (; i < 5; ++i) {
  4359. /* istanbul ignore if */
  4360. if (this.pos >= this.len)
  4361. throw indexOutOfRange(this);
  4362. // 6th..10th
  4363. bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
  4364. if (this.buf[this.pos++] < 128)
  4365. return bits;
  4366. }
  4367. }
  4368. /* istanbul ignore next */
  4369. throw Error("invalid varint encoding");
  4370. }
  4371. /* eslint-enable no-invalid-this */
  4372. /**
  4373. * Reads a varint as a signed 64 bit value.
  4374. * @name Reader#int64
  4375. * @function
  4376. * @returns {Long} Value read
  4377. */
  4378. /**
  4379. * Reads a varint as an unsigned 64 bit value.
  4380. * @name Reader#uint64
  4381. * @function
  4382. * @returns {Long} Value read
  4383. */
  4384. /**
  4385. * Reads a zig-zag encoded varint as a signed 64 bit value.
  4386. * @name Reader#sint64
  4387. * @function
  4388. * @returns {Long} Value read
  4389. */
  4390. /**
  4391. * Reads a varint as a boolean.
  4392. * @returns {boolean} Value read
  4393. */
  4394. Reader.prototype.bool = function read_bool() {
  4395. var value = false,
  4396. b;
  4397. for (var i = 0; i < 10; ++i) {
  4398. /* istanbul ignore if */
  4399. if (this.pos >= this.len)
  4400. throw indexOutOfRange(this);
  4401. b = this.buf[this.pos++];
  4402. if (b & 127)
  4403. value = true;
  4404. if (b < 128)
  4405. return value;
  4406. }
  4407. /* istanbul ignore next */
  4408. throw Error("invalid varint encoding");
  4409. };
  4410. function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`
  4411. return (buf[end - 4]
  4412. | buf[end - 3] << 8
  4413. | buf[end - 2] << 16
  4414. | buf[end - 1] << 24) >>> 0;
  4415. }
  4416. /**
  4417. * Reads fixed 32 bits as an unsigned 32 bit integer.
  4418. * @returns {number} Value read
  4419. */
  4420. Reader.prototype.fixed32 = function read_fixed32() {
  4421. /* istanbul ignore if */
  4422. if (this.pos + 4 > this.len)
  4423. throw indexOutOfRange(this, 4);
  4424. return readFixed32_end(this.buf, this.pos += 4);
  4425. };
  4426. /**
  4427. * Reads fixed 32 bits as a signed 32 bit integer.
  4428. * @returns {number} Value read
  4429. */
  4430. Reader.prototype.sfixed32 = function read_sfixed32() {
  4431. /* istanbul ignore if */
  4432. if (this.pos + 4 > this.len)
  4433. throw indexOutOfRange(this, 4);
  4434. return readFixed32_end(this.buf, this.pos += 4) | 0;
  4435. };
  4436. /* eslint-disable no-invalid-this */
  4437. function readFixed64(/* this: Reader */) {
  4438. /* istanbul ignore if */
  4439. if (this.pos + 8 > this.len)
  4440. throw indexOutOfRange(this, 8);
  4441. return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
  4442. }
  4443. /* eslint-enable no-invalid-this */
  4444. /**
  4445. * Reads fixed 64 bits.
  4446. * @name Reader#fixed64
  4447. * @function
  4448. * @returns {Long} Value read
  4449. */
  4450. /**
  4451. * Reads zig-zag encoded fixed 64 bits.
  4452. * @name Reader#sfixed64
  4453. * @function
  4454. * @returns {Long} Value read
  4455. */
  4456. /**
  4457. * Reads a float (32 bit) as a number.
  4458. * @function
  4459. * @returns {number} Value read
  4460. */
  4461. Reader.prototype.float = function read_float() {
  4462. /* istanbul ignore if */
  4463. if (this.pos + 4 > this.len)
  4464. throw indexOutOfRange(this, 4);
  4465. var value = util.float.readFloatLE(this.buf, this.pos);
  4466. this.pos += 4;
  4467. return value;
  4468. };
  4469. /**
  4470. * Reads a double (64 bit float) as a number.
  4471. * @function
  4472. * @returns {number} Value read
  4473. */
  4474. Reader.prototype.double = function read_double() {
  4475. /* istanbul ignore if */
  4476. if (this.pos + 8 > this.len)
  4477. throw indexOutOfRange(this, 4);
  4478. var value = util.float.readDoubleLE(this.buf, this.pos);
  4479. this.pos += 8;
  4480. return value;
  4481. };
  4482. /**
  4483. * Reads a sequence of bytes preceeded by its length as a varint.
  4484. * @returns {Uint8Array} Value read
  4485. */
  4486. Reader.prototype.bytes = function read_bytes() {
  4487. var length = this.uint32(),
  4488. start = this.pos,
  4489. end = this.pos + length;
  4490. /* istanbul ignore if */
  4491. if (end > this.len)
  4492. throw indexOutOfRange(this, length);
  4493. this.pos = end;
  4494. return this.raw(start, end);
  4495. };
  4496. /**
  4497. * Reads a string preceeded by its byte length as a varint.
  4498. * @returns {string} Value read
  4499. */
  4500. Reader.prototype.string = function read_string() {
  4501. var length = this.uint32(),
  4502. start = this.pos,
  4503. end = this.pos + length;
  4504. /* istanbul ignore if */
  4505. if (end > this.len)
  4506. throw indexOutOfRange(this, length);
  4507. this.pos = end;
  4508. return utf8.read(this.buf, start, end);
  4509. };
  4510. /**
  4511. * Reads a string preceeded by its byte length as a varint, rejecting invalid UTF8.
  4512. * @returns {string} Value read
  4513. */
  4514. Reader.prototype.stringVerify = function read_string_verify() {
  4515. var length = this.uint32(),
  4516. start = this.pos,
  4517. end = this.pos + length;
  4518. /* istanbul ignore if */
  4519. if (end > this.len)
  4520. throw indexOutOfRange(this, length);
  4521. this.pos = end;
  4522. return utf8.readStrict(this.buf, start, end);
  4523. };
  4524. /**
  4525. * Skips the specified number of bytes if specified, otherwise skips a varint.
  4526. * @param {number} [length] Length if known, otherwise a varint is assumed
  4527. * @returns {Reader} `this`
  4528. */
  4529. Reader.prototype.skip = function skip(length) {
  4530. if (typeof length === "number") {
  4531. /* istanbul ignore if */
  4532. if (this.pos + length > this.len)
  4533. throw indexOutOfRange(this, length);
  4534. this.pos += length;
  4535. } else {
  4536. do {
  4537. /* istanbul ignore if */
  4538. if (this.pos >= this.len)
  4539. throw indexOutOfRange(this);
  4540. } while (this.buf[this.pos++] & 128);
  4541. }
  4542. return this;
  4543. };
  4544. /**
  4545. * Recursion limit.
  4546. * @type {number}
  4547. */
  4548. Reader.recursionLimit = util.recursionLimit;
  4549. /**
  4550. * Whether readers discard unknown fields while decoding.
  4551. * @type {boolean}
  4552. */
  4553. Reader.discardUnknown = true;
  4554. /**
  4555. * Skips the next element of the specified wire type.
  4556. * @param {number} wireType Wire type received
  4557. * @param {number} [depth] Depth of recursion to control nested calls; 0 if omitted
  4558. * @param {number} [fieldNumber] Field number for validating group end tags
  4559. * @returns {Reader} `this`
  4560. */
  4561. Reader.prototype.skipType = function(wireType, depth, fieldNumber) {
  4562. if (depth === undefined) depth = 0;
  4563. if (depth > Reader.recursionLimit)
  4564. throw Error("max depth exceeded");
  4565. if (fieldNumber === 0)
  4566. throw Error("illegal tag: field number 0");
  4567. switch (wireType) {
  4568. case 0:
  4569. this.skip();
  4570. break;
  4571. case 1:
  4572. this.skip(8);
  4573. break;
  4574. case 2:
  4575. this.skip(this.uint32());
  4576. break;
  4577. case 3:
  4578. while (true) {
  4579. var tag = this.tag();
  4580. var nestedField = tag >>> 3;
  4581. wireType = tag & 7;
  4582. if (!nestedField)
  4583. throw Error("illegal tag: field number 0");
  4584. if (wireType === 4) {
  4585. if (fieldNumber !== undefined && nestedField !== fieldNumber)
  4586. throw Error("invalid end group tag");
  4587. break;
  4588. }
  4589. this.skipType(wireType, depth + 1, nestedField);
  4590. }
  4591. break;
  4592. case 5:
  4593. this.skip(4);
  4594. break;
  4595. /* istanbul ignore next */
  4596. default:
  4597. throw Error("invalid wire type " + wireType + " at offset " + this.pos);
  4598. }
  4599. return this;
  4600. };
  4601. Reader._configure = function(BufferReader_) {
  4602. BufferReader = BufferReader_;
  4603. Reader.create = create();
  4604. BufferReader._configure();
  4605. var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";
  4606. util.merge(Reader.prototype, {
  4607. int64: function read_int64() {
  4608. return readLongVarint.call(this)[fn](false);
  4609. },
  4610. uint64: function read_uint64() {
  4611. return readLongVarint.call(this)[fn](true);
  4612. },
  4613. sint64: function read_sint64() {
  4614. return readLongVarint.call(this).zzDecode()[fn](false);
  4615. },
  4616. fixed64: function read_fixed64() {
  4617. return readFixed64.call(this)[fn](true);
  4618. },
  4619. sfixed64: function read_sfixed64() {
  4620. return readFixed64.call(this)[fn](false);
  4621. }
  4622. });
  4623. };
  4624. },{"37":37}],19:[function(require,module,exports){
  4625. "use strict";
  4626. module.exports = BufferReader;
  4627. // extends Reader
  4628. var Reader = require(18);
  4629. (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;
  4630. var util = require(37);
  4631. /**
  4632. * Constructs a new buffer reader instance.
  4633. * @classdesc Wire format reader using node buffers.
  4634. * @extends Reader
  4635. * @constructor
  4636. * @param {Buffer} buffer Buffer to read from
  4637. */
  4638. function BufferReader(buffer) {
  4639. Reader.call(this, buffer);
  4640. /**
  4641. * Read buffer.
  4642. * @name BufferReader#buf
  4643. * @type {Buffer}
  4644. */
  4645. }
  4646. BufferReader._configure = function () {
  4647. /* istanbul ignore else */
  4648. if (util.Buffer)
  4649. BufferReader.prototype._slice = util.Buffer.prototype.slice;
  4650. };
  4651. /**
  4652. * Returns raw bytes from the backing buffer without advancing the reader.
  4653. * @name BufferReader#raw
  4654. * @function
  4655. * @param {number} start Start offset
  4656. * @param {number} end End offset
  4657. * @returns {Buffer} Raw bytes
  4658. */
  4659. BufferReader.prototype.raw = function read_raw_buffer(start, end) {
  4660. if (start === end)
  4661. return util.Buffer.alloc(0);
  4662. return this._slice.call(this.buf, start, end);
  4663. };
  4664. /**
  4665. * @override
  4666. */
  4667. BufferReader.prototype.string = function read_string_buffer() {
  4668. var len = this.uint32(), // modifies pos
  4669. start = this.pos,
  4670. end = this.pos + len;
  4671. /* istanbul ignore if */
  4672. if (end > this.len)
  4673. throw RangeError("index out of range: " + this.pos + " + " + len + " > " + this.len);
  4674. this.pos = end;
  4675. return this.buf.utf8Slice
  4676. ? this.buf.utf8Slice(start, end)
  4677. : this.buf.toString("utf-8", start, end);
  4678. };
  4679. /**
  4680. * Reads a sequence of bytes preceeded by its length as a varint.
  4681. * @name BufferReader#bytes
  4682. * @function
  4683. * @returns {Buffer} Value read
  4684. */
  4685. BufferReader._configure();
  4686. },{"18":18,"37":37}],20:[function(require,module,exports){
  4687. "use strict";
  4688. module.exports = Root;
  4689. // extends Namespace
  4690. var Namespace = require(14);
  4691. ((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root";
  4692. var Field = require(7),
  4693. Enum = require(6),
  4694. OneOf = require(16),
  4695. util = require(28);
  4696. var Type, // cyclic
  4697. parse, // might be excluded
  4698. common; // "
  4699. /**
  4700. * Constructs a new root namespace instance.
  4701. * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.
  4702. * @extends NamespaceBase
  4703. * @constructor
  4704. * @param {Object.<string,*>} [options] Top level options
  4705. */
  4706. function Root(options) {
  4707. Namespace.call(this, "", options);
  4708. /**
  4709. * Deferred extension fields.
  4710. * @type {Field[]}
  4711. */
  4712. this.deferred = [];
  4713. /**
  4714. * Resolved file names of loaded files.
  4715. * @type {string[]}
  4716. */
  4717. this.files = [];
  4718. /**
  4719. * Edition, defaults to proto2 if unspecified.
  4720. * @type {string}
  4721. * @private
  4722. */
  4723. this._edition = "proto2";
  4724. /**
  4725. * Global lookup cache of fully qualified names.
  4726. * @type {Object.<string,ReflectionObject>}
  4727. * @private
  4728. */
  4729. this._fullyQualifiedObjects = {};
  4730. }
  4731. /**
  4732. * Loads a namespace descriptor into a root namespace.
  4733. * @param {INamespace} json Namespace descriptor
  4734. * @param {Root} [root] Root namespace, defaults to create a new one if omitted
  4735. * @param {number} [depth] Current nesting depth, defaults to `0`
  4736. * @returns {Root} Root namespace
  4737. */
  4738. Root.fromJSON = function fromJSON(json, root, depth) {
  4739. if (depth === undefined)
  4740. depth = 0;
  4741. if (depth > util.recursionLimit)
  4742. throw Error("max depth exceeded");
  4743. if (!root)
  4744. root = new Root();
  4745. if (json.options)
  4746. root.setOptions(json.options);
  4747. return root.addJSON(json.nested, depth).resolveAll();
  4748. };
  4749. /**
  4750. * Resolves the path of an imported file, relative to the importing origin.
  4751. * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.
  4752. * @function
  4753. * @param {string} origin The file name of the importing file
  4754. * @param {string} target The file name being imported
  4755. * @returns {string|null} Resolved path to `target` or `null` to skip the file
  4756. */
  4757. Root.prototype.resolvePath = util.path.resolve;
  4758. /**
  4759. * Fetch content from file path or url
  4760. * This method exists so you can override it with your own logic.
  4761. * @function
  4762. * @param {string} path File path or url
  4763. * @param {FetchCallback} callback Callback function
  4764. * @returns {undefined}
  4765. */
  4766. Root.prototype.fetch = util.fetch;
  4767. // A symbol-like function to safely signal synchronous loading
  4768. /* istanbul ignore next */
  4769. function SYNC() {} // eslint-disable-line no-empty-function
  4770. /**
  4771. * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
  4772. * @param {string|string[]} filename Names of one or multiple files to load
  4773. * @param {IParseOptions} options Parse options
  4774. * @param {LoadCallback} callback Callback function
  4775. * @returns {undefined}
  4776. */
  4777. Root.prototype.load = function load(filename, options, callback) {
  4778. if (typeof options === "function") {
  4779. callback = options;
  4780. options = undefined;
  4781. }
  4782. var self = this;
  4783. if (!callback) {
  4784. return util.asPromise(load, self, filename, options);
  4785. }
  4786. var sync = callback === SYNC; // undocumented
  4787. // Finishes loading by calling the callback (exactly once)
  4788. function finish(err, root) {
  4789. /* istanbul ignore if */
  4790. if (!callback) {
  4791. return;
  4792. }
  4793. if (sync) {
  4794. throw err;
  4795. }
  4796. if (root) {
  4797. root.resolveAll();
  4798. }
  4799. var cb = callback;
  4800. callback = null;
  4801. cb(err, root);
  4802. }
  4803. // Bundled definition existence checking
  4804. function getBundledFileName(filename) {
  4805. var idx = filename.lastIndexOf("google/protobuf/");
  4806. if (idx > -1) {
  4807. var altname = filename.substring(idx);
  4808. if (Object.prototype.hasOwnProperty.call(common, altname)) return altname;
  4809. }
  4810. if (Object.prototype.hasOwnProperty.call(common, filename)) return filename;
  4811. return null;
  4812. }
  4813. // Processes a single file
  4814. function process(filename, source, depth) {
  4815. if (depth === undefined)
  4816. depth = 0;
  4817. try {
  4818. if (depth > util.recursionLimit)
  4819. throw Error("max depth exceeded");
  4820. if (util.isString(source) && source.charAt(0) === "{")
  4821. source = JSON.parse(source);
  4822. if (!util.isString(source))
  4823. self.setOptions(source.options).addJSON(source.nested);
  4824. else {
  4825. parse.filename = filename;
  4826. var parsed = parse(source, self, options),
  4827. resolved,
  4828. i = 0;
  4829. if (parsed.imports)
  4830. for (; i < parsed.imports.length; ++i)
  4831. if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))
  4832. fetch(resolved, false, depth + 1);
  4833. if (parsed.weakImports)
  4834. for (i = 0; i < parsed.weakImports.length; ++i)
  4835. if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))
  4836. fetch(resolved, true, depth + 1);
  4837. }
  4838. } catch (err) {
  4839. finish(err);
  4840. }
  4841. if (!sync && !queued) {
  4842. finish(null, self); // only once anyway
  4843. }
  4844. }
  4845. // Fetches a single file
  4846. function fetch(filename, weak, depth) {
  4847. if (depth === undefined)
  4848. depth = 0;
  4849. filename = getBundledFileName(filename) || filename;
  4850. // Skip if already loaded / attempted
  4851. if (self.files.indexOf(filename) > -1) {
  4852. return;
  4853. }
  4854. self.files.push(filename);
  4855. // Shortcut bundled definitions
  4856. if (Object.prototype.hasOwnProperty.call(common, filename)) {
  4857. if (sync) {
  4858. process(filename, common[filename], depth);
  4859. } else {
  4860. ++queued;
  4861. setTimeout(function() {
  4862. --queued;
  4863. process(filename, common[filename], depth);
  4864. });
  4865. }
  4866. return;
  4867. }
  4868. // Otherwise fetch from disk or network
  4869. if (sync) {
  4870. var source;
  4871. try {
  4872. source = util.fs.readFileSync(filename).toString("utf8");
  4873. } catch (err) {
  4874. if (!weak)
  4875. finish(err);
  4876. return;
  4877. }
  4878. process(filename, source, depth);
  4879. } else {
  4880. ++queued;
  4881. self.fetch(filename, function(err, source) {
  4882. --queued;
  4883. /* istanbul ignore if */
  4884. if (!callback) {
  4885. return; // terminated meanwhile
  4886. }
  4887. if (err) {
  4888. /* istanbul ignore else */
  4889. if (!weak)
  4890. finish(err);
  4891. else if (!queued) // can't be covered reliably
  4892. finish(null, self);
  4893. return;
  4894. }
  4895. process(filename, source, depth);
  4896. });
  4897. }
  4898. }
  4899. var queued = 0;
  4900. // Assembling the root namespace doesn't require working type
  4901. // references anymore, so we can load everything in parallel
  4902. if (util.isString(filename)) {
  4903. filename = [ filename ];
  4904. }
  4905. for (var i = 0, resolved; i < filename.length; ++i)
  4906. if (resolved = self.resolvePath("", filename[i]))
  4907. fetch(resolved);
  4908. if (sync) {
  4909. self.resolveAll();
  4910. return self;
  4911. }
  4912. if (!queued) {
  4913. finish(null, self);
  4914. }
  4915. return self;
  4916. };
  4917. // function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined
  4918. /**
  4919. * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
  4920. * @function Root#load
  4921. * @param {string|string[]} filename Names of one or multiple files to load
  4922. * @param {LoadCallback} callback Callback function
  4923. * @returns {undefined}
  4924. * @variation 2
  4925. */
  4926. // function load(filename:string, callback:LoadCallback):undefined
  4927. /**
  4928. * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.
  4929. * @function Root#load
  4930. * @param {string|string[]} filename Names of one or multiple files to load
  4931. * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
  4932. * @returns {Promise<Root>} Promise
  4933. * @variation 3
  4934. */
  4935. // function load(filename:string, [options:IParseOptions]):Promise<Root>
  4936. /**
  4937. * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).
  4938. * @function Root#loadSync
  4939. * @param {string|string[]} filename Names of one or multiple files to load
  4940. * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
  4941. * @returns {Root} Root namespace
  4942. * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
  4943. */
  4944. Root.prototype.loadSync = function loadSync(filename, options) {
  4945. if (!util.isNode)
  4946. throw Error("not supported");
  4947. return this.load(filename, options, SYNC);
  4948. };
  4949. /**
  4950. * @override
  4951. */
  4952. Root.prototype.resolveAll = function resolveAll() {
  4953. if (!this._needsRecursiveResolve) return this;
  4954. if (this.deferred.length)
  4955. throw Error("unresolvable extensions: " + this.deferred.map(function(field) {
  4956. return "'extend " + field.extend + "' in " + field.parent.fullName;
  4957. }).join(", "));
  4958. return Namespace.prototype.resolveAll.call(this);
  4959. };
  4960. // only uppercased (and thus conflict-free) children are exposed, see below
  4961. var exposeRe = /^[A-Z]/;
  4962. /**
  4963. * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.
  4964. * @param {Root} root Root instance
  4965. * @param {Field} field Declaring extension field witin the declaring type
  4966. * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise
  4967. * @inner
  4968. * @ignore
  4969. */
  4970. function tryHandleExtension(root, field) {
  4971. var extendedType = field.parent.lookup(field.extend);
  4972. if (extendedType) {
  4973. var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);
  4974. //do not allow to extend same field twice to prevent the error
  4975. if (extendedType.get(sisterField.name)) {
  4976. return true;
  4977. }
  4978. sisterField.declaringField = field;
  4979. field.extensionField = sisterField;
  4980. extendedType.add(sisterField);
  4981. return true;
  4982. }
  4983. return false;
  4984. }
  4985. /**
  4986. * Called when any object is added to this root or its sub-namespaces.
  4987. * @param {ReflectionObject} object Object added
  4988. * @returns {undefined}
  4989. * @private
  4990. */
  4991. Root.prototype._handleAdd = function _handleAdd(object) {
  4992. if (object instanceof Field) {
  4993. if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)
  4994. if (!tryHandleExtension(this, object))
  4995. this.deferred.push(object);
  4996. } else if (object instanceof Enum) {
  4997. if (exposeRe.test(object.name))
  4998. object.parent[object.name] = object.values; // expose enum values as property of its parent
  4999. } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {
  5000. if (object instanceof Type) // Try to handle any deferred extensions
  5001. for (var i = 0; i < this.deferred.length;)
  5002. if (tryHandleExtension(this, this.deferred[i]))
  5003. this.deferred.splice(i, 1);
  5004. else
  5005. ++i;
  5006. for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace
  5007. this._handleAdd(object._nestedArray[j]);
  5008. if (exposeRe.test(object.name))
  5009. object.parent[object.name] = object; // expose namespace as property of its parent
  5010. }
  5011. if (object instanceof Type || object instanceof Enum || object instanceof Field) {
  5012. // Only store types and enums for quick lookup during resolve.
  5013. this._fullyQualifiedObjects[object.fullName] = object;
  5014. }
  5015. // The above also adds uppercased (and thus conflict-free) nested types, services and enums as
  5016. // properties of namespaces just like static code does. This allows using a .d.ts generated for
  5017. // a static module with reflection-based solutions where the condition is met.
  5018. };
  5019. /**
  5020. * Called when any object is removed from this root or its sub-namespaces.
  5021. * @param {ReflectionObject} object Object removed
  5022. * @returns {undefined}
  5023. * @private
  5024. */
  5025. Root.prototype._handleRemove = function _handleRemove(object) {
  5026. if (object instanceof Field) {
  5027. if (/* an extension field */ object.extend !== undefined) {
  5028. if (/* already handled */ object.extensionField) { // remove its sister field
  5029. object.extensionField.parent.remove(object.extensionField);
  5030. object.extensionField = null;
  5031. } else { // cancel the extension
  5032. var index = this.deferred.indexOf(object);
  5033. /* istanbul ignore else */
  5034. if (index > -1)
  5035. this.deferred.splice(index, 1);
  5036. }
  5037. }
  5038. } else if (object instanceof Enum) {
  5039. if (exposeRe.test(object.name))
  5040. delete object.parent[object.name]; // unexpose enum values
  5041. } else if (object instanceof Namespace) {
  5042. for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace
  5043. this._handleRemove(object._nestedArray[i]);
  5044. if (exposeRe.test(object.name))
  5045. delete object.parent[object.name]; // unexpose namespaces
  5046. }
  5047. delete this._fullyQualifiedObjects[object.fullName];
  5048. };
  5049. // Sets up cyclic dependencies (called in index-light)
  5050. Root._configure = function(Type_, parse_, common_) {
  5051. Type = Type_;
  5052. parse = parse_;
  5053. common = common_;
  5054. };
  5055. },{"14":14,"16":16,"28":28,"6":6,"7":7}],21:[function(require,module,exports){
  5056. "use strict";
  5057. module.exports = Object.create(null);
  5058. /**
  5059. * Named roots.
  5060. * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
  5061. * Can also be used manually to make roots available across modules.
  5062. * @name roots
  5063. * @type {Object.<string,Root>}
  5064. * @example
  5065. * // pbjs -r myroot -o compiled.js ...
  5066. *
  5067. * // in another module:
  5068. * require("./compiled.js");
  5069. *
  5070. * // in any subsequent module:
  5071. * var root = protobuf.roots["myroot"];
  5072. */
  5073. },{}],22:[function(require,module,exports){
  5074. "use strict";
  5075. /**
  5076. * Streaming RPC helpers.
  5077. * @namespace
  5078. */
  5079. var rpc = exports;
  5080. /**
  5081. * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
  5082. * @typedef RPCImpl
  5083. * @type {function}
  5084. * @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called
  5085. * @param {Uint8Array} requestData Request data
  5086. * @param {RPCImplCallback} callback Callback function
  5087. * @returns {undefined}
  5088. * @example
  5089. * function rpcImpl(method, requestData, callback) {
  5090. * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code
  5091. * throw Error("no such method");
  5092. * asynchronouslyObtainAResponse(requestData, function(err, responseData) {
  5093. * callback(err, responseData);
  5094. * });
  5095. * }
  5096. */
  5097. /**
  5098. * Node-style callback as used by {@link RPCImpl}.
  5099. * @typedef RPCImplCallback
  5100. * @type {function}
  5101. * @param {Error|null} error Error, if any, otherwise `null`
  5102. * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error
  5103. * @returns {undefined}
  5104. */
  5105. rpc.Service = require(23);
  5106. },{"23":23}],23:[function(require,module,exports){
  5107. "use strict";
  5108. module.exports = Service;
  5109. var util = require(37);
  5110. // Extends EventEmitter
  5111. (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;
  5112. /**
  5113. * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
  5114. *
  5115. * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
  5116. * @typedef rpc.ServiceMethodCallback
  5117. * @template TRes extends Message<TRes>
  5118. * @type {function}
  5119. * @param {Error|null} error Error, if any
  5120. * @param {TRes} [response] Response message
  5121. * @returns {undefined}
  5122. */
  5123. /**
  5124. * A service method part of a {@link rpc.Service} as created by {@link Service.create}.
  5125. * @typedef rpc.ServiceMethod
  5126. * @template TReq extends Message<TReq>
  5127. * @template TRes extends Message<TRes>
  5128. * @type {{
  5129. * (request: TReq|Properties<TReq>, callback: rpc.ServiceMethodCallback<TRes>): void;
  5130. * (request: TReq|Properties<TReq>): Promise<TRes>;
  5131. * readonly name: string;
  5132. * readonly path: string;
  5133. * readonly requestType: string;
  5134. * readonly responseType: string;
  5135. * readonly requestStream: true|undefined;
  5136. * readonly responseStream: true|undefined;
  5137. * }}
  5138. */
  5139. /**
  5140. * Constructs a new RPC service instance.
  5141. * @classdesc An RPC service as returned by {@link Service#create}.
  5142. * @exports rpc.Service
  5143. * @extends util.EventEmitter
  5144. * @constructor
  5145. * @param {RPCImpl} rpcImpl RPC implementation
  5146. * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
  5147. * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
  5148. */
  5149. function Service(rpcImpl, requestDelimited, responseDelimited) {
  5150. if (typeof rpcImpl !== "function")
  5151. throw TypeError("rpcImpl must be a function");
  5152. util.EventEmitter.call(this);
  5153. /**
  5154. * RPC implementation. Becomes `null` once the service is ended.
  5155. * @type {RPCImpl|null}
  5156. */
  5157. this.rpcImpl = rpcImpl;
  5158. /**
  5159. * Whether requests are length-delimited.
  5160. * @type {boolean}
  5161. */
  5162. this.requestDelimited = Boolean(requestDelimited);
  5163. /**
  5164. * Whether responses are length-delimited.
  5165. * @type {boolean}
  5166. */
  5167. this.responseDelimited = Boolean(responseDelimited);
  5168. }
  5169. /**
  5170. * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
  5171. * @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method
  5172. * @param {Constructor<TReq>} requestCtor Request constructor
  5173. * @param {Constructor<TRes>} responseCtor Response constructor
  5174. * @param {TReq|Properties<TReq>} request Request message or plain object
  5175. * @param {rpc.ServiceMethodCallback<TRes>} callback Service callback
  5176. * @returns {undefined}
  5177. * @template TReq extends Message<TReq>
  5178. * @template TRes extends Message<TRes>
  5179. */
  5180. Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {
  5181. if (!request)
  5182. throw TypeError("request must be specified");
  5183. var self = this;
  5184. if (!callback)
  5185. return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);
  5186. if (!self.rpcImpl) {
  5187. setTimeout(function() { callback(Error("already ended")); }, 0);
  5188. return undefined;
  5189. }
  5190. try {
  5191. return self.rpcImpl(
  5192. method,
  5193. requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),
  5194. function rpcCallback(err, response) {
  5195. if (err) {
  5196. self.emit("error", err, method);
  5197. return callback(err);
  5198. }
  5199. if (response === null) {
  5200. self.end(/* endedByRPC */ true);
  5201. return undefined;
  5202. }
  5203. if (!(response instanceof responseCtor)) {
  5204. try {
  5205. response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);
  5206. } catch (err) {
  5207. self.emit("error", err, method);
  5208. return callback(err);
  5209. }
  5210. }
  5211. self.emit("data", response, method);
  5212. return callback(null, response);
  5213. }
  5214. );
  5215. } catch (err) {
  5216. self.emit("error", err, method);
  5217. setTimeout(function() { callback(err); }, 0);
  5218. return undefined;
  5219. }
  5220. };
  5221. /**
  5222. * Ends this service and emits the `end` event.
  5223. * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.
  5224. * @returns {rpc.Service} `this`
  5225. */
  5226. Service.prototype.end = function end(endedByRPC) {
  5227. if (this.rpcImpl) {
  5228. if (!endedByRPC) // signal end to rpcImpl
  5229. this.rpcImpl(null, null, null);
  5230. this.rpcImpl = null;
  5231. this.emit("end").off();
  5232. }
  5233. return this;
  5234. };
  5235. },{"37":37}],24:[function(require,module,exports){
  5236. "use strict";
  5237. module.exports = Service;
  5238. // extends Namespace
  5239. var Namespace = require(14);
  5240. ((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service";
  5241. var Method = require(13),
  5242. util = require(28),
  5243. rpc = require(22);
  5244. /**
  5245. * Constructs a new service instance.
  5246. * @classdesc Reflected service.
  5247. * @extends NamespaceBase
  5248. * @constructor
  5249. * @param {string} name Service name
  5250. * @param {Object.<string,*>} [options] Service options
  5251. * @throws {TypeError} If arguments are invalid
  5252. */
  5253. function Service(name, options) {
  5254. Namespace.call(this, name, options);
  5255. /**
  5256. * Service methods.
  5257. * @type {Object.<string,Method>}
  5258. */
  5259. this.methods = {}; // toJSON, marker
  5260. /**
  5261. * Cached methods as an array.
  5262. * @type {Method[]|null}
  5263. * @private
  5264. */
  5265. this._methodsArray = null;
  5266. }
  5267. /**
  5268. * Service descriptor.
  5269. * @interface IService
  5270. * @extends INamespace
  5271. * @property {string} [edition] Edition
  5272. * @property {Object.<string,IMethod>} methods Method descriptors
  5273. * @property {string|null} [comment] Service comment
  5274. */
  5275. /**
  5276. * Constructs a service from a service descriptor.
  5277. * @param {string} name Service name
  5278. * @param {IService} json Service descriptor
  5279. * @param {number} [depth] Current nesting depth, defaults to `0`
  5280. * @returns {Service} Created service
  5281. * @throws {TypeError} If arguments are invalid
  5282. */
  5283. Service.fromJSON = function fromJSON(name, json, depth) {
  5284. if (depth === undefined)
  5285. depth = 0;
  5286. if (depth > util.recursionLimit)
  5287. throw Error("max depth exceeded");
  5288. var service = new Service(name, json.options);
  5289. /* istanbul ignore else */
  5290. if (json.methods)
  5291. for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)
  5292. service.add(Method.fromJSON(names[i], json.methods[names[i]]));
  5293. if (json.nested)
  5294. service.addJSON(json.nested, depth);
  5295. if (json.edition)
  5296. service._edition = json.edition;
  5297. service.comment = json.comment;
  5298. service._defaultEdition = "proto3"; // For backwards-compatibility.
  5299. return service;
  5300. };
  5301. /**
  5302. * Converts this service to a service descriptor.
  5303. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  5304. * @returns {IService} Service descriptor
  5305. */
  5306. Service.prototype.toJSON = function toJSON(toJSONOptions) {
  5307. var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
  5308. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  5309. return util.toObject([
  5310. "edition" , this._editionToJSON(),
  5311. "options" , inherited && inherited.options || undefined,
  5312. "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},
  5313. "nested" , inherited && inherited.nested || undefined,
  5314. "comment" , keepComments ? this.comment : undefined
  5315. ]);
  5316. };
  5317. /**
  5318. * Methods of this service as an array for iteration.
  5319. * @name Service#methodsArray
  5320. * @type {Method[]}
  5321. * @readonly
  5322. */
  5323. Object.defineProperty(Service.prototype, "methodsArray", {
  5324. get: function() {
  5325. return this._methodsArray || (this._methodsArray = util.toArray(this.methods));
  5326. }
  5327. });
  5328. function clearCache(service) {
  5329. service._methodsArray = null;
  5330. return service;
  5331. }
  5332. /**
  5333. * @override
  5334. */
  5335. Service.prototype.get = function get(name) {
  5336. return Object.prototype.hasOwnProperty.call(this.methods, name)
  5337. ? this.methods[name]
  5338. : Namespace.prototype.get.call(this, name);
  5339. };
  5340. /**
  5341. * @override
  5342. */
  5343. Service.prototype.resolveAll = function resolveAll() {
  5344. if (!this._needsRecursiveResolve) return this;
  5345. Namespace.prototype.resolve.call(this);
  5346. var methods = this.methodsArray;
  5347. for (var i = 0; i < methods.length; ++i)
  5348. methods[i].resolve();
  5349. return this;
  5350. };
  5351. /**
  5352. * @override
  5353. */
  5354. Service.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {
  5355. if (!this._needsRecursiveFeatureResolution) return this;
  5356. edition = this._edition || edition;
  5357. Namespace.prototype._resolveFeaturesRecursive.call(this, edition);
  5358. this.methodsArray.forEach(method => {
  5359. method._resolveFeaturesRecursive(edition);
  5360. });
  5361. return this;
  5362. };
  5363. /**
  5364. * @override
  5365. */
  5366. Service.prototype.add = function add(object) {
  5367. /* istanbul ignore if */
  5368. if (this.get(object.name))
  5369. throw Error("duplicate name '" + object.name + "' in " + this);
  5370. if (object instanceof Method) {
  5371. if (object.name === "__proto__")
  5372. return this;
  5373. this.methods[object.name] = object;
  5374. object.parent = this;
  5375. return clearCache(this);
  5376. }
  5377. return Namespace.prototype.add.call(this, object);
  5378. };
  5379. /**
  5380. * @override
  5381. */
  5382. Service.prototype.remove = function remove(object) {
  5383. if (object instanceof Method) {
  5384. /* istanbul ignore if */
  5385. if (this.methods[object.name] !== object)
  5386. throw Error(object + " is not a member of " + this);
  5387. delete this.methods[object.name];
  5388. object.parent = null;
  5389. return clearCache(this);
  5390. }
  5391. return Namespace.prototype.remove.call(this, object);
  5392. };
  5393. /**
  5394. * Creates a runtime service using the specified rpc implementation.
  5395. * @param {RPCImpl} rpcImpl RPC implementation
  5396. * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
  5397. * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
  5398. * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.
  5399. */
  5400. Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {
  5401. var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);
  5402. for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {
  5403. var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, "");
  5404. rpcService[methodName] = (function(method, requestType, responseType) {
  5405. return function rpcMethod(request, callback) {
  5406. return rpc.Service.prototype.rpcCall.call(this, method, requestType, responseType, request, callback);
  5407. };
  5408. })(method, method.resolvedRequestType.ctor, method.resolvedResponseType.ctor);
  5409. }
  5410. return rpcService;
  5411. };
  5412. },{"13":13,"14":14,"22":22,"28":28}],25:[function(require,module,exports){
  5413. "use strict";
  5414. module.exports = tokenize;
  5415. var delimRe = /[\s{}=;:[\],'"()<>]/g,
  5416. stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
  5417. stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g;
  5418. var setCommentRe = /^ *[*/]+ */,
  5419. setCommentAltRe = /^\s*\*?\/*/,
  5420. setCommentSplitRe = /\n/g,
  5421. whitespaceRe = /\s/,
  5422. unescapeRe = /\\(.?)/g;
  5423. var unescapeMap = {
  5424. "0": "\0",
  5425. "r": "\r",
  5426. "n": "\n",
  5427. "t": "\t"
  5428. };
  5429. /**
  5430. * Unescapes a string.
  5431. * @param {string} str String to unescape
  5432. * @returns {string} Unescaped string
  5433. * @property {Object.<string,string>} map Special characters map
  5434. * @memberof tokenize
  5435. */
  5436. function unescape(str) {
  5437. return str.replace(unescapeRe, function($0, $1) {
  5438. switch ($1) {
  5439. case "\\":
  5440. case "":
  5441. return $1;
  5442. default:
  5443. return unescapeMap[$1] || "";
  5444. }
  5445. });
  5446. }
  5447. tokenize.unescape = unescape;
  5448. /**
  5449. * Gets the next token and advances.
  5450. * @typedef TokenizerHandleNext
  5451. * @type {function}
  5452. * @returns {string|null} Next token or `null` on eof
  5453. */
  5454. /**
  5455. * Peeks for the next token.
  5456. * @typedef TokenizerHandlePeek
  5457. * @type {function}
  5458. * @returns {string|null} Next token or `null` on eof
  5459. */
  5460. /**
  5461. * Pushes a token back to the stack.
  5462. * @typedef TokenizerHandlePush
  5463. * @type {function}
  5464. * @param {string} token Token
  5465. * @returns {undefined}
  5466. */
  5467. /**
  5468. * Skips the next token.
  5469. * @typedef TokenizerHandleSkip
  5470. * @type {function}
  5471. * @param {string} expected Expected token
  5472. * @param {boolean} [optional=false] If optional
  5473. * @returns {boolean} Whether the token matched
  5474. * @throws {Error} If the token didn't match and is not optional
  5475. */
  5476. /**
  5477. * Gets the comment on the previous line or, alternatively, the line comment on the specified line.
  5478. * @typedef TokenizerHandleCmnt
  5479. * @type {function}
  5480. * @param {number} [line] Line number
  5481. * @returns {string|null} Comment text or `null` if none
  5482. */
  5483. /**
  5484. * Handle object returned from {@link tokenize}.
  5485. * @interface ITokenizerHandle
  5486. * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)
  5487. * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)
  5488. * @property {TokenizerHandlePush} push Pushes a token back to the stack
  5489. * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws
  5490. * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any
  5491. * @property {number} line Current line number
  5492. */
  5493. /**
  5494. * Tokenizes the given .proto source and returns an object with useful utility functions.
  5495. * @param {string} source Source contents
  5496. * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.
  5497. * @returns {ITokenizerHandle} Tokenizer handle
  5498. */
  5499. function tokenize(source, alternateCommentMode) {
  5500. /* eslint-disable callback-return */
  5501. source = source.toString();
  5502. var offset = 0,
  5503. length = source.length,
  5504. line = 1,
  5505. lastCommentLine = 0,
  5506. comments = {};
  5507. var stack = [];
  5508. var stringDelim = null;
  5509. /* istanbul ignore next */
  5510. /**
  5511. * Creates an error for illegal syntax.
  5512. * @param {string} subject Subject
  5513. * @returns {Error} Error created
  5514. * @inner
  5515. */
  5516. function illegal(subject) {
  5517. return Error("illegal " + subject + " (line " + line + ")");
  5518. }
  5519. /**
  5520. * Reads a string till its end.
  5521. * @returns {string} String read
  5522. * @inner
  5523. */
  5524. function readString() {
  5525. var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe;
  5526. re.lastIndex = offset - 1;
  5527. var match = re.exec(source);
  5528. if (!match)
  5529. throw illegal("string");
  5530. offset = re.lastIndex;
  5531. push(stringDelim);
  5532. stringDelim = null;
  5533. return unescape(match[1]);
  5534. }
  5535. /**
  5536. * Gets the character at `pos` within the source.
  5537. * @param {number} pos Position
  5538. * @returns {string} Character
  5539. * @inner
  5540. */
  5541. function charAt(pos) {
  5542. return source.charAt(pos);
  5543. }
  5544. /**
  5545. * Sets the current comment text.
  5546. * @param {number} start Start offset
  5547. * @param {number} end End offset
  5548. * @param {boolean} isLeading set if a leading comment
  5549. * @returns {undefined}
  5550. * @inner
  5551. */
  5552. function setComment(start, end, isLeading) {
  5553. var comment = {
  5554. type: source.charAt(start++),
  5555. lineEmpty: false,
  5556. leading: isLeading,
  5557. };
  5558. var lookback;
  5559. if (alternateCommentMode) {
  5560. lookback = 2; // alternate comment parsing: "//" or "/*"
  5561. } else {
  5562. lookback = 3; // "///" or "/**"
  5563. }
  5564. var commentOffset = start - lookback,
  5565. c;
  5566. do {
  5567. if (--commentOffset < 0 ||
  5568. (c = source.charAt(commentOffset)) === "\n") {
  5569. comment.lineEmpty = true;
  5570. break;
  5571. }
  5572. } while (c === " " || c === "\t");
  5573. var lines = source
  5574. .substring(start, end)
  5575. .split(setCommentSplitRe);
  5576. for (var i = 0; i < lines.length; ++i)
  5577. lines[i] = lines[i]
  5578. .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "")
  5579. .trim();
  5580. comment.text = lines
  5581. .join("\n")
  5582. .trim();
  5583. comments[line] = comment;
  5584. lastCommentLine = line;
  5585. }
  5586. function isDoubleSlashCommentLine(startOffset) {
  5587. var endOffset = findEndOfLine(startOffset);
  5588. // see if remaining line matches comment pattern
  5589. var lineText = source.substring(startOffset, endOffset);
  5590. var isComment = /^\s*\/\//.test(lineText);
  5591. return isComment;
  5592. }
  5593. function findEndOfLine(cursor) {
  5594. // find end of cursor's line
  5595. var endOffset = cursor;
  5596. while (endOffset < length && charAt(endOffset) !== "\n") {
  5597. endOffset++;
  5598. }
  5599. return endOffset;
  5600. }
  5601. /**
  5602. * Obtains the next token.
  5603. * @returns {string|null} Next token or `null` on eof
  5604. * @inner
  5605. */
  5606. function next() {
  5607. if (stack.length > 0)
  5608. return stack.shift();
  5609. if (stringDelim)
  5610. return readString();
  5611. var repeat,
  5612. prev,
  5613. curr,
  5614. start,
  5615. isDoc,
  5616. nextLineIsComment,
  5617. isLeadingComment = offset === 0;
  5618. do {
  5619. if (offset === length)
  5620. return null;
  5621. repeat = false;
  5622. while (whitespaceRe.test(curr = charAt(offset))) {
  5623. if (curr === "\n") {
  5624. isLeadingComment = true;
  5625. ++line;
  5626. }
  5627. if (++offset === length)
  5628. return null;
  5629. }
  5630. if (charAt(offset) === "/") {
  5631. if (++offset === length) {
  5632. throw illegal("comment");
  5633. }
  5634. if (charAt(offset) === "/") { // Line
  5635. if (!alternateCommentMode) {
  5636. // check for triple-slash comment
  5637. isDoc = charAt(start = offset + 1) === "/";
  5638. while (charAt(++offset) !== "\n") {
  5639. if (offset === length) {
  5640. return null;
  5641. }
  5642. }
  5643. ++offset;
  5644. if (isDoc) {
  5645. setComment(start, offset - 1, isLeadingComment);
  5646. // Trailing comment cannot not be multi-line,
  5647. // so leading comment state should be reset to handle potential next comments
  5648. isLeadingComment = true;
  5649. }
  5650. ++line;
  5651. repeat = true;
  5652. } else {
  5653. // check for double-slash comments, consolidating consecutive lines
  5654. start = offset;
  5655. isDoc = false;
  5656. if (isDoubleSlashCommentLine(offset - 1)) {
  5657. isDoc = true;
  5658. do {
  5659. offset = findEndOfLine(offset);
  5660. if (offset === length) {
  5661. break;
  5662. }
  5663. offset++;
  5664. if (!isLeadingComment) {
  5665. // Trailing comment cannot not be multi-line
  5666. break;
  5667. }
  5668. nextLineIsComment = isDoubleSlashCommentLine(offset);
  5669. if (nextLineIsComment) {
  5670. line++;
  5671. }
  5672. } while (nextLineIsComment);
  5673. } else {
  5674. offset = Math.min(length, findEndOfLine(offset) + 1);
  5675. }
  5676. if (isDoc) {
  5677. setComment(start, offset, isLeadingComment);
  5678. isLeadingComment = true;
  5679. }
  5680. line++;
  5681. repeat = true;
  5682. }
  5683. } else if ((curr = charAt(offset)) === "*") { /* Block */
  5684. // check for /** (regular comment mode) or /* (alternate comment mode)
  5685. start = offset + 1;
  5686. isDoc = alternateCommentMode || charAt(start) === "*";
  5687. do {
  5688. if (curr === "\n") {
  5689. ++line;
  5690. }
  5691. if (++offset === length) {
  5692. throw illegal("comment");
  5693. }
  5694. prev = curr;
  5695. curr = charAt(offset);
  5696. } while (prev !== "*" || curr !== "/");
  5697. ++offset;
  5698. if (isDoc) {
  5699. setComment(start, offset - 2, isLeadingComment);
  5700. isLeadingComment = true;
  5701. }
  5702. repeat = true;
  5703. } else {
  5704. return "/";
  5705. }
  5706. }
  5707. } while (repeat);
  5708. // offset !== length if we got here
  5709. var end = offset;
  5710. delimRe.lastIndex = 0;
  5711. var delim = delimRe.test(charAt(end++));
  5712. if (!delim)
  5713. while (end < length && !delimRe.test(charAt(end)))
  5714. ++end;
  5715. var token = source.substring(offset, offset = end);
  5716. if (token === "\"" || token === "'")
  5717. stringDelim = token;
  5718. return token;
  5719. }
  5720. /**
  5721. * Pushes a token back to the stack.
  5722. * @param {string} token Token
  5723. * @returns {undefined}
  5724. * @inner
  5725. */
  5726. function push(token) {
  5727. stack.push(token);
  5728. }
  5729. /**
  5730. * Peeks for the next token.
  5731. * @returns {string|null} Token or `null` on eof
  5732. * @inner
  5733. */
  5734. function peek() {
  5735. if (!stack.length) {
  5736. var token = next();
  5737. if (token === null)
  5738. return null;
  5739. push(token);
  5740. }
  5741. return stack[0];
  5742. }
  5743. /**
  5744. * Skips a token.
  5745. * @param {string} expected Expected token
  5746. * @param {boolean} [optional=false] Whether the token is optional
  5747. * @returns {boolean} `true` when skipped, `false` if not
  5748. * @throws {Error} When a required token is not present
  5749. * @inner
  5750. */
  5751. function skip(expected, optional) {
  5752. var actual = peek(),
  5753. equals = actual === expected;
  5754. if (equals) {
  5755. next();
  5756. return true;
  5757. }
  5758. if (!optional)
  5759. throw illegal("token '" + actual + "', '" + expected + "' expected");
  5760. return false;
  5761. }
  5762. /**
  5763. * Gets a comment.
  5764. * @param {number} [trailingLine] Line number if looking for a trailing comment
  5765. * @returns {string|null} Comment text
  5766. * @inner
  5767. */
  5768. function cmnt(trailingLine) {
  5769. var ret = null;
  5770. var comment;
  5771. if (trailingLine === undefined) {
  5772. comment = comments[line - 1];
  5773. delete comments[line - 1];
  5774. if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) {
  5775. ret = comment.leading ? comment.text : null;
  5776. }
  5777. } else {
  5778. /* istanbul ignore else */
  5779. if (lastCommentLine < trailingLine) {
  5780. peek();
  5781. }
  5782. comment = comments[trailingLine];
  5783. delete comments[trailingLine];
  5784. if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) {
  5785. ret = comment.leading ? null : comment.text;
  5786. }
  5787. }
  5788. return ret;
  5789. }
  5790. return Object.defineProperty({
  5791. next: next,
  5792. peek: peek,
  5793. push: push,
  5794. skip: skip,
  5795. cmnt: cmnt
  5796. }, "line", {
  5797. get: function() { return line; }
  5798. });
  5799. /* eslint-enable callback-return */
  5800. }
  5801. },{}],26:[function(require,module,exports){
  5802. "use strict";
  5803. module.exports = Type;
  5804. // extends Namespace
  5805. var Namespace = require(14);
  5806. ((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type";
  5807. var Enum = require(6),
  5808. OneOf = require(16),
  5809. Field = require(7),
  5810. MapField = require(11),
  5811. Service = require(24),
  5812. Message = require(12),
  5813. Reader = require(18),
  5814. Writer = require(44),
  5815. util = require(28),
  5816. encoder = require(5),
  5817. decoder = require(4),
  5818. verifier = require(42),
  5819. converter = require(3),
  5820. wrappers = require(43);
  5821. /**
  5822. * Constructs a new reflected message type instance.
  5823. * @classdesc Reflected message type.
  5824. * @extends NamespaceBase
  5825. * @constructor
  5826. * @param {string} name Message name
  5827. * @param {Object.<string,*>} [options] Declared options
  5828. */
  5829. function Type(name, options) {
  5830. name = name.replace(/\W/g, "");
  5831. Namespace.call(this, name, options);
  5832. /**
  5833. * Message fields.
  5834. * @type {Object.<string,Field>}
  5835. */
  5836. this.fields = {}; // toJSON, marker
  5837. /**
  5838. * Oneofs declared within this namespace, if any.
  5839. * @type {Object.<string,OneOf>}
  5840. */
  5841. this.oneofs = undefined; // toJSON
  5842. /**
  5843. * Extension ranges, if any.
  5844. * @type {number[][]}
  5845. */
  5846. this.extensions = undefined; // toJSON
  5847. /**
  5848. * Reserved ranges, if any.
  5849. * @type {Array.<number[]|string>}
  5850. */
  5851. this.reserved = undefined; // toJSON
  5852. /*?
  5853. * Whether this type is a legacy group.
  5854. * @type {boolean|undefined}
  5855. */
  5856. this.group = undefined; // toJSON
  5857. /**
  5858. * Cached fields by id.
  5859. * @type {Object.<number,Field>|null}
  5860. * @private
  5861. */
  5862. this._fieldsById = null;
  5863. /**
  5864. * Cached fields as an array.
  5865. * @type {Field[]|null}
  5866. * @private
  5867. */
  5868. this._fieldsArray = null;
  5869. /**
  5870. * Cached oneofs as an array.
  5871. * @type {OneOf[]|null}
  5872. * @private
  5873. */
  5874. this._oneofsArray = null;
  5875. /**
  5876. * Cached constructor.
  5877. * @type {Constructor<{}>}
  5878. * @private
  5879. */
  5880. this._ctor = null;
  5881. /**
  5882. * Cached fields by JSON name.
  5883. * @type {Object.<string,Field>|null}
  5884. * @private
  5885. */
  5886. this._fieldsByJsonName = null; // used by ext/protojson
  5887. }
  5888. Object.defineProperties(Type.prototype, {
  5889. /**
  5890. * Message fields by id.
  5891. * @name Type#fieldsById
  5892. * @type {Object.<number,Field>}
  5893. * @readonly
  5894. */
  5895. fieldsById: {
  5896. get: function() {
  5897. /* istanbul ignore if */
  5898. if (this._fieldsById)
  5899. return this._fieldsById;
  5900. this._fieldsById = {};
  5901. for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {
  5902. var field = this.fields[names[i]],
  5903. id = field.id;
  5904. /* istanbul ignore if */
  5905. if (this._fieldsById[id])
  5906. throw Error("duplicate id " + id + " in " + this);
  5907. this._fieldsById[id] = field;
  5908. }
  5909. return this._fieldsById;
  5910. }
  5911. },
  5912. /**
  5913. * Fields of this message as an array for iteration.
  5914. * @name Type#fieldsArray
  5915. * @type {Field[]}
  5916. * @readonly
  5917. */
  5918. fieldsArray: {
  5919. get: function() {
  5920. return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));
  5921. }
  5922. },
  5923. /**
  5924. * Oneofs of this message as an array for iteration.
  5925. * @name Type#oneofsArray
  5926. * @type {OneOf[]}
  5927. * @readonly
  5928. */
  5929. oneofsArray: {
  5930. get: function() {
  5931. return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));
  5932. }
  5933. },
  5934. /**
  5935. * The registered constructor, if any registered, otherwise a generic constructor.
  5936. * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.
  5937. * When assigning manually, add the type to its parent namespace/root first if fields reference other reflected types, because constructor setup resolves field defaults.
  5938. * @name Type#ctor
  5939. * @type {Constructor<{}>}
  5940. */
  5941. ctor: {
  5942. get: function() {
  5943. return this._ctor || (this.ctor = Type.generateConstructor(this)());
  5944. },
  5945. set: function(ctor) {
  5946. // Ensure proper prototype
  5947. var prototype = ctor.prototype;
  5948. if (!(prototype instanceof Message)) {
  5949. (ctor.prototype = new Message()).constructor = ctor;
  5950. util.merge(ctor.prototype, prototype);
  5951. }
  5952. // Classes and messages reference their reflected type
  5953. ctor.$type = ctor.prototype.$type = this;
  5954. // Mix in static methods
  5955. util.merge(ctor, Message, true);
  5956. this._ctor = ctor;
  5957. delete this.decode;
  5958. delete this.fromObject;
  5959. // Messages have non-enumerable default values on their prototype
  5960. var i = 0;
  5961. for (var field; i < /* initializes */ this.fieldsArray.length; ++i) {
  5962. field = this._fieldsArray[i].resolve(); // ensures a proper value
  5963. ctor.prototype[field.name] = field.defaultValue;
  5964. }
  5965. // Messages have non-enumerable getters and setters for each virtual oneof field
  5966. var ctorProperties = {};
  5967. for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)
  5968. ctorProperties[this._oneofsArray[i].resolve().name] = {
  5969. get: util.oneOfGetter(this._oneofsArray[i].oneof),
  5970. set: util.oneOfSetter(this._oneofsArray[i].oneof)
  5971. };
  5972. if (i)
  5973. Object.defineProperties(ctor.prototype, ctorProperties);
  5974. }
  5975. }
  5976. });
  5977. /**
  5978. * Generates a constructor function for the specified type.
  5979. * @param {Type} mtype Message type
  5980. * @returns {Codegen} Codegen instance
  5981. */
  5982. Type.generateConstructor = function generateConstructor(mtype) {
  5983. /* eslint-disable no-unexpected-multiline */
  5984. var gen = util.codegen(["p"]);
  5985. // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype
  5986. for (var i = 0, field; i < mtype.fieldsArray.length; ++i)
  5987. if ((field = mtype._fieldsArray[i]).map) gen
  5988. ("this%s={}", util.safeProp(field.name));
  5989. else if (field.repeated) gen
  5990. ("this%s=[]", util.safeProp(field.name));
  5991. return gen
  5992. ("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null&&ks[i]!==\"__proto__\")") // omit undefined or null
  5993. ("this[ks[i]]=p[ks[i]]");
  5994. /* eslint-enable no-unexpected-multiline */
  5995. };
  5996. function clearCache(type) {
  5997. type._fieldsById = type._fieldsArray = type._oneofsArray = type._fieldsByJsonName = null;
  5998. delete type.encode;
  5999. delete type.decode;
  6000. delete type.verify;
  6001. return type;
  6002. }
  6003. /**
  6004. * Message type descriptor.
  6005. * @interface IType
  6006. * @extends INamespace
  6007. * @property {string} [edition] Edition
  6008. * @property {Object.<string,IOneOf>} [oneofs] Oneof descriptors
  6009. * @property {Object.<string,IField>} fields Field descriptors
  6010. * @property {number[][]} [extensions] Extension ranges
  6011. * @property {Array.<number[]|string>} [reserved] Reserved ranges
  6012. * @property {boolean} [group=false] Whether a legacy group or not
  6013. * @property {string|null} [comment] Message type comment
  6014. */
  6015. /**
  6016. * Creates a message type from a message type descriptor.
  6017. * @param {string} name Message name
  6018. * @param {IType} json Message type descriptor
  6019. * @param {number} [depth] Current nesting depth, defaults to `0`
  6020. * @returns {Type} Created message type
  6021. */
  6022. Type.fromJSON = function fromJSON(name, json, depth) {
  6023. if (depth === undefined)
  6024. depth = 0;
  6025. if (depth > util.nestingLimit)
  6026. throw Error("max depth exceeded");
  6027. var type = new Type(name, json.options);
  6028. type.extensions = json.extensions;
  6029. type.reserved = json.reserved;
  6030. var names = Object.keys(json.fields),
  6031. i = 0;
  6032. for (; i < names.length; ++i)
  6033. type.add(
  6034. ( typeof json.fields[names[i]].keyType !== "undefined"
  6035. ? MapField.fromJSON
  6036. : Field.fromJSON )(names[i], json.fields[names[i]])
  6037. );
  6038. if (json.oneofs)
  6039. for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)
  6040. type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));
  6041. if (json.nested)
  6042. for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {
  6043. var nested = json.nested[names[i]];
  6044. type.add( // most to least likely
  6045. ( nested.id !== undefined
  6046. ? Field.fromJSON
  6047. : nested.fields !== undefined
  6048. ? Type.fromJSON
  6049. : nested.values !== undefined
  6050. ? Enum.fromJSON
  6051. : nested.methods !== undefined
  6052. ? Service.fromJSON
  6053. : Namespace.fromJSON )(names[i], nested, depth + 1)
  6054. );
  6055. }
  6056. if (json.extensions && json.extensions.length)
  6057. type.extensions = json.extensions;
  6058. if (json.reserved && json.reserved.length)
  6059. type.reserved = json.reserved;
  6060. if (json.group)
  6061. type.group = true;
  6062. if (json.comment)
  6063. type.comment = json.comment;
  6064. if (json.edition)
  6065. type._edition = json.edition;
  6066. type._defaultEdition = "proto3"; // For backwards-compatibility.
  6067. return type;
  6068. };
  6069. /**
  6070. * Converts this message type to a message type descriptor.
  6071. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  6072. * @returns {IType} Message type descriptor
  6073. */
  6074. Type.prototype.toJSON = function toJSON(toJSONOptions) {
  6075. var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
  6076. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  6077. return util.toObject([
  6078. "edition" , this._editionToJSON(),
  6079. "options" , inherited && inherited.options || undefined,
  6080. "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),
  6081. "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},
  6082. "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined,
  6083. "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,
  6084. "group" , this.group || undefined,
  6085. "nested" , inherited && inherited.nested || undefined,
  6086. "comment" , keepComments ? this.comment : undefined
  6087. ]);
  6088. };
  6089. /**
  6090. * @override
  6091. */
  6092. Type.prototype.resolveAll = function resolveAll() {
  6093. if (!this._needsRecursiveResolve) return this;
  6094. Namespace.prototype.resolveAll.call(this);
  6095. var oneofs = this.oneofsArray; i = 0;
  6096. while (i < oneofs.length)
  6097. oneofs[i++].resolve();
  6098. var fields = this.fieldsArray, i = 0;
  6099. while (i < fields.length)
  6100. fields[i++].resolve();
  6101. return this;
  6102. };
  6103. /**
  6104. * @override
  6105. */
  6106. Type.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) {
  6107. if (!this._needsRecursiveFeatureResolution) return this;
  6108. edition = this._edition || edition;
  6109. Namespace.prototype._resolveFeaturesRecursive.call(this, edition);
  6110. this.oneofsArray.forEach(oneof => {
  6111. oneof._resolveFeatures(edition);
  6112. });
  6113. this.fieldsArray.forEach(field => {
  6114. field._resolveFeatures(edition);
  6115. });
  6116. return this;
  6117. };
  6118. /**
  6119. * @override
  6120. */
  6121. Type.prototype.get = function get(name) {
  6122. if (Object.prototype.hasOwnProperty.call(this.fields, name))
  6123. return this.fields[name];
  6124. if (this.oneofs && Object.prototype.hasOwnProperty.call(this.oneofs, name))
  6125. return this.oneofs[name];
  6126. if (this.nested && Object.prototype.hasOwnProperty.call(this.nested, name))
  6127. return this.nested[name];
  6128. return null;
  6129. };
  6130. /**
  6131. * Adds a nested object to this type.
  6132. * @param {ReflectionObject} object Nested object to add
  6133. * @returns {Type} `this`
  6134. * @throws {TypeError} If arguments are invalid
  6135. * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id
  6136. */
  6137. Type.prototype.add = function add(object) {
  6138. if (this.get(object.name))
  6139. throw Error("duplicate name '" + object.name + "' in " + this);
  6140. if (object instanceof Field && object.extend === undefined) {
  6141. // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.
  6142. // The root object takes care of adding distinct sister-fields to the respective extended
  6143. // type instead.
  6144. // avoids calling the getter if not absolutely necessary because it's called quite frequently
  6145. if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])
  6146. throw Error("duplicate id " + object.id + " in " + this);
  6147. if (this.isReservedId(object.id))
  6148. throw Error("id " + object.id + " is reserved in " + this);
  6149. if (this.isReservedName(object.name) || object.name.charAt(0) === "$")
  6150. throw Error("name '" + object.name + "' is reserved in " + this);
  6151. if (object.name === "__proto__")
  6152. return this;
  6153. if (object.parent)
  6154. object.parent.remove(object);
  6155. this.fields[object.name] = object;
  6156. object.message = this;
  6157. object.onAdd(this);
  6158. return clearCache(this);
  6159. }
  6160. if (object instanceof OneOf) {
  6161. if (object.name.charAt(0) === "$")
  6162. throw Error("name '" + object.name + "' is reserved in " + this);
  6163. if (object.name === "__proto__")
  6164. return this;
  6165. if (!this.oneofs)
  6166. this.oneofs = {};
  6167. this.oneofs[object.name] = object;
  6168. object.onAdd(this);
  6169. return clearCache(this);
  6170. }
  6171. return Namespace.prototype.add.call(this, object);
  6172. };
  6173. /**
  6174. * Removes a nested object from this type.
  6175. * @param {ReflectionObject} object Nested object to remove
  6176. * @returns {Type} `this`
  6177. * @throws {TypeError} If arguments are invalid
  6178. * @throws {Error} If `object` is not a member of this type
  6179. */
  6180. Type.prototype.remove = function remove(object) {
  6181. if (object instanceof Field && object.extend === undefined) {
  6182. // See Type#add for the reason why extension fields are excluded here.
  6183. /* istanbul ignore if */
  6184. if (!util.remove(this.fields, object, object.name))
  6185. throw Error(object + " is not a member of " + this);
  6186. object.parent = null;
  6187. object.onRemove(this);
  6188. return clearCache(this);
  6189. }
  6190. if (object instanceof OneOf) {
  6191. /* istanbul ignore if */
  6192. if (!util.remove(this.oneofs, object, object.name))
  6193. throw Error(object + " is not a member of " + this);
  6194. object.parent = null;
  6195. object.onRemove(this);
  6196. return clearCache(this);
  6197. }
  6198. return Namespace.prototype.remove.call(this, object);
  6199. };
  6200. /**
  6201. * Tests if the specified id is reserved.
  6202. * @param {number} id Id to test
  6203. * @returns {boolean} `true` if reserved, otherwise `false`
  6204. */
  6205. Type.prototype.isReservedId = function isReservedId(id) {
  6206. return Namespace.isReservedId(this.reserved, id);
  6207. };
  6208. /**
  6209. * Tests if the specified name is reserved.
  6210. * @param {string} name Name to test
  6211. * @returns {boolean} `true` if reserved, otherwise `false`
  6212. */
  6213. Type.prototype.isReservedName = function isReservedName(name) {
  6214. return Namespace.isReservedName(this.reserved, name);
  6215. };
  6216. /**
  6217. * Creates a new message of this type using the specified properties.
  6218. * @param {Object.<string,*>} [properties] Properties to set
  6219. * @returns {ReflectedMessage} Message instance
  6220. */
  6221. Type.prototype.create = function create(properties) {
  6222. return new this.ctor(properties);
  6223. };
  6224. /**
  6225. * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.
  6226. * @returns {Type} `this`
  6227. */
  6228. Type.prototype.setup = function setup() {
  6229. // Sets up everything at once so that the prototype chain does not have to be re-evaluated
  6230. // multiple times (V8, soft-deopt prototype-check).
  6231. var fullName = this.fullName,
  6232. types = [];
  6233. for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)
  6234. types.push(this._fieldsArray[i].resolve().resolvedType);
  6235. // Replace setup methods with type-specific generated functions
  6236. this.encode = encoder(this)({
  6237. Writer : Writer,
  6238. types : types,
  6239. util : util
  6240. });
  6241. this.decode = decoder(this)({
  6242. Reader : Reader,
  6243. types : types,
  6244. util : util,
  6245. C : this.ctor
  6246. });
  6247. this.verify = verifier(this)({
  6248. types : types,
  6249. util : util
  6250. });
  6251. this.fromObject = converter.fromObject(this)({
  6252. types : types,
  6253. util : util,
  6254. C : this.ctor
  6255. });
  6256. this.toObject = converter.toObject(this)({
  6257. types : types,
  6258. util : util
  6259. });
  6260. // Inject custom wrappers for common types
  6261. var wrapper = wrappers[fullName];
  6262. if (wrapper) {
  6263. var wrapperThis = Object.create(this);
  6264. // Reuse this type's runtime constructor in wrapper fromObject/toObject
  6265. wrapperThis._ctor = this.ctor;
  6266. wrapperThis.fromObject = this.fromObject;
  6267. this.fromObject = wrapper.fromObject.bind(wrapperThis);
  6268. wrapperThis.toObject = this.toObject;
  6269. this.toObject = wrapper.toObject.bind(wrapperThis);
  6270. }
  6271. return this;
  6272. };
  6273. /**
  6274. * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.
  6275. * @param {Message<{}>|Object.<string,*>} message Message instance or plain object
  6276. * @param {Writer} [writer] Writer to encode to
  6277. * @returns {Writer} writer
  6278. */
  6279. Type.prototype.encode = function encode_setup(message, writer) { // eslint-disable-line no-unused-vars
  6280. return this.setup().encode.apply(this, arguments); // overrides this method
  6281. };
  6282. /**
  6283. * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.
  6284. * @param {Message<{}>|Object.<string,*>} message Message instance or plain object
  6285. * @param {Writer} [writer] Writer to encode to
  6286. * @returns {Writer} writer
  6287. */
  6288. Type.prototype.encodeDelimited = function encodeDelimited(message, writer) {
  6289. return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();
  6290. };
  6291. /**
  6292. * Decodes a message of this type.
  6293. * @param {Reader|Uint8Array} reader Reader or buffer to decode from
  6294. * @param {number} [length] Length of the message, if known beforehand
  6295. * @returns {ReflectedMessage} Decoded message
  6296. * @throws {Error} If the payload is not a reader or valid buffer
  6297. * @throws {util.ProtocolError<{}>} If required fields are missing
  6298. */
  6299. Type.prototype.decode = function decode_setup(reader, length) { // eslint-disable-line no-unused-vars
  6300. return this.setup().decode.apply(this, arguments); // overrides this method
  6301. };
  6302. /**
  6303. * Decodes a message of this type preceeded by its byte length as a varint.
  6304. * @param {Reader|Uint8Array} reader Reader or buffer to decode from
  6305. * @returns {ReflectedMessage} Decoded message
  6306. * @throws {Error} If the payload is not a reader or valid buffer
  6307. * @throws {util.ProtocolError} If required fields are missing
  6308. */
  6309. Type.prototype.decodeDelimited = function decodeDelimited(reader) {
  6310. if (!(reader instanceof Reader))
  6311. reader = Reader.create(reader);
  6312. return this.decode(reader, reader.uint32());
  6313. };
  6314. /**
  6315. * Verifies that field values are valid and that required fields are present.
  6316. * @param {Object.<string,*>} message Plain object to verify
  6317. * @returns {null|string} `null` if valid, otherwise the reason why it is not
  6318. */
  6319. Type.prototype.verify = function verify_setup(message) { // eslint-disable-line no-unused-vars
  6320. return this.setup().verify.apply(this, arguments); // overrides this method
  6321. };
  6322. /**
  6323. * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
  6324. * @param {Object.<string,*>} object Plain object to convert
  6325. * @returns {ReflectedMessage} Message instance
  6326. */
  6327. Type.prototype.fromObject = function fromObject(object) { // eslint-disable-line no-unused-vars
  6328. return this.setup().fromObject.apply(this, arguments);
  6329. };
  6330. /**
  6331. * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.
  6332. * @interface IConversionOptions
  6333. * @property {Function} [longs] Long conversion type.
  6334. * Valid values are `BigInt`, `String` and `Number` (the global types).
  6335. * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.
  6336. * @property {Function} [enums] Enum value conversion type.
  6337. * Only valid value is `String` (the global type).
  6338. * Defaults to copy the present value, which is the numeric id.
  6339. * @property {Function} [bytes] Bytes value conversion type.
  6340. * Valid values are `Array` and (a base64 encoded) `String` (the global types).
  6341. * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.
  6342. * @property {boolean} [defaults=false] Also sets default values on the resulting object
  6343. * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`
  6344. * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`
  6345. * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any
  6346. * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings
  6347. */
  6348. /**
  6349. * Creates a plain object from a message of this type. Also converts values to other types if specified.
  6350. * @param {Message<{}>} message Message instance
  6351. * @param {IConversionOptions} [options] Conversion options
  6352. * @returns {Object.<string,*>} Plain object
  6353. */
  6354. Type.prototype.toObject = function toObject(message, options) { // eslint-disable-line no-unused-vars
  6355. return this.setup().toObject.apply(this, arguments);
  6356. };
  6357. /**
  6358. * Gets the type url for this type.
  6359. * @param {string} [prefix] Custom type url prefix, defaults to `"type.googleapis.com"`
  6360. * @returns {string} The type url
  6361. */
  6362. Type.prototype.getTypeUrl = function getTypeUrl(prefix) {
  6363. if (prefix === undefined)
  6364. prefix = "type.googleapis.com";
  6365. var fullName = this.fullName;
  6366. return prefix + "/" + (fullName.charAt(0) === "." ? fullName.substring(1) : fullName);
  6367. };
  6368. /**
  6369. * Decorator function as returned by {@link Type.d} (TypeScript).
  6370. * @typedef TypeDecorator
  6371. * @type {function}
  6372. * @param {Constructor<T>} target Target constructor
  6373. * @returns {undefined}
  6374. * @template T extends Message<T>
  6375. * @deprecated Legacy TypeScript decorator support. Will be removed in a future release.
  6376. */
  6377. /**
  6378. * Type decorator (TypeScript).
  6379. * @param {string} [typeName] Type name, defaults to the constructor's name
  6380. * @returns {TypeDecorator<T>} Decorator function
  6381. * @template T extends Message<T>
  6382. * @deprecated Legacy TypeScript decorator support. Will be removed in a future release.
  6383. */
  6384. Type.d = function decorateType(typeName) {
  6385. return function typeDecorator(target) {
  6386. util.decorateType(target, typeName);
  6387. };
  6388. };
  6389. },{"11":11,"12":12,"14":14,"16":16,"18":18,"24":24,"28":28,"3":3,"4":4,"42":42,"43":43,"44":44,"5":5,"6":6,"7":7}],27:[function(require,module,exports){
  6390. "use strict";
  6391. /**
  6392. * Common type constants.
  6393. * @namespace
  6394. */
  6395. var types = exports;
  6396. var util = require(28);
  6397. var s = [
  6398. "double", // 0
  6399. "float", // 1
  6400. "int32", // 2
  6401. "uint32", // 3
  6402. "sint32", // 4
  6403. "fixed32", // 5
  6404. "sfixed32", // 6
  6405. "int64", // 7
  6406. "uint64", // 8
  6407. "sint64", // 9
  6408. "fixed64", // 10
  6409. "sfixed64", // 11
  6410. "bool", // 12
  6411. "string", // 13
  6412. "bytes" // 14
  6413. ];
  6414. function bake(values, offset) {
  6415. var i = 0, o = Object.create(null);
  6416. offset |= 0;
  6417. while (i < values.length) o[s[i + offset]] = values[i++];
  6418. return o;
  6419. }
  6420. /**
  6421. * Basic type wire types.
  6422. * @type {Object.<string,number>}
  6423. * @const
  6424. * @property {number} double=1 Fixed64 wire type
  6425. * @property {number} float=5 Fixed32 wire type
  6426. * @property {number} int32=0 Varint wire type
  6427. * @property {number} uint32=0 Varint wire type
  6428. * @property {number} sint32=0 Varint wire type
  6429. * @property {number} fixed32=5 Fixed32 wire type
  6430. * @property {number} sfixed32=5 Fixed32 wire type
  6431. * @property {number} int64=0 Varint wire type
  6432. * @property {number} uint64=0 Varint wire type
  6433. * @property {number} sint64=0 Varint wire type
  6434. * @property {number} fixed64=1 Fixed64 wire type
  6435. * @property {number} sfixed64=1 Fixed64 wire type
  6436. * @property {number} bool=0 Varint wire type
  6437. * @property {number} string=2 Ldelim wire type
  6438. * @property {number} bytes=2 Ldelim wire type
  6439. */
  6440. types.basic = bake([
  6441. /* double */ 1,
  6442. /* float */ 5,
  6443. /* int32 */ 0,
  6444. /* uint32 */ 0,
  6445. /* sint32 */ 0,
  6446. /* fixed32 */ 5,
  6447. /* sfixed32 */ 5,
  6448. /* int64 */ 0,
  6449. /* uint64 */ 0,
  6450. /* sint64 */ 0,
  6451. /* fixed64 */ 1,
  6452. /* sfixed64 */ 1,
  6453. /* bool */ 0,
  6454. /* string */ 2,
  6455. /* bytes */ 2
  6456. ]);
  6457. /**
  6458. * Basic type defaults.
  6459. * @type {Object.<string,*>}
  6460. * @const
  6461. * @property {number} double=0 Double default
  6462. * @property {number} float=0 Float default
  6463. * @property {number} int32=0 Int32 default
  6464. * @property {number} uint32=0 Uint32 default
  6465. * @property {number} sint32=0 Sint32 default
  6466. * @property {number} fixed32=0 Fixed32 default
  6467. * @property {number} sfixed32=0 Sfixed32 default
  6468. * @property {number} int64=0 Int64 default
  6469. * @property {number} uint64=0 Uint64 default
  6470. * @property {number} sint64=0 Sint32 default
  6471. * @property {number} fixed64=0 Fixed64 default
  6472. * @property {number} sfixed64=0 Sfixed64 default
  6473. * @property {boolean} bool=false Bool default
  6474. * @property {string} string="" String default
  6475. * @property {Array.<number>} bytes=Array(0) Bytes default
  6476. * @property {null} message=null Message default
  6477. */
  6478. types.defaults = bake([
  6479. /* double */ 0,
  6480. /* float */ 0,
  6481. /* int32 */ 0,
  6482. /* uint32 */ 0,
  6483. /* sint32 */ 0,
  6484. /* fixed32 */ 0,
  6485. /* sfixed32 */ 0,
  6486. /* int64 */ 0,
  6487. /* uint64 */ 0,
  6488. /* sint64 */ 0,
  6489. /* fixed64 */ 0,
  6490. /* sfixed64 */ 0,
  6491. /* bool */ false,
  6492. /* string */ "",
  6493. /* bytes */ util.emptyArray,
  6494. /* message */ null
  6495. ]);
  6496. /**
  6497. * Basic long type wire types.
  6498. * @type {Object.<string,number>}
  6499. * @const
  6500. * @property {number} int64=0 Varint wire type
  6501. * @property {number} uint64=0 Varint wire type
  6502. * @property {number} sint64=0 Varint wire type
  6503. * @property {number} fixed64=1 Fixed64 wire type
  6504. * @property {number} sfixed64=1 Fixed64 wire type
  6505. */
  6506. types.long = bake([
  6507. /* int64 */ 0,
  6508. /* uint64 */ 0,
  6509. /* sint64 */ 0,
  6510. /* fixed64 */ 1,
  6511. /* sfixed64 */ 1
  6512. ], 7);
  6513. /**
  6514. * Allowed types for map keys with their associated wire type.
  6515. * @type {Object.<string,number>}
  6516. * @const
  6517. * @property {number} int32=0 Varint wire type
  6518. * @property {number} uint32=0 Varint wire type
  6519. * @property {number} sint32=0 Varint wire type
  6520. * @property {number} fixed32=5 Fixed32 wire type
  6521. * @property {number} sfixed32=5 Fixed32 wire type
  6522. * @property {number} int64=0 Varint wire type
  6523. * @property {number} uint64=0 Varint wire type
  6524. * @property {number} sint64=0 Varint wire type
  6525. * @property {number} fixed64=1 Fixed64 wire type
  6526. * @property {number} sfixed64=1 Fixed64 wire type
  6527. * @property {number} bool=0 Varint wire type
  6528. * @property {number} string=2 Ldelim wire type
  6529. */
  6530. types.mapKey = bake([
  6531. /* int32 */ 0,
  6532. /* uint32 */ 0,
  6533. /* sint32 */ 0,
  6534. /* fixed32 */ 5,
  6535. /* sfixed32 */ 5,
  6536. /* int64 */ 0,
  6537. /* uint64 */ 0,
  6538. /* sint64 */ 0,
  6539. /* fixed64 */ 1,
  6540. /* sfixed64 */ 1,
  6541. /* bool */ 0,
  6542. /* string */ 2
  6543. ], 2);
  6544. /**
  6545. * Allowed types for packed repeated fields with their associated wire type.
  6546. * @type {Object.<string,number>}
  6547. * @const
  6548. * @property {number} double=1 Fixed64 wire type
  6549. * @property {number} float=5 Fixed32 wire type
  6550. * @property {number} int32=0 Varint wire type
  6551. * @property {number} uint32=0 Varint wire type
  6552. * @property {number} sint32=0 Varint wire type
  6553. * @property {number} fixed32=5 Fixed32 wire type
  6554. * @property {number} sfixed32=5 Fixed32 wire type
  6555. * @property {number} int64=0 Varint wire type
  6556. * @property {number} uint64=0 Varint wire type
  6557. * @property {number} sint64=0 Varint wire type
  6558. * @property {number} fixed64=1 Fixed64 wire type
  6559. * @property {number} sfixed64=1 Fixed64 wire type
  6560. * @property {number} bool=0 Varint wire type
  6561. */
  6562. types.packed = bake([
  6563. /* double */ 1,
  6564. /* float */ 5,
  6565. /* int32 */ 0,
  6566. /* uint32 */ 0,
  6567. /* sint32 */ 0,
  6568. /* fixed32 */ 5,
  6569. /* sfixed32 */ 5,
  6570. /* int64 */ 0,
  6571. /* uint64 */ 0,
  6572. /* sint64 */ 0,
  6573. /* fixed64 */ 1,
  6574. /* sfixed64 */ 1,
  6575. /* bool */ 0
  6576. ]);
  6577. },{"28":28}],28:[function(require,module,exports){
  6578. "use strict";
  6579. /**
  6580. * Various utility functions.
  6581. * @namespace
  6582. */
  6583. var util = module.exports = require(37);
  6584. var roots = require(21);
  6585. var Type, // cyclic
  6586. Enum;
  6587. util.codegen = require(31);
  6588. util.fetch = require(33);
  6589. util.path = require(38);
  6590. util.patterns = require(39);
  6591. var reservedRe = util.patterns.reservedRe;
  6592. /**
  6593. * Node's fs module if available.
  6594. * @type {Object.<string,*>}
  6595. */
  6596. util.fs = require(35);
  6597. /**
  6598. * Converts an object's values to an array.
  6599. * @param {Object.<string,*>} object Object to convert
  6600. * @returns {Array.<*>} Converted array
  6601. */
  6602. util.toArray = function toArray(object) {
  6603. if (object) {
  6604. var keys = Object.keys(object),
  6605. array = new Array(keys.length),
  6606. index = 0;
  6607. while (index < keys.length)
  6608. array[index] = object[keys[index++]];
  6609. return array;
  6610. }
  6611. return [];
  6612. };
  6613. /**
  6614. * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.
  6615. * @param {Array.<*>} array Array to convert
  6616. * @returns {Object.<string,*>} Converted object
  6617. */
  6618. util.toObject = function toObject(array) {
  6619. var object = {},
  6620. index = 0;
  6621. while (index < array.length) {
  6622. var key = array[index++],
  6623. val = array[index++];
  6624. if (val !== undefined)
  6625. object[key] = val;
  6626. }
  6627. return object;
  6628. };
  6629. /**
  6630. * Removes the first matching value from an object.
  6631. * @param {Object.<string,*>|undefined} object Object to remove from
  6632. * @param {*} value Value to remove
  6633. * @param {string} [key] Optional key for fast path removal
  6634. * @returns {boolean} `true` if removed, otherwise `false`
  6635. */
  6636. util.remove = function remove(object, value, key) {
  6637. if (!object)
  6638. return false;
  6639. if (key !== undefined && Object.prototype.hasOwnProperty.call(object, key) && object[key] === value) {
  6640. delete object[key];
  6641. return true;
  6642. }
  6643. for (var names = Object.keys(object), i = 0; i < names.length; ++i)
  6644. if (object[names[i]] === value) {
  6645. delete object[names[i]];
  6646. return true;
  6647. }
  6648. return false;
  6649. };
  6650. /**
  6651. * Tests whether the specified name is a reserved word in JS.
  6652. * @param {string} name Name to test
  6653. * @returns {boolean} `true` if reserved, otherwise `false`
  6654. */
  6655. util.isReserved = function isReserved(name) {
  6656. return reservedRe.test(name);
  6657. };
  6658. /**
  6659. * Returns a safe property accessor for the specified property name.
  6660. * @param {string} prop Property name
  6661. * @returns {string} Safe accessor
  6662. */
  6663. util.safeProp = function safeProp(prop) {
  6664. if (!/^[$\w_]+$/.test(prop) || reservedRe.test(prop))
  6665. return "[" + JSON.stringify(prop) + "]";
  6666. return "." + prop;
  6667. };
  6668. /**
  6669. * Converts the first character of a string to upper case.
  6670. * @param {string} str String to convert
  6671. * @returns {string} Converted string
  6672. */
  6673. util.ucFirst = function ucFirst(str) {
  6674. return str.charAt(0).toUpperCase() + str.substring(1);
  6675. };
  6676. var camelCaseRe = /_([a-z])/g;
  6677. /**
  6678. * Converts a string to camel case.
  6679. * @param {string} str String to convert
  6680. * @returns {string} Converted string
  6681. * @deprecated Use {@link util.jsonName} for protobuf field JSON names.
  6682. */
  6683. util.camelCase = function camelCase(str) {
  6684. return str.substring(0, 1)
  6685. + str.substring(1)
  6686. .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });
  6687. };
  6688. /**
  6689. * Converts a proto field name to its protoc-compatible JSON name.
  6690. * @param {string} str Proto field name
  6691. * @returns {string} JSON name
  6692. */
  6693. util.jsonName = function jsonName(str) {
  6694. var result = "",
  6695. upperNext = false,
  6696. i = 0;
  6697. for (; i < str.length; ++i) {
  6698. var ch = str.charAt(i);
  6699. if (ch === "_")
  6700. upperNext = true;
  6701. else if (upperNext) {
  6702. result += ch.toUpperCase();
  6703. upperNext = false;
  6704. } else
  6705. result += ch;
  6706. }
  6707. return result;
  6708. };
  6709. /**
  6710. * Compares reflected fields by id.
  6711. * @param {Field} a First field
  6712. * @param {Field} b Second field
  6713. * @returns {number} Comparison value
  6714. */
  6715. util.compareFieldsById = function compareFieldsById(a, b) {
  6716. return a.id - b.id;
  6717. };
  6718. /**
  6719. * Decorator helper for types (TypeScript).
  6720. * @param {Constructor<T>} ctor Constructor function
  6721. * @param {string} [typeName] Type name, defaults to the constructor's name
  6722. * @returns {Type} Reflected type
  6723. * @template T extends Message<T>
  6724. * @property {Root} root Decorators root
  6725. * @deprecated Legacy TypeScript decorator support. Will be removed in a future release.
  6726. */
  6727. util.decorateType = function decorateType(ctor, typeName) {
  6728. /* istanbul ignore if */
  6729. if (ctor.$type) {
  6730. if (typeName && ctor.$type.name !== typeName) {
  6731. util.decorateRoot.remove(ctor.$type);
  6732. ctor.$type.name = typeName;
  6733. util.decorateRoot.add(ctor.$type);
  6734. }
  6735. return ctor.$type;
  6736. }
  6737. /* istanbul ignore next */
  6738. if (!Type)
  6739. Type = require(26);
  6740. var type = new Type(typeName || ctor.name);
  6741. util.decorateRoot.add(type);
  6742. type.ctor = ctor; // sets up .encode, .decode etc.
  6743. Object.defineProperty(ctor, "$type", { value: type, enumerable: false });
  6744. Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false });
  6745. return type;
  6746. };
  6747. var decorateEnumIndex = 0;
  6748. /**
  6749. * Decorator helper for enums (TypeScript).
  6750. * @param {Object} object Enum object
  6751. * @returns {Enum} Reflected enum
  6752. * @deprecated Legacy TypeScript decorator support. Will be removed in a future release.
  6753. */
  6754. util.decorateEnum = function decorateEnum(object) {
  6755. /* istanbul ignore if */
  6756. if (object.$type)
  6757. return object.$type;
  6758. /* istanbul ignore next */
  6759. if (!Enum)
  6760. Enum = require(6);
  6761. var enm = new Enum("Enum" + decorateEnumIndex++, object);
  6762. util.decorateRoot.add(enm);
  6763. Object.defineProperty(object, "$type", { value: enm, enumerable: false });
  6764. return enm;
  6765. };
  6766. /**
  6767. * Sets the value of a property by property path. If a value already exists, it is turned to an array
  6768. * @param {Object.<string,*>} dst Destination object
  6769. * @param {string} path dot '.' delimited path of the property to set
  6770. * @param {Object} value the value to set
  6771. * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set
  6772. * @returns {Object.<string,*>} Destination object
  6773. */
  6774. util.setProperty = function setProperty(dst, path, value, ifNotSet) {
  6775. function setProp(dst, path, value) {
  6776. var part = path.shift();
  6777. if (util.isUnsafeProperty(part))
  6778. return dst;
  6779. if (path.length > 0) {
  6780. dst[part] = setProp(dst[part] || {}, path, value);
  6781. } else {
  6782. var prevValue = dst[part];
  6783. if (prevValue && ifNotSet)
  6784. return dst;
  6785. if (prevValue)
  6786. value = [].concat(prevValue).concat(value);
  6787. dst[part] = value;
  6788. }
  6789. return dst;
  6790. }
  6791. if (typeof dst !== "object")
  6792. throw TypeError("dst must be an object");
  6793. if (!path)
  6794. throw TypeError("path must be specified");
  6795. path = path.split(".");
  6796. if (path.length > util.recursionLimit)
  6797. throw Error("max depth exceeded");
  6798. return setProp(dst, path, value);
  6799. };
  6800. /**
  6801. * Decorator root (TypeScript).
  6802. * @name util.decorateRoot
  6803. * @type {Root}
  6804. * @readonly
  6805. * @deprecated Legacy TypeScript decorator support. Will be removed in a future release.
  6806. */
  6807. Object.defineProperty(util, "decorateRoot", {
  6808. get: function() {
  6809. return roots["decorated"] || (roots["decorated"] = new (require(20))());
  6810. }
  6811. });
  6812. },{"20":20,"21":21,"26":26,"31":31,"33":33,"35":35,"37":37,"38":38,"39":39,"6":6}],29:[function(require,module,exports){
  6813. "use strict";
  6814. module.exports = asPromise;
  6815. /**
  6816. * Callback as used by {@link util.asPromise}.
  6817. * @typedef asPromiseCallback
  6818. * @type {function}
  6819. * @param {Error|null} error Error, if any
  6820. * @param {...*} params Additional arguments
  6821. * @returns {undefined}
  6822. */
  6823. /**
  6824. * Returns a promise from a node-style callback function.
  6825. * @memberof util
  6826. * @param {asPromiseCallback} fn Function to call
  6827. * @param {*} ctx Function context
  6828. * @param {...*} params Function arguments
  6829. * @returns {Promise<*>} Promisified function
  6830. */
  6831. function asPromise(fn, ctx/*, varargs */) {
  6832. var params = new Array(arguments.length - 1),
  6833. offset = 0,
  6834. index = 2,
  6835. pending = true;
  6836. while (index < arguments.length)
  6837. params[offset++] = arguments[index++];
  6838. return new Promise(function executor(resolve, reject) {
  6839. params[offset] = function callback(err/*, varargs */) {
  6840. if (pending) {
  6841. pending = false;
  6842. if (err)
  6843. reject(err);
  6844. else {
  6845. var params = new Array(arguments.length - 1),
  6846. offset = 0;
  6847. while (offset < params.length)
  6848. params[offset++] = arguments[offset];
  6849. resolve.apply(null, params);
  6850. }
  6851. }
  6852. };
  6853. try {
  6854. fn.apply(ctx || null, params);
  6855. } catch (err) {
  6856. if (pending) {
  6857. pending = false;
  6858. reject(err);
  6859. }
  6860. }
  6861. });
  6862. }
  6863. },{}],30:[function(require,module,exports){
  6864. "use strict";
  6865. /**
  6866. * A minimal base64 implementation for number arrays.
  6867. * @memberof util
  6868. * @namespace
  6869. */
  6870. var base64 = exports;
  6871. /**
  6872. * Calculates the byte length of a base64 encoded string.
  6873. * @param {string} string Base64 encoded string
  6874. * @returns {number} Byte length
  6875. */
  6876. base64.length = function length(string) {
  6877. var p = string.length;
  6878. if (!p)
  6879. return 0;
  6880. while (p > 0 && string.charAt(p - 1) === "=")
  6881. --p;
  6882. return Math.floor(p * 3 / 4);
  6883. };
  6884. // Base64 encoding table
  6885. var b64 = new Array(64);
  6886. // Base64 decoding table
  6887. var s64 = new Array(123);
  6888. // 65..90, 97..122, 48..57, 43, 47
  6889. for (var i = 0; i < 64;)
  6890. s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
  6891. s64[45] = 62; // - -> +
  6892. s64[95] = 63; // _ -> /
  6893. /**
  6894. * Encodes a buffer to a base64 encoded string.
  6895. * @param {Uint8Array} buffer Source buffer
  6896. * @param {number} start Source start
  6897. * @param {number} end Source end
  6898. * @returns {string} Base64 encoded string
  6899. */
  6900. base64.encode = function encode(buffer, start, end) {
  6901. var parts = null,
  6902. chunk = [];
  6903. var i = 0, // output index
  6904. j = 0, // goto index
  6905. t; // temporary
  6906. while (start < end) {
  6907. var b = buffer[start++];
  6908. switch (j) {
  6909. case 0:
  6910. chunk[i++] = b64[b >> 2];
  6911. t = (b & 3) << 4;
  6912. j = 1;
  6913. break;
  6914. case 1:
  6915. chunk[i++] = b64[t | b >> 4];
  6916. t = (b & 15) << 2;
  6917. j = 2;
  6918. break;
  6919. case 2:
  6920. chunk[i++] = b64[t | b >> 6];
  6921. chunk[i++] = b64[b & 63];
  6922. j = 0;
  6923. break;
  6924. }
  6925. if (i > 8191) {
  6926. (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
  6927. i = 0;
  6928. }
  6929. }
  6930. if (j) {
  6931. chunk[i++] = b64[t];
  6932. chunk[i++] = 61;
  6933. if (j === 1)
  6934. chunk[i++] = 61;
  6935. }
  6936. if (parts) {
  6937. if (i)
  6938. parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
  6939. return parts.join("");
  6940. }
  6941. return String.fromCharCode.apply(String, chunk.slice(0, i));
  6942. };
  6943. var invalidEncoding = "invalid encoding";
  6944. /**
  6945. * Decodes a base64 encoded string to a buffer.
  6946. * @param {string} string Source string
  6947. * @param {Uint8Array} buffer Destination buffer
  6948. * @param {number} offset Destination offset
  6949. * @returns {number} Number of bytes written
  6950. * @throws {Error} If encoding is invalid
  6951. */
  6952. base64.decode = function decode(string, buffer, offset) {
  6953. var start = offset;
  6954. var j = 0, // goto index
  6955. t; // temporary
  6956. for (var i = 0; i < string.length;) {
  6957. var c = string.charCodeAt(i++);
  6958. if (c === 61 && j > 1)
  6959. break;
  6960. if ((c = s64[c]) === undefined)
  6961. throw Error(invalidEncoding);
  6962. switch (j) {
  6963. case 0:
  6964. t = c;
  6965. j = 1;
  6966. break;
  6967. case 1:
  6968. buffer[offset++] = t << 2 | (c & 48) >> 4;
  6969. t = c;
  6970. j = 2;
  6971. break;
  6972. case 2:
  6973. buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
  6974. t = c;
  6975. j = 3;
  6976. break;
  6977. case 3:
  6978. buffer[offset++] = (t & 3) << 6 | c;
  6979. j = 0;
  6980. break;
  6981. }
  6982. }
  6983. if (j === 1)
  6984. throw Error(invalidEncoding);
  6985. return offset - start;
  6986. };
  6987. var base64Re = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,
  6988. base64UrlRe = /[-_]/,
  6989. base64UrlNoPaddingRe = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2}(?:==)?|[A-Za-z0-9_-]{3}=?)?$/;
  6990. /**
  6991. * Tests if the specified string appears to be base64 encoded.
  6992. * @param {string} string String to test
  6993. * @returns {boolean} `true` if probably base64 encoded, otherwise false
  6994. */
  6995. base64.test = function test(string) {
  6996. return base64Re.test(string)
  6997. || base64UrlRe.test(string) && base64UrlNoPaddingRe.test(string);
  6998. };
  6999. },{}],31:[function(require,module,exports){
  7000. "use strict";
  7001. module.exports = codegen;
  7002. var patterns = require(39);
  7003. var reservedRe = patterns.reservedRe;
  7004. /**
  7005. * Begins generating a function.
  7006. * @memberof util
  7007. * @param {string[]} functionParams Function parameter names
  7008. * @param {string} [functionName] Function name if not anonymous
  7009. * @returns {Codegen} Appender that appends code to the function's body
  7010. */
  7011. function codegen(functionParams, functionName) {
  7012. /* istanbul ignore if */
  7013. if (typeof functionParams === "string") {
  7014. functionName = functionParams;
  7015. functionParams = undefined;
  7016. }
  7017. var body = [];
  7018. /**
  7019. * Appends code to the function's body or finishes generation.
  7020. * @typedef Codegen
  7021. * @type {function}
  7022. * @param {string|Object.<string,*>} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any
  7023. * @param {...*} [formatParams] Format parameters
  7024. * @returns {Codegen|Function} Itself or the generated function if finished
  7025. * @throws {Error} If format parameter counts do not match
  7026. */
  7027. function Codegen(formatStringOrScope) {
  7028. // note that explicit array handling below makes this ~50% faster
  7029. // finish the function
  7030. if (typeof formatStringOrScope !== "string") {
  7031. var source = toString();
  7032. if (codegen.verbose)
  7033. console.log("codegen: " + source); // eslint-disable-line no-console
  7034. source = "return " + source;
  7035. if (formatStringOrScope) {
  7036. var scopeKeys = Object.keys(formatStringOrScope),
  7037. scopeParams = new Array(scopeKeys.length + 1),
  7038. scopeValues = new Array(scopeKeys.length),
  7039. scopeOffset = 0;
  7040. while (scopeOffset < scopeKeys.length) {
  7041. scopeParams[scopeOffset] = scopeKeys[scopeOffset];
  7042. scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];
  7043. }
  7044. scopeParams[scopeOffset] = source;
  7045. return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func
  7046. }
  7047. return Function(source)(); // eslint-disable-line no-new-func
  7048. }
  7049. // otherwise append to body
  7050. var formatParams = new Array(arguments.length - 1),
  7051. formatOffset = 0;
  7052. while (formatOffset < formatParams.length)
  7053. formatParams[formatOffset] = arguments[++formatOffset];
  7054. formatOffset = 0;
  7055. formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {
  7056. var value = formatParams[formatOffset++];
  7057. switch ($1) {
  7058. case "d": case "f": return String(Number(value));
  7059. case "i": return String(Math.floor(value));
  7060. case "j": return JSON.stringify(value);
  7061. case "s": return String(value);
  7062. }
  7063. return "%";
  7064. });
  7065. if (formatOffset !== formatParams.length)
  7066. throw Error("parameter count mismatch");
  7067. body.push(formatStringOrScope);
  7068. return Codegen;
  7069. }
  7070. function toString(functionNameOverride) {
  7071. return "function " + safeFunctionName(functionNameOverride || functionName) + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}";
  7072. }
  7073. Codegen.toString = toString;
  7074. return Codegen;
  7075. }
  7076. /**
  7077. * Begins generating a function.
  7078. * @memberof util
  7079. * @function codegen
  7080. * @param {string} [functionName] Function name if not anonymous
  7081. * @returns {Codegen} Appender that appends code to the function's body
  7082. * @variation 2
  7083. */
  7084. /**
  7085. * When set to `true`, codegen will log generated code to console. Useful for debugging.
  7086. * @name util.codegen.verbose
  7087. * @type {boolean}
  7088. */
  7089. codegen.verbose = false;
  7090. function safeFunctionName(name) {
  7091. if (!name)
  7092. return "";
  7093. name = String(name).replace(/[^\w$]/g, "");
  7094. if (!name)
  7095. return "";
  7096. if (/^\d/.test(name))
  7097. name = "_" + name;
  7098. return reservedRe.test(name) ? name + "_" : name;
  7099. }
  7100. },{"39":39}],32:[function(require,module,exports){
  7101. "use strict";
  7102. module.exports = EventEmitter;
  7103. /**
  7104. * Constructs a new event emitter instance.
  7105. * @classdesc A minimal event emitter.
  7106. * @memberof util
  7107. * @constructor
  7108. */
  7109. function EventEmitter() {
  7110. /**
  7111. * Registered listeners.
  7112. * @type {Object.<string,*>}
  7113. * @private
  7114. */
  7115. this._listeners = Object.create(null);
  7116. }
  7117. /**
  7118. * Event listener as used by {@link util.EventEmitter}.
  7119. * @typedef EventEmitterListener
  7120. * @type {function}
  7121. * @param {...*} args Arguments
  7122. * @returns {undefined}
  7123. */
  7124. /**
  7125. * Registers an event listener.
  7126. * @param {string} evt Event name
  7127. * @param {EventEmitterListener} fn Listener
  7128. * @param {*} [ctx] Listener context
  7129. * @returns {this} `this`
  7130. */
  7131. EventEmitter.prototype.on = function on(evt, fn, ctx) {
  7132. (this._listeners[evt] || (this._listeners[evt] = [])).push({
  7133. fn : fn,
  7134. ctx : ctx || this
  7135. });
  7136. return this;
  7137. };
  7138. /**
  7139. * Removes an event listener or any matching listeners if arguments are omitted.
  7140. * @param {string} [evt] Event name. Removes all listeners if omitted.
  7141. * @param {EventEmitterListener} [fn] Listener to remove. Removes all listeners of `evt` if omitted.
  7142. * @returns {this} `this`
  7143. */
  7144. EventEmitter.prototype.off = function off(evt, fn) {
  7145. if (evt === undefined)
  7146. this._listeners = Object.create(null);
  7147. else {
  7148. if (fn === undefined)
  7149. this._listeners[evt] = [];
  7150. else {
  7151. var listeners = this._listeners[evt];
  7152. if (!listeners)
  7153. return this;
  7154. for (var i = 0; i < listeners.length;)
  7155. if (listeners[i].fn === fn)
  7156. listeners.splice(i, 1);
  7157. else
  7158. ++i;
  7159. }
  7160. }
  7161. return this;
  7162. };
  7163. /**
  7164. * Emits an event by calling its listeners with the specified arguments.
  7165. * @param {string} evt Event name
  7166. * @param {...*} args Arguments
  7167. * @returns {this} `this`
  7168. */
  7169. EventEmitter.prototype.emit = function emit(evt) {
  7170. var listeners = this._listeners[evt];
  7171. if (listeners) {
  7172. var args = [],
  7173. i = 1;
  7174. for (; i < arguments.length;)
  7175. args.push(arguments[i++]);
  7176. for (i = 0; i < listeners.length;)
  7177. listeners[i].fn.apply(listeners[i++].ctx, args);
  7178. }
  7179. return this;
  7180. };
  7181. },{}],33:[function(require,module,exports){
  7182. "use strict";
  7183. module.exports = fetch;
  7184. var asPromise = require(29),
  7185. fs = require(35);
  7186. /**
  7187. * Node-style callback as used by {@link util.fetch}.
  7188. * @typedef FetchCallback
  7189. * @type {function}
  7190. * @param {?Error} error Error, if any, otherwise `null`
  7191. * @param {string} [contents] File contents, if there hasn't been an error
  7192. * @returns {undefined}
  7193. */
  7194. /**
  7195. * Options as used by {@link util.fetch}.
  7196. * @interface IFetchOptions
  7197. * @property {boolean} [binary=false] Whether expecting a binary response
  7198. * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest
  7199. */
  7200. /**
  7201. * Fetches the contents of a file.
  7202. * @memberof util
  7203. * @param {string} filename File path or url
  7204. * @param {IFetchOptions} options Fetch options
  7205. * @param {FetchCallback} callback Callback function
  7206. * @returns {undefined}
  7207. */
  7208. function fetch(filename, options, callback) {
  7209. if (typeof options === "function") {
  7210. callback = options;
  7211. options = {};
  7212. } else if (!options)
  7213. options = {};
  7214. if (!callback)
  7215. return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this
  7216. // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.
  7217. if (!options.xhr && fs && fs.readFile)
  7218. return fs.readFile(filename, function fetchReadFileCallback(err, contents) {
  7219. return err && typeof XMLHttpRequest !== "undefined"
  7220. ? fetch.xhr(filename, options, callback)
  7221. : err
  7222. ? callback(err)
  7223. : callback(null, options.binary ? contents : contents.toString("utf8"));
  7224. });
  7225. // use the XHR version otherwise.
  7226. return fetch.xhr(filename, options, callback);
  7227. }
  7228. /**
  7229. * Fetches the contents of a file.
  7230. * @name util.fetch
  7231. * @function
  7232. * @param {string} path File path or url
  7233. * @param {FetchCallback} callback Callback function
  7234. * @returns {undefined}
  7235. * @variation 2
  7236. */
  7237. /**
  7238. * Fetches the contents of a file.
  7239. * @name util.fetch
  7240. * @function
  7241. * @param {string} path File path or url
  7242. * @param {IFetchOptions} [options] Fetch options
  7243. * @returns {Promise<string|Uint8Array>} Promise
  7244. * @variation 3
  7245. */
  7246. /**/
  7247. fetch.xhr = function fetch_xhr(filename, options, callback) {
  7248. var xhr = new XMLHttpRequest();
  7249. xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {
  7250. if (xhr.readyState !== 4)
  7251. return undefined;
  7252. // local cors security errors return status 0 / empty string, too. afaik this cannot be
  7253. // reliably distinguished from an actually empty file for security reasons. feel free
  7254. // to send a pull request if you are aware of a solution.
  7255. if (xhr.status !== 0 && xhr.status !== 200)
  7256. return callback(Error("status " + xhr.status));
  7257. // if binary data is expected, make sure that some sort of array is returned, even if
  7258. // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.
  7259. if (options.binary) {
  7260. var buffer = xhr.response;
  7261. if (!buffer) {
  7262. buffer = [];
  7263. for (var i = 0; i < xhr.responseText.length; ++i)
  7264. buffer.push(xhr.responseText.charCodeAt(i) & 255);
  7265. }
  7266. return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer);
  7267. }
  7268. return callback(null, xhr.responseText);
  7269. };
  7270. if (options.binary) {
  7271. // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers
  7272. if ("overrideMimeType" in xhr)
  7273. xhr.overrideMimeType("text/plain; charset=x-user-defined");
  7274. xhr.responseType = "arraybuffer";
  7275. }
  7276. xhr.open("GET", filename);
  7277. xhr.send();
  7278. };
  7279. },{"29":29,"35":35}],34:[function(require,module,exports){
  7280. "use strict";
  7281. module.exports = factory(factory);
  7282. /**
  7283. * Reads / writes floats / doubles from / to buffers.
  7284. * @name util.float
  7285. * @namespace
  7286. */
  7287. /**
  7288. * Writes a 32 bit float to a buffer using little endian byte order.
  7289. * @name util.float.writeFloatLE
  7290. * @function
  7291. * @param {number} val Value to write
  7292. * @param {Uint8Array} buf Target buffer
  7293. * @param {number} pos Target buffer offset
  7294. * @returns {undefined}
  7295. */
  7296. /**
  7297. * Writes a 32 bit float to a buffer using big endian byte order.
  7298. * @name util.float.writeFloatBE
  7299. * @function
  7300. * @param {number} val Value to write
  7301. * @param {Uint8Array} buf Target buffer
  7302. * @param {number} pos Target buffer offset
  7303. * @returns {undefined}
  7304. */
  7305. /**
  7306. * Reads a 32 bit float from a buffer using little endian byte order.
  7307. * @name util.float.readFloatLE
  7308. * @function
  7309. * @param {Uint8Array} buf Source buffer
  7310. * @param {number} pos Source buffer offset
  7311. * @returns {number} Value read
  7312. */
  7313. /**
  7314. * Reads a 32 bit float from a buffer using big endian byte order.
  7315. * @name util.float.readFloatBE
  7316. * @function
  7317. * @param {Uint8Array} buf Source buffer
  7318. * @param {number} pos Source buffer offset
  7319. * @returns {number} Value read
  7320. */
  7321. /**
  7322. * Writes a 64 bit double to a buffer using little endian byte order.
  7323. * @name util.float.writeDoubleLE
  7324. * @function
  7325. * @param {number} val Value to write
  7326. * @param {Uint8Array} buf Target buffer
  7327. * @param {number} pos Target buffer offset
  7328. * @returns {undefined}
  7329. */
  7330. /**
  7331. * Writes a 64 bit double to a buffer using big endian byte order.
  7332. * @name util.float.writeDoubleBE
  7333. * @function
  7334. * @param {number} val Value to write
  7335. * @param {Uint8Array} buf Target buffer
  7336. * @param {number} pos Target buffer offset
  7337. * @returns {undefined}
  7338. */
  7339. /**
  7340. * Reads a 64 bit double from a buffer using little endian byte order.
  7341. * @name util.float.readDoubleLE
  7342. * @function
  7343. * @param {Uint8Array} buf Source buffer
  7344. * @param {number} pos Source buffer offset
  7345. * @returns {number} Value read
  7346. */
  7347. /**
  7348. * Reads a 64 bit double from a buffer using big endian byte order.
  7349. * @name util.float.readDoubleBE
  7350. * @function
  7351. * @param {Uint8Array} buf Source buffer
  7352. * @param {number} pos Source buffer offset
  7353. * @returns {number} Value read
  7354. */
  7355. // Factory function for the purpose of node-based testing in modified global environments
  7356. function factory(exports) {
  7357. // float: typed array
  7358. if (typeof Float32Array !== "undefined") (function() {
  7359. var f32 = new Float32Array([ -0 ]),
  7360. f8b = new Uint8Array(f32.buffer),
  7361. le = f8b[3] === 128;
  7362. function writeFloat_f32_cpy(val, buf, pos) {
  7363. f32[0] = val;
  7364. buf[pos ] = f8b[0];
  7365. buf[pos + 1] = f8b[1];
  7366. buf[pos + 2] = f8b[2];
  7367. buf[pos + 3] = f8b[3];
  7368. }
  7369. function writeFloat_f32_rev(val, buf, pos) {
  7370. f32[0] = val;
  7371. buf[pos ] = f8b[3];
  7372. buf[pos + 1] = f8b[2];
  7373. buf[pos + 2] = f8b[1];
  7374. buf[pos + 3] = f8b[0];
  7375. }
  7376. /* istanbul ignore next */
  7377. exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
  7378. /* istanbul ignore next */
  7379. exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;
  7380. function readFloat_f32_cpy(buf, pos) {
  7381. f8b[0] = buf[pos ];
  7382. f8b[1] = buf[pos + 1];
  7383. f8b[2] = buf[pos + 2];
  7384. f8b[3] = buf[pos + 3];
  7385. return f32[0];
  7386. }
  7387. function readFloat_f32_rev(buf, pos) {
  7388. f8b[3] = buf[pos ];
  7389. f8b[2] = buf[pos + 1];
  7390. f8b[1] = buf[pos + 2];
  7391. f8b[0] = buf[pos + 3];
  7392. return f32[0];
  7393. }
  7394. /* istanbul ignore next */
  7395. exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
  7396. /* istanbul ignore next */
  7397. exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;
  7398. // float: ieee754
  7399. })(); else (function() {
  7400. function writeFloat_ieee754(writeUint, val, buf, pos) {
  7401. var sign = val < 0 ? 1 : 0;
  7402. if (sign)
  7403. val = -val;
  7404. if (val === 0)
  7405. writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);
  7406. else if (isNaN(val))
  7407. writeUint(2143289344, buf, pos);
  7408. else if (val > 3.4028234663852886e+38) // +-Infinity
  7409. writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
  7410. else if (val < 1.1754943508222875e-38) // denormal
  7411. writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);
  7412. else {
  7413. var exponent = Math.floor(Math.log(val) / Math.LN2),
  7414. mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
  7415. writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);
  7416. }
  7417. }
  7418. exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
  7419. exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);
  7420. function readFloat_ieee754(readUint, buf, pos) {
  7421. var uint = readUint(buf, pos),
  7422. sign = (uint >> 31) * 2 + 1,
  7423. exponent = uint >>> 23 & 255,
  7424. mantissa = uint & 8388607;
  7425. return exponent === 255
  7426. ? mantissa
  7427. ? NaN
  7428. : sign * Infinity
  7429. : exponent === 0 // denormal
  7430. ? sign * 1.401298464324817e-45 * mantissa
  7431. : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
  7432. }
  7433. exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
  7434. exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);
  7435. })();
  7436. // double: typed array
  7437. if (typeof Float64Array !== "undefined") (function() {
  7438. var f64 = new Float64Array([-0]),
  7439. f8b = new Uint8Array(f64.buffer),
  7440. le = f8b[7] === 128;
  7441. function writeDouble_f64_cpy(val, buf, pos) {
  7442. f64[0] = val;
  7443. buf[pos ] = f8b[0];
  7444. buf[pos + 1] = f8b[1];
  7445. buf[pos + 2] = f8b[2];
  7446. buf[pos + 3] = f8b[3];
  7447. buf[pos + 4] = f8b[4];
  7448. buf[pos + 5] = f8b[5];
  7449. buf[pos + 6] = f8b[6];
  7450. buf[pos + 7] = f8b[7];
  7451. }
  7452. function writeDouble_f64_rev(val, buf, pos) {
  7453. f64[0] = val;
  7454. buf[pos ] = f8b[7];
  7455. buf[pos + 1] = f8b[6];
  7456. buf[pos + 2] = f8b[5];
  7457. buf[pos + 3] = f8b[4];
  7458. buf[pos + 4] = f8b[3];
  7459. buf[pos + 5] = f8b[2];
  7460. buf[pos + 6] = f8b[1];
  7461. buf[pos + 7] = f8b[0];
  7462. }
  7463. /* istanbul ignore next */
  7464. exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
  7465. /* istanbul ignore next */
  7466. exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;
  7467. function readDouble_f64_cpy(buf, pos) {
  7468. f8b[0] = buf[pos ];
  7469. f8b[1] = buf[pos + 1];
  7470. f8b[2] = buf[pos + 2];
  7471. f8b[3] = buf[pos + 3];
  7472. f8b[4] = buf[pos + 4];
  7473. f8b[5] = buf[pos + 5];
  7474. f8b[6] = buf[pos + 6];
  7475. f8b[7] = buf[pos + 7];
  7476. return f64[0];
  7477. }
  7478. function readDouble_f64_rev(buf, pos) {
  7479. f8b[7] = buf[pos ];
  7480. f8b[6] = buf[pos + 1];
  7481. f8b[5] = buf[pos + 2];
  7482. f8b[4] = buf[pos + 3];
  7483. f8b[3] = buf[pos + 4];
  7484. f8b[2] = buf[pos + 5];
  7485. f8b[1] = buf[pos + 6];
  7486. f8b[0] = buf[pos + 7];
  7487. return f64[0];
  7488. }
  7489. /* istanbul ignore next */
  7490. exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
  7491. /* istanbul ignore next */
  7492. exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;
  7493. // double: ieee754
  7494. })(); else (function() {
  7495. function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {
  7496. var sign = val < 0 ? 1 : 0;
  7497. if (sign)
  7498. val = -val;
  7499. if (val === 0) {
  7500. writeUint(0, buf, pos + off0);
  7501. writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);
  7502. } else if (isNaN(val)) {
  7503. writeUint(0, buf, pos + off0);
  7504. writeUint(2146959360, buf, pos + off1);
  7505. } else if (val > 1.7976931348623157e+308) { // +-Infinity
  7506. writeUint(0, buf, pos + off0);
  7507. writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
  7508. } else {
  7509. var mantissa;
  7510. if (val < 2.2250738585072014e-308) { // denormal
  7511. mantissa = val / 5e-324;
  7512. writeUint(mantissa >>> 0, buf, pos + off0);
  7513. writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);
  7514. } else {
  7515. var exponent = Math.floor(Math.log(val) / Math.LN2);
  7516. if (exponent === 1024)
  7517. exponent = 1023;
  7518. mantissa = val * Math.pow(2, -exponent);
  7519. writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);
  7520. writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);
  7521. }
  7522. }
  7523. }
  7524. exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
  7525. exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);
  7526. function readDouble_ieee754(readUint, off0, off1, buf, pos) {
  7527. var lo = readUint(buf, pos + off0),
  7528. hi = readUint(buf, pos + off1);
  7529. var sign = (hi >> 31) * 2 + 1,
  7530. exponent = hi >>> 20 & 2047,
  7531. mantissa = 4294967296 * (hi & 1048575) + lo;
  7532. return exponent === 2047
  7533. ? mantissa
  7534. ? NaN
  7535. : sign * Infinity
  7536. : exponent === 0 // denormal
  7537. ? sign * 5e-324 * mantissa
  7538. : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
  7539. }
  7540. exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
  7541. exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
  7542. })();
  7543. return exports;
  7544. }
  7545. // uint helpers
  7546. function writeUintLE(val, buf, pos) {
  7547. buf[pos ] = val & 255;
  7548. buf[pos + 1] = val >>> 8 & 255;
  7549. buf[pos + 2] = val >>> 16 & 255;
  7550. buf[pos + 3] = val >>> 24;
  7551. }
  7552. function writeUintBE(val, buf, pos) {
  7553. buf[pos ] = val >>> 24;
  7554. buf[pos + 1] = val >>> 16 & 255;
  7555. buf[pos + 2] = val >>> 8 & 255;
  7556. buf[pos + 3] = val & 255;
  7557. }
  7558. function readUintLE(buf, pos) {
  7559. return (buf[pos ]
  7560. | buf[pos + 1] << 8
  7561. | buf[pos + 2] << 16
  7562. | buf[pos + 3] << 24) >>> 0;
  7563. }
  7564. function readUintBE(buf, pos) {
  7565. return (buf[pos ] << 24
  7566. | buf[pos + 1] << 16
  7567. | buf[pos + 2] << 8
  7568. | buf[pos + 3]) >>> 0;
  7569. }
  7570. },{}],35:[function(require,module,exports){
  7571. "use strict";
  7572. var fs = null;
  7573. try {
  7574. fs = require(1);
  7575. if (!fs || !fs.readFile || !fs.readFileSync)
  7576. fs = null;
  7577. } catch (e) {
  7578. // `fs` is unavailable in browsers and browser-like bundles.
  7579. }
  7580. module.exports = fs;
  7581. },{"1":1}],36:[function(require,module,exports){
  7582. "use strict";
  7583. module.exports = LongBits;
  7584. var util = require(37);
  7585. /**
  7586. * Constructs new long bits.
  7587. * @classdesc Helper class for working with the low and high bits of a 64 bit value.
  7588. * @memberof util
  7589. * @constructor
  7590. * @param {number} lo Low 32 bits, unsigned
  7591. * @param {number} hi High 32 bits, unsigned
  7592. */
  7593. function LongBits(lo, hi) {
  7594. // note that the casts below are theoretically unnecessary as of today, but older statically
  7595. // generated converter code might still call the ctor with signed 32bits. kept for compat.
  7596. /**
  7597. * Low bits.
  7598. * @type {number}
  7599. */
  7600. this.lo = lo >>> 0;
  7601. /**
  7602. * High bits.
  7603. * @type {number}
  7604. */
  7605. this.hi = hi >>> 0;
  7606. }
  7607. /**
  7608. * Zero bits.
  7609. * @memberof util.LongBits
  7610. * @type {util.LongBits}
  7611. */
  7612. var zero = LongBits.zero = new LongBits(0, 0);
  7613. zero.toNumber = function() { return 0; };
  7614. zero.zzEncode = zero.zzDecode = function() { return this; };
  7615. zero.length = function() { return 1; };
  7616. /**
  7617. * Zero hash.
  7618. * @memberof util.LongBits
  7619. * @type {string}
  7620. */
  7621. var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";
  7622. /**
  7623. * Constructs new long bits from the specified number.
  7624. * @param {number} value Value
  7625. * @returns {util.LongBits} Instance
  7626. */
  7627. LongBits.fromNumber = function fromNumber(value) {
  7628. if (value === 0)
  7629. return zero;
  7630. var sign = value < 0;
  7631. if (sign)
  7632. value = -value;
  7633. var lo = value >>> 0,
  7634. hi = (value - lo) / 4294967296 >>> 0;
  7635. if (sign) {
  7636. hi = ~hi >>> 0;
  7637. lo = ~lo >>> 0;
  7638. if (++lo > 4294967295) {
  7639. lo = 0;
  7640. if (++hi > 4294967295)
  7641. hi = 0;
  7642. }
  7643. }
  7644. return new LongBits(lo, hi);
  7645. };
  7646. /**
  7647. * Constructs new long bits from a number, long or string.
  7648. * @param {Long|number|string} value Value
  7649. * @returns {util.LongBits} Instance
  7650. */
  7651. LongBits.from = function from(value) {
  7652. if (typeof value === "number")
  7653. return LongBits.fromNumber(value);
  7654. if (util.isString(value)) {
  7655. /* istanbul ignore else */
  7656. if (util.Long)
  7657. value = util.Long.fromString(value);
  7658. else
  7659. return LongBits.fromNumber(parseInt(value, 10));
  7660. }
  7661. return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
  7662. };
  7663. /**
  7664. * Converts this long bits to a possibly unsafe JavaScript number.
  7665. * @param {boolean} [unsigned=false] Whether unsigned or not
  7666. * @returns {number} Possibly unsafe number
  7667. */
  7668. LongBits.prototype.toNumber = function toNumber(unsigned) {
  7669. if (!unsigned && this.hi >>> 31) {
  7670. var lo = ~this.lo + 1 >>> 0,
  7671. hi = ~this.hi >>> 0;
  7672. if (!lo)
  7673. hi = hi + 1 >>> 0;
  7674. return -(lo + hi * 4294967296);
  7675. }
  7676. return this.lo + this.hi * 4294967296;
  7677. };
  7678. /**
  7679. * Converts this long bits to a long.
  7680. * @param {boolean} [unsigned=false] Whether unsigned or not
  7681. * @returns {Long} Long
  7682. */
  7683. LongBits.prototype.toLong = function toLong(unsigned) {
  7684. return util.Long
  7685. ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
  7686. /* istanbul ignore next */
  7687. : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
  7688. };
  7689. var charCodeAt = String.prototype.charCodeAt;
  7690. /**
  7691. * Constructs new long bits from the specified 8 characters long hash.
  7692. * @param {string} hash Hash
  7693. * @returns {util.LongBits} Bits
  7694. */
  7695. LongBits.fromHash = function fromHash(hash) {
  7696. if (hash === zeroHash)
  7697. return zero;
  7698. return new LongBits(
  7699. ( charCodeAt.call(hash, 0)
  7700. | charCodeAt.call(hash, 1) << 8
  7701. | charCodeAt.call(hash, 2) << 16
  7702. | charCodeAt.call(hash, 3) << 24) >>> 0
  7703. ,
  7704. ( charCodeAt.call(hash, 4)
  7705. | charCodeAt.call(hash, 5) << 8
  7706. | charCodeAt.call(hash, 6) << 16
  7707. | charCodeAt.call(hash, 7) << 24) >>> 0
  7708. );
  7709. };
  7710. /**
  7711. * Converts this long bits to a 8 characters long hash.
  7712. * @returns {string} Hash
  7713. */
  7714. LongBits.prototype.toHash = function toHash() {
  7715. return String.fromCharCode(
  7716. this.lo & 255,
  7717. this.lo >>> 8 & 255,
  7718. this.lo >>> 16 & 255,
  7719. this.lo >>> 24 ,
  7720. this.hi & 255,
  7721. this.hi >>> 8 & 255,
  7722. this.hi >>> 16 & 255,
  7723. this.hi >>> 24
  7724. );
  7725. };
  7726. /**
  7727. * Zig-zag encodes this long bits.
  7728. * @returns {util.LongBits} `this`
  7729. */
  7730. LongBits.prototype.zzEncode = function zzEncode() {
  7731. var mask = this.hi >> 31;
  7732. this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
  7733. this.lo = ( this.lo << 1 ^ mask) >>> 0;
  7734. return this;
  7735. };
  7736. /**
  7737. * Zig-zag decodes this long bits.
  7738. * @returns {util.LongBits} `this`
  7739. */
  7740. LongBits.prototype.zzDecode = function zzDecode() {
  7741. var mask = -(this.lo & 1);
  7742. this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
  7743. this.hi = ( this.hi >>> 1 ^ mask) >>> 0;
  7744. return this;
  7745. };
  7746. /**
  7747. * Calculates the length of this longbits when encoded as a varint.
  7748. * @returns {number} Length
  7749. */
  7750. LongBits.prototype.length = function length() {
  7751. var part0 = this.lo,
  7752. part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,
  7753. part2 = this.hi >>> 24;
  7754. return part2 === 0
  7755. ? part1 === 0
  7756. ? part0 < 16384
  7757. ? part0 < 128 ? 1 : 2
  7758. : part0 < 2097152 ? 3 : 4
  7759. : part1 < 16384
  7760. ? part1 < 128 ? 5 : 6
  7761. : part1 < 2097152 ? 7 : 8
  7762. : part2 < 128 ? 9 : 10;
  7763. };
  7764. },{"37":37}],37:[function(require,module,exports){
  7765. "use strict";
  7766. var util = exports;
  7767. // used to return a Promise where callback is omitted
  7768. util.asPromise = require(29);
  7769. // converts to / from base64 encoded strings
  7770. util.base64 = require(30);
  7771. // base class of rpc.Service
  7772. util.EventEmitter = require(32);
  7773. // float handling accross browsers
  7774. util.float = require(34);
  7775. // converts to / from utf8 encoded strings
  7776. util.utf8 = require(41);
  7777. // provides a node-like buffer pool in the browser
  7778. util.pool = require(40);
  7779. // utility to work with the low and high bits of a 64 bit value
  7780. util.LongBits = require(36);
  7781. /**
  7782. * Tests if the specified key can affect object prototypes.
  7783. * @memberof util
  7784. * @param {string} key Key to test
  7785. * @returns {boolean} `true` if the key is unsafe
  7786. */
  7787. function isUnsafeProperty(key) {
  7788. return key === "__proto__" || key === "prototype" || key === "constructor";
  7789. }
  7790. util.isUnsafeProperty = isUnsafeProperty;
  7791. /**
  7792. * Whether running within node or not.
  7793. * @memberof util
  7794. * @type {boolean}
  7795. */
  7796. util.isNode = Boolean(typeof global !== "undefined"
  7797. && global
  7798. && global.process
  7799. && global.process.versions
  7800. && global.process.versions.node);
  7801. /**
  7802. * Global object reference.
  7803. * @memberof util
  7804. * @type {Object}
  7805. */
  7806. util.global = util.isNode && global
  7807. || typeof window !== "undefined" && window
  7808. || typeof self !== "undefined" && self
  7809. || this; // eslint-disable-line no-invalid-this
  7810. /**
  7811. * An immuable empty array.
  7812. * @memberof util
  7813. * @type {Array.<*>}
  7814. * @const
  7815. */
  7816. util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes
  7817. /**
  7818. * An immutable empty object.
  7819. * @type {Object}
  7820. * @const
  7821. */
  7822. util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes
  7823. /**
  7824. * Tests if the specified value is an integer.
  7825. * @function
  7826. * @param {*} value Value to test
  7827. * @returns {boolean} `true` if the value is an integer
  7828. */
  7829. util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {
  7830. return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
  7831. };
  7832. /**
  7833. * Tests if the specified value is a string.
  7834. * @param {*} value Value to test
  7835. * @returns {boolean} `true` if the value is a string
  7836. */
  7837. util.isString = function isString(value) {
  7838. return typeof value === "string" || value instanceof String;
  7839. };
  7840. /**
  7841. * Tests if the specified value is a non-null object.
  7842. * @param {*} value Value to test
  7843. * @returns {boolean} `true` if the value is a non-null object
  7844. */
  7845. util.isObject = function isObject(value) {
  7846. return value && typeof value === "object";
  7847. };
  7848. /**
  7849. * Checks if a property on a message is considered to be present.
  7850. * This is an alias of {@link util.isSet}.
  7851. * @function
  7852. * @param {Object} obj Plain object or message instance
  7853. * @param {string} prop Property name
  7854. * @returns {boolean} `true` if considered to be present, otherwise `false`
  7855. */
  7856. util.isset =
  7857. /**
  7858. * Checks if a property on a message is considered to be present.
  7859. * @param {Object} obj Plain object or message instance
  7860. * @param {string} prop Property name
  7861. * @returns {boolean} `true` if considered to be present, otherwise `false`
  7862. */
  7863. util.isSet = function isSet(obj, prop) {
  7864. var value = obj[prop];
  7865. if (value != null && Object.hasOwnProperty.call(obj, prop)) // eslint-disable-line eqeqeq
  7866. return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
  7867. return false;
  7868. };
  7869. /**
  7870. * Any compatible Buffer instance.
  7871. * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
  7872. * @interface Buffer
  7873. * @extends Uint8Array
  7874. */
  7875. /**
  7876. * Node's Buffer class if available.
  7877. * @type {Constructor<Buffer>}
  7878. */
  7879. util.Buffer = (function() {
  7880. try {
  7881. var Buffer = util.global.Buffer;
  7882. // refuse to use non-node buffers if not explicitly assigned (perf reasons):
  7883. return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;
  7884. } catch (e) {
  7885. /* istanbul ignore next */
  7886. return null;
  7887. }
  7888. })();
  7889. // Internal alias of or polyfull for Buffer.from.
  7890. util._Buffer_from = null;
  7891. // Internal alias of or polyfill for Buffer.allocUnsafe.
  7892. util._Buffer_allocUnsafe = null;
  7893. /**
  7894. * Creates a new buffer of whatever type supported by the environment.
  7895. * @param {number|number[]} [sizeOrArray=0] Buffer size or number array
  7896. * @returns {Uint8Array|Buffer} Buffer
  7897. */
  7898. util.newBuffer = function newBuffer(sizeOrArray) {
  7899. /* istanbul ignore next */
  7900. return typeof sizeOrArray === "number"
  7901. ? util.Buffer
  7902. ? util._Buffer_allocUnsafe(sizeOrArray)
  7903. : new util.Array(sizeOrArray)
  7904. : util.Buffer
  7905. ? util._Buffer_from(sizeOrArray)
  7906. : typeof Uint8Array === "undefined"
  7907. ? sizeOrArray
  7908. : new Uint8Array(sizeOrArray);
  7909. };
  7910. /**
  7911. * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.
  7912. * @type {Constructor<Uint8Array>}
  7913. */
  7914. util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;
  7915. /**
  7916. * Any compatible Long instance.
  7917. * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
  7918. * @interface Long
  7919. * @property {number} low Low bits
  7920. * @property {number} high High bits
  7921. * @property {boolean} unsigned Whether unsigned or not
  7922. */
  7923. /**
  7924. * Long.js's Long class if available.
  7925. * @type {Constructor<Long>}
  7926. */
  7927. util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long
  7928. || /* istanbul ignore next */ util.global.Long
  7929. || (function() {
  7930. try {
  7931. var Long = require("long");
  7932. return Long && Long.isLong ? Long : null;
  7933. } catch (e) {
  7934. /* istanbul ignore next */
  7935. return null;
  7936. }
  7937. })();
  7938. /**
  7939. * Regular expression used to verify 2 bit (`bool`) map keys.
  7940. * @type {RegExp}
  7941. * @const
  7942. */
  7943. util.key2Re = /^(?:true|false|0|1)$/;
  7944. /**
  7945. * Regular expression used to verify 32 bit (`int32` etc.) map keys.
  7946. * @type {RegExp}
  7947. * @const
  7948. */
  7949. util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
  7950. /**
  7951. * Regular expression used to verify 64 bit (`int64` etc.) map keys.
  7952. * @type {RegExp}
  7953. * @const
  7954. */
  7955. util.key64Re = /^(?:[\x00-\xff]{8}|-?(?:0|[1-9][0-9]*))$/; // eslint-disable-line no-control-regex
  7956. /**
  7957. * Converts a number or long to an 8 characters long hash string.
  7958. * @param {Long|number} value Value to convert
  7959. * @returns {string} Hash
  7960. */
  7961. util.longToHash = function longToHash(value) {
  7962. return value
  7963. ? util.LongBits.from(value).toHash()
  7964. : util.LongBits.zeroHash;
  7965. };
  7966. /**
  7967. * Converts an 8 characters long hash string to a long or number.
  7968. * @param {string} hash Hash
  7969. * @param {boolean} [unsigned=false] Whether unsigned or not
  7970. * @returns {Long|number} Original value
  7971. */
  7972. util.longFromHash = function longFromHash(hash, unsigned) {
  7973. var bits = util.LongBits.fromHash(hash);
  7974. if (util.Long)
  7975. return util.Long.fromBits(bits.lo, bits.hi, unsigned);
  7976. return bits.toNumber(Boolean(unsigned));
  7977. };
  7978. /**
  7979. * Converts a 64 bit key to a long or number if it is an 8 characters long hash string.
  7980. * @param {string} key Map key
  7981. * @param {boolean} [unsigned=false] Whether unsigned or not
  7982. * @returns {Long|number|string} Original value
  7983. */
  7984. util.longFromKey = function longFromKey(key, unsigned) {
  7985. return util.key64Re.test(key) && !util.key32Re.test(key)
  7986. ? util.longFromHash(key, unsigned)
  7987. : key;
  7988. };
  7989. /**
  7990. * Converts a boolean key to a boolean value.
  7991. * @param {string} key Map key
  7992. * @returns {boolean} Boolean value
  7993. */
  7994. util.boolFromKey = function boolFromKey(key) {
  7995. return key === "true" || key === "1";
  7996. };
  7997. /**
  7998. * Merges the properties of the source object into the destination object.
  7999. * @memberof util
  8000. * @param {Object.<string,*>} dst Destination object
  8001. * @param {...(Object.<string,*>|boolean)} src Source objects, optionally followed by an `ifNotSet` flag
  8002. * @returns {Object.<string,*>} Destination object
  8003. */
  8004. function merge(dst) { // used by converters
  8005. var ifNotSet = typeof arguments[arguments.length - 1] === "boolean",
  8006. limit = ifNotSet ? arguments.length - 1 : arguments.length;
  8007. ifNotSet = ifNotSet && arguments[arguments.length - 1];
  8008. for (var a = 1; a < limit; ++a) {
  8009. var src = arguments[a];
  8010. if (!src)
  8011. continue;
  8012. for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
  8013. if (!isUnsafeProperty(keys[i]) && (dst[keys[i]] === undefined || !ifNotSet))
  8014. dst[keys[i]] = src[keys[i]];
  8015. }
  8016. return dst;
  8017. }
  8018. util.merge = merge;
  8019. /**
  8020. * Schema declaration nesting limit.
  8021. * @memberof util
  8022. * @type {number}
  8023. */
  8024. util.nestingLimit = 32; // protoc: MaxMessageDeclarationNestingDepth
  8025. /**
  8026. * Recursion limit.
  8027. * @memberof util
  8028. * @type {number}
  8029. */
  8030. util.recursionLimit = 100; // protoc: CodedInputStream::default_recursion_limit_
  8031. /**
  8032. * Makes a property safe for assignment as an own property.
  8033. * @memberof util
  8034. * @param {Object.<string,*>} obj Object
  8035. * @param {string} key Property key
  8036. * @param {boolean} [enumerable=true] Whether the property should be enumerable
  8037. * @returns {undefined}
  8038. */
  8039. util.makeProp = function makeProp(obj, key, enumerable) {
  8040. if (Object.prototype.hasOwnProperty.call(obj, key))
  8041. return;
  8042. Object.defineProperty(obj, key, {
  8043. enumerable: enumerable === undefined ? true : enumerable,
  8044. configurable: true,
  8045. writable: true
  8046. });
  8047. };
  8048. /**
  8049. * Converts the first character of a string to lower case.
  8050. * @param {string} str String to convert
  8051. * @returns {string} Converted string
  8052. */
  8053. util.lcFirst = function lcFirst(str) {
  8054. return str.charAt(0).toLowerCase() + str.substring(1);
  8055. };
  8056. /**
  8057. * Creates a custom error constructor.
  8058. * @memberof util
  8059. * @param {string} name Error name
  8060. * @returns {Constructor<Error>} Custom error constructor
  8061. */
  8062. function newError(name) {
  8063. function CustomError(message, properties) {
  8064. if (!(this instanceof CustomError))
  8065. return new CustomError(message, properties);
  8066. // Error.call(this, message);
  8067. // ^ just returns a new error instance because the ctor can be called as a function
  8068. Object.defineProperty(this, "message", { get: function() { return message; } });
  8069. /* istanbul ignore next */
  8070. if (Error.captureStackTrace) // node
  8071. Error.captureStackTrace(this, CustomError);
  8072. else
  8073. Object.defineProperty(this, "stack", { value: new Error().stack || "" });
  8074. if (properties)
  8075. merge(this, properties);
  8076. }
  8077. CustomError.prototype = Object.create(Error.prototype, {
  8078. constructor: {
  8079. value: CustomError,
  8080. writable: true,
  8081. enumerable: false,
  8082. configurable: true,
  8083. },
  8084. name: {
  8085. get: function get() { return name; },
  8086. set: undefined,
  8087. enumerable: false,
  8088. // configurable: false would accurately preserve the behavior of
  8089. // the original, but I'm guessing that was not intentional.
  8090. // For an actual error subclass, this property would
  8091. // be configurable.
  8092. configurable: true,
  8093. },
  8094. toString: {
  8095. value: function value() { return this.name + ": " + this.message; },
  8096. writable: true,
  8097. enumerable: false,
  8098. configurable: true,
  8099. },
  8100. });
  8101. return CustomError;
  8102. }
  8103. util.newError = newError;
  8104. /**
  8105. * Constructs a new protocol error.
  8106. * @classdesc Error subclass indicating a protocol specifc error.
  8107. * @memberof util
  8108. * @extends Error
  8109. * @template T extends Message<T>
  8110. * @constructor
  8111. * @param {string} message Error message
  8112. * @param {Object.<string,*>} [properties] Additional properties
  8113. * @example
  8114. * try {
  8115. * MyMessage.decode(someBuffer); // throws if required fields are missing
  8116. * } catch (e) {
  8117. * if (e instanceof ProtocolError && e.instance)
  8118. * console.log("decoded so far: " + JSON.stringify(e.instance));
  8119. * }
  8120. */
  8121. util.ProtocolError = newError("ProtocolError");
  8122. /**
  8123. * So far decoded message instance.
  8124. * @name util.ProtocolError#instance
  8125. * @type {Message<T>}
  8126. */
  8127. /**
  8128. * A OneOf getter as returned by {@link util.oneOfGetter}.
  8129. * @typedef OneOfGetter
  8130. * @type {function}
  8131. * @returns {string|undefined} Set field name, if any
  8132. */
  8133. /**
  8134. * Builds a getter for a oneof's present field name.
  8135. * @param {string[]} fieldNames Field names
  8136. * @returns {OneOfGetter} Unbound getter
  8137. */
  8138. util.oneOfGetter = function getOneOf(fieldNames) {
  8139. var fieldMap = {};
  8140. for (var i = 0; i < fieldNames.length; ++i)
  8141. fieldMap[fieldNames[i]] = 1;
  8142. /**
  8143. * @returns {string|undefined} Set field name, if any
  8144. * @this Object
  8145. * @ignore
  8146. */
  8147. return function() { // eslint-disable-line consistent-return
  8148. for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)
  8149. if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)
  8150. return keys[i];
  8151. };
  8152. };
  8153. /**
  8154. * A OneOf setter as returned by {@link util.oneOfSetter}.
  8155. * @typedef OneOfSetter
  8156. * @type {function}
  8157. * @param {string|undefined} value Field name
  8158. * @returns {undefined}
  8159. */
  8160. /**
  8161. * Builds a setter for a oneof's present field name.
  8162. * @param {string[]} fieldNames Field names
  8163. * @returns {OneOfSetter} Unbound setter
  8164. */
  8165. util.oneOfSetter = function setOneOf(fieldNames) {
  8166. /**
  8167. * @param {string} name Field name
  8168. * @returns {undefined}
  8169. * @this Object
  8170. * @ignore
  8171. */
  8172. return function(name) {
  8173. for (var i = 0; i < fieldNames.length; ++i)
  8174. if (fieldNames[i] !== name)
  8175. delete this[fieldNames[i]];
  8176. };
  8177. };
  8178. /**
  8179. * Default conversion options used for {@link Message#toJSON} implementations.
  8180. *
  8181. * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:
  8182. *
  8183. * - Longs become strings
  8184. * - Enums become string keys
  8185. * - Bytes become base64 encoded strings
  8186. * - (Sub-)Messages become plain objects
  8187. * - Maps become plain objects with all string keys
  8188. * - Repeated fields become arrays
  8189. * - NaN and Infinity for float and double fields become strings
  8190. *
  8191. * @type {IConversionOptions}
  8192. * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json
  8193. */
  8194. util.toJSONOptions = {
  8195. longs: String,
  8196. enums: String,
  8197. bytes: String,
  8198. json: true
  8199. };
  8200. // Sets up buffer utility according to the environment (called in index-minimal)
  8201. util._configure = function() {
  8202. var Buffer = util.Buffer;
  8203. /* istanbul ignore if */
  8204. if (!Buffer) {
  8205. util._Buffer_from = util._Buffer_allocUnsafe = null;
  8206. return;
  8207. }
  8208. // because node 4.x buffers are incompatible & immutable
  8209. // see: https://github.com/dcodeIO/protobuf.js/pull/665
  8210. util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||
  8211. /* istanbul ignore next */
  8212. function Buffer_from(value, encoding) {
  8213. return new Buffer(value, encoding);
  8214. };
  8215. util._Buffer_allocUnsafe = Buffer.allocUnsafe ||
  8216. /* istanbul ignore next */
  8217. function Buffer_allocUnsafe(size) {
  8218. return new Buffer(size);
  8219. };
  8220. };
  8221. },{"29":29,"30":30,"32":32,"34":34,"36":36,"40":40,"41":41,"long":"long"}],38:[function(require,module,exports){
  8222. "use strict";
  8223. /**
  8224. * A minimal path module to resolve Unix, Windows and URL paths alike.
  8225. * @memberof util
  8226. * @namespace
  8227. */
  8228. var path = exports;
  8229. var urlRe = /^[a-zA-Z][a-zA-Z0-9+.-]+:\/\//;
  8230. function normalizeUrl(path) {
  8231. if (typeof URL === "undefined" || !urlRe.test(path))
  8232. return null;
  8233. try {
  8234. return new URL(path).href;
  8235. } catch (e) {
  8236. return null;
  8237. }
  8238. }
  8239. function resolveUrl(originPath, includePath) {
  8240. if (typeof URL === "undefined" || !urlRe.test(originPath) || urlRe.test(includePath))
  8241. return null;
  8242. try {
  8243. return new URL(includePath, originPath).href;
  8244. } catch (e) {
  8245. return null;
  8246. }
  8247. }
  8248. var isAbsolute =
  8249. /**
  8250. * Tests if the specified path is absolute.
  8251. * @param {string} path Path to test
  8252. * @returns {boolean} `true` if path is absolute
  8253. */
  8254. path.isAbsolute = function isAbsolute(path) {
  8255. return /^(?:\/|\w+:|\\\\\w+)/.test(path);
  8256. };
  8257. var normalize =
  8258. /**
  8259. * Normalizes the specified path.
  8260. * @param {string} path Path to normalize
  8261. * @returns {string} Normalized path
  8262. */
  8263. path.normalize = function normalize(path) {
  8264. var normalizedUrl = normalizeUrl(path);
  8265. if (normalizedUrl)
  8266. return normalizedUrl;
  8267. var firstTwoCharacters = path.substring(0,2);
  8268. var uncPrefix = "";
  8269. if (firstTwoCharacters === "\\\\") {
  8270. uncPrefix = firstTwoCharacters;
  8271. path = path.substring(2);
  8272. }
  8273. path = path.replace(/\\/g, "/")
  8274. .replace(/\/{2,}/g, "/");
  8275. var parts = path.split("/"),
  8276. absolute = isAbsolute(path),
  8277. prefix = "";
  8278. if (absolute)
  8279. prefix = parts.shift() + "/";
  8280. for (var i = 0; i < parts.length;) {
  8281. if (parts[i] === "..") {
  8282. if (i > 0 && parts[i - 1] !== "..")
  8283. parts.splice(--i, 2);
  8284. else if (absolute)
  8285. parts.splice(i, 1);
  8286. else
  8287. ++i;
  8288. } else if (parts[i] === ".")
  8289. parts.splice(i, 1);
  8290. else
  8291. ++i;
  8292. }
  8293. return uncPrefix + prefix + parts.join("/");
  8294. };
  8295. /**
  8296. * Resolves the specified include path against the specified origin path.
  8297. * @param {string} originPath Path to the origin file
  8298. * @param {string} includePath Include path relative to origin path
  8299. * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized
  8300. * @returns {string} Path to the include file
  8301. */
  8302. path.resolve = function resolve(originPath, includePath, alreadyNormalized) {
  8303. var resolvedUrl = resolveUrl(originPath, includePath);
  8304. if (resolvedUrl)
  8305. return resolvedUrl;
  8306. if (!alreadyNormalized)
  8307. includePath = normalize(includePath); // path or absolute url
  8308. if (isAbsolute(includePath))
  8309. return includePath;
  8310. if (!alreadyNormalized)
  8311. originPath = normalize(originPath);
  8312. return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath;
  8313. };
  8314. },{}],39:[function(require,module,exports){
  8315. "use strict";
  8316. var patterns = exports;
  8317. patterns.numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/;
  8318. patterns.typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;
  8319. patterns.reservedRe = /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/;
  8320. },{}],40:[function(require,module,exports){
  8321. "use strict";
  8322. module.exports = pool;
  8323. /**
  8324. * An allocator as used by {@link util.pool}.
  8325. * @typedef PoolAllocator
  8326. * @type {function}
  8327. * @param {number} size Buffer size
  8328. * @returns {Uint8Array} Buffer
  8329. */
  8330. /**
  8331. * A slicer as used by {@link util.pool}.
  8332. * @typedef PoolSlicer
  8333. * @type {function}
  8334. * @param {number} start Start offset
  8335. * @param {number} end End offset
  8336. * @returns {Uint8Array} Buffer slice
  8337. * @this Uint8Array
  8338. */
  8339. /**
  8340. * A general purpose buffer pool.
  8341. * @memberof util
  8342. * @function
  8343. * @param {PoolAllocator} alloc Allocator
  8344. * @param {PoolSlicer} slice Slicer
  8345. * @param {number} [size=8192] Slab size
  8346. * @returns {PoolAllocator} Pooled allocator
  8347. */
  8348. function pool(alloc, slice, size) {
  8349. var SIZE = size || 8192;
  8350. var MAX = SIZE >>> 1;
  8351. var slab = null;
  8352. var offset = SIZE;
  8353. return function pool_alloc(size) {
  8354. if (size < 1 || size > MAX)
  8355. return alloc(size);
  8356. if (offset + size > SIZE) {
  8357. slab = alloc(SIZE);
  8358. offset = 0;
  8359. }
  8360. var buf = slice.call(slab, offset, offset += size);
  8361. if (offset & 7) // align to 32 bit
  8362. offset = (offset | 7) + 1;
  8363. return buf;
  8364. };
  8365. }
  8366. },{}],41:[function(require,module,exports){
  8367. "use strict";
  8368. /**
  8369. * A minimal UTF8 implementation for number arrays.
  8370. * @memberof util
  8371. * @namespace
  8372. */
  8373. var utf8 = exports,
  8374. replacementChar = "\ufffd",
  8375. strictDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
  8376. /**
  8377. * Calculates the UTF8 byte length of a string.
  8378. * @param {string} string String
  8379. * @returns {number} Byte length
  8380. */
  8381. utf8.length = function utf8_length(string) {
  8382. var len = 0,
  8383. c = 0;
  8384. for (var i = 0; i < string.length; ++i) {
  8385. c = string.charCodeAt(i);
  8386. if (c < 128)
  8387. len += 1;
  8388. else if (c < 2048)
  8389. len += 2;
  8390. else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
  8391. ++i;
  8392. len += 4;
  8393. } else
  8394. len += 3;
  8395. }
  8396. return len;
  8397. };
  8398. function utf8_read_js(buffer, start, end, str) {
  8399. for (var i = start; i < end;) {
  8400. var t = buffer[i++];
  8401. if (t <= 0x7F) {
  8402. str += String.fromCharCode(t);
  8403. } else if (t >= 0xC0 && t < 0xE0) {
  8404. var c2 = (t & 0x1F) << 6 | buffer[i++] & 0x3F;
  8405. str += c2 >= 0x80 ? String.fromCharCode(c2) : replacementChar;
  8406. } else if (t >= 0xE0 && t < 0xF0) {
  8407. var c3 = (t & 0xF) << 12 | (buffer[i++] & 0x3F) << 6 | buffer[i++] & 0x3F;
  8408. str += c3 >= 0x800 ? String.fromCharCode(c3) : replacementChar;
  8409. } else if (t >= 0xF0) {
  8410. var t2 = (t & 7) << 18 | (buffer[i++] & 0x3F) << 12 | (buffer[i++] & 0x3F) << 6 | buffer[i++] & 0x3F;
  8411. if (t2 < 0x10000 || t2 > 0x10FFFF)
  8412. str += replacementChar;
  8413. else {
  8414. t2 -= 0x10000;
  8415. str += String.fromCharCode(0xD800 + (t2 >> 10));
  8416. str += String.fromCharCode(0xDC00 + (t2 & 0x3FF));
  8417. }
  8418. }
  8419. }
  8420. return str;
  8421. }
  8422. /**
  8423. * Reads UTF8 bytes as a string.
  8424. * @param {Uint8Array} buffer Source buffer
  8425. * @param {number} start Source start
  8426. * @param {number} end Source end
  8427. * @returns {string} String read
  8428. */
  8429. utf8.read = function utf8_read_ascii(buffer, start, end) {
  8430. if (end - start < 1)
  8431. return "";
  8432. var str = "",
  8433. i = start,
  8434. c1, c2, c3, c4, c5, c6, c7, c8;
  8435. for (; i + 7 < end; i += 8) {
  8436. c1 = buffer[i];
  8437. c2 = buffer[i + 1];
  8438. c3 = buffer[i + 2];
  8439. c4 = buffer[i + 3];
  8440. c5 = buffer[i + 4];
  8441. c6 = buffer[i + 5];
  8442. c7 = buffer[i + 6];
  8443. c8 = buffer[i + 7];
  8444. if ((c1 | c2 | c3 | c4 | c5 | c6 | c7 | c8) & 0x80)
  8445. return utf8_read_js(buffer, i, end, str);
  8446. str += String.fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8);
  8447. }
  8448. for (; i < end; ++i) {
  8449. c1 = buffer[i];
  8450. if (c1 & 0x80)
  8451. return utf8_read_js(buffer, i, end, str);
  8452. str += String.fromCharCode(c1);
  8453. }
  8454. return str;
  8455. };
  8456. function utf8_read_strict(buffer, start, end) {
  8457. var source = start === 0 && end === buffer.length
  8458. ? buffer
  8459. : buffer.subarray
  8460. ? buffer.subarray(start, end)
  8461. : buffer.slice(start, end);
  8462. if (Array.isArray(source))
  8463. source = Uint8Array.from(source);
  8464. return strictDecoder.decode(source);
  8465. }
  8466. /**
  8467. * Reads UTF8 bytes as a string, rejecting invalid UTF8.
  8468. * @param {Uint8Array} buffer Source buffer
  8469. * @param {number} start Source start
  8470. * @param {number} end Source end
  8471. * @returns {string} String read
  8472. */
  8473. utf8.readStrict = function utf8_read_strict_ascii(buffer, start, end) {
  8474. if (end - start < 1)
  8475. return "";
  8476. var str = "",
  8477. i = start,
  8478. c1, c2, c3, c4, c5, c6, c7, c8;
  8479. for (; i + 7 < end; i += 8) {
  8480. c1 = buffer[i];
  8481. c2 = buffer[i + 1];
  8482. c3 = buffer[i + 2];
  8483. c4 = buffer[i + 3];
  8484. c5 = buffer[i + 4];
  8485. c6 = buffer[i + 5];
  8486. c7 = buffer[i + 6];
  8487. c8 = buffer[i + 7];
  8488. if ((c1 | c2 | c3 | c4 | c5 | c6 | c7 | c8) & 0x80)
  8489. return str + utf8_read_strict(buffer, i, end);
  8490. str += String.fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8);
  8491. }
  8492. for (; i < end; ++i) {
  8493. c1 = buffer[i];
  8494. if (c1 & 0x80)
  8495. return str + utf8_read_strict(buffer, i, end);
  8496. str += String.fromCharCode(c1);
  8497. }
  8498. return str;
  8499. };
  8500. /**
  8501. * Writes a string as UTF8 bytes.
  8502. * @param {string} string Source string
  8503. * @param {Uint8Array} buffer Destination buffer
  8504. * @param {number} offset Destination offset
  8505. * @returns {number} Bytes written
  8506. */
  8507. utf8.write = function utf8_write(string, buffer, offset) {
  8508. var start = offset,
  8509. c1, // character 1
  8510. c2; // character 2
  8511. for (var i = 0; i < string.length; ++i) {
  8512. c1 = string.charCodeAt(i);
  8513. if (c1 < 128) {
  8514. buffer[offset++] = c1;
  8515. } else if (c1 < 2048) {
  8516. buffer[offset++] = c1 >> 6 | 192;
  8517. buffer[offset++] = c1 & 63 | 128;
  8518. } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
  8519. c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
  8520. ++i;
  8521. buffer[offset++] = c1 >> 18 | 240;
  8522. buffer[offset++] = c1 >> 12 & 63 | 128;
  8523. buffer[offset++] = c1 >> 6 & 63 | 128;
  8524. buffer[offset++] = c1 & 63 | 128;
  8525. } else {
  8526. buffer[offset++] = c1 >> 12 | 224;
  8527. buffer[offset++] = c1 >> 6 & 63 | 128;
  8528. buffer[offset++] = c1 & 63 | 128;
  8529. }
  8530. }
  8531. return offset - start;
  8532. };
  8533. },{}],42:[function(require,module,exports){
  8534. "use strict";
  8535. module.exports = verifier;
  8536. var Enum = require(6),
  8537. util = require(28);
  8538. function invalid(field, expected) {
  8539. return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected";
  8540. }
  8541. /**
  8542. * Generates a partial value verifier.
  8543. * @param {Codegen} gen Codegen instance
  8544. * @param {Field} field Reflected field
  8545. * @param {number} fieldIndex Field index
  8546. * @param {string} ref Variable reference
  8547. * @returns {Codegen} Codegen instance
  8548. * @ignore
  8549. */
  8550. function genVerifyValue(gen, field, fieldIndex, ref) {
  8551. /* eslint-disable no-unexpected-multiline */
  8552. if (field.resolvedType) {
  8553. if (field.resolvedType instanceof Enum) { gen
  8554. ("switch(%s){", ref)
  8555. ("default:")
  8556. ("return%j", invalid(field, "enum value"));
  8557. for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen
  8558. ("case %i:", field.resolvedType.values[keys[j]]);
  8559. gen
  8560. ("break")
  8561. ("}");
  8562. } else {
  8563. gen
  8564. ("{")
  8565. ("var e=types[%i].verify(%s,q+1);", fieldIndex, ref)
  8566. ("if(e)")
  8567. ("return%j+e", field.name + ".")
  8568. ("}");
  8569. }
  8570. } else {
  8571. switch (field.type) {
  8572. case "int32":
  8573. case "uint32":
  8574. case "sint32":
  8575. case "fixed32":
  8576. case "sfixed32": gen
  8577. ("if(!util.isInteger(%s))", ref)
  8578. ("return%j", invalid(field, "integer"));
  8579. break;
  8580. case "int64":
  8581. case "uint64":
  8582. case "sint64":
  8583. case "fixed64":
  8584. case "sfixed64": gen
  8585. ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref)
  8586. ("return%j", invalid(field, "integer|Long"));
  8587. break;
  8588. case "float":
  8589. case "double": gen
  8590. ("if(typeof %s!==\"number\")", ref)
  8591. ("return%j", invalid(field, "number"));
  8592. break;
  8593. case "bool": gen
  8594. ("if(typeof %s!==\"boolean\")", ref)
  8595. ("return%j", invalid(field, "boolean"));
  8596. break;
  8597. case "string": gen
  8598. ("if(!util.isString(%s))", ref)
  8599. ("return%j", invalid(field, "string"));
  8600. break;
  8601. case "bytes": gen
  8602. ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref)
  8603. ("return%j", invalid(field, "buffer"));
  8604. break;
  8605. }
  8606. }
  8607. return gen;
  8608. /* eslint-enable no-unexpected-multiline */
  8609. }
  8610. /**
  8611. * Generates a partial key verifier.
  8612. * @param {Codegen} gen Codegen instance
  8613. * @param {Field} field Reflected field
  8614. * @param {string} ref Variable reference
  8615. * @returns {Codegen} Codegen instance
  8616. * @ignore
  8617. */
  8618. function genVerifyKey(gen, field, ref) {
  8619. /* eslint-disable no-unexpected-multiline */
  8620. switch (field.keyType) {
  8621. case "int32":
  8622. case "uint32":
  8623. case "sint32":
  8624. case "fixed32":
  8625. case "sfixed32": gen
  8626. ("if(!util.key32Re.test(%s))", ref)
  8627. ("return%j", invalid(field, "integer key"));
  8628. break;
  8629. case "int64":
  8630. case "uint64":
  8631. case "sint64":
  8632. case "fixed64":
  8633. case "sfixed64": gen
  8634. ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not
  8635. ("return%j", invalid(field, "integer|Long key"));
  8636. break;
  8637. case "bool": gen
  8638. ("if(!util.key2Re.test(%s))", ref)
  8639. ("return%j", invalid(field, "boolean key"));
  8640. break;
  8641. }
  8642. return gen;
  8643. /* eslint-enable no-unexpected-multiline */
  8644. }
  8645. /**
  8646. * Generates a verifier specific to the specified message type.
  8647. * @param {Type} mtype Message type
  8648. * @returns {Codegen} Codegen instance
  8649. */
  8650. function verifier(mtype) {
  8651. /* eslint-disable no-unexpected-multiline */
  8652. var gen = util.codegen(["m", "q"])
  8653. ("if(typeof m!==\"object\"||m===null)")
  8654. ("return%j", "object expected")
  8655. ("if(q===undefined)q=0")
  8656. ("if(q>util.recursionLimit)")
  8657. ("return%j", "max depth exceeded");
  8658. var oneofs = mtype.oneofsArray,
  8659. seenFirstField = {};
  8660. if (oneofs.length) gen
  8661. ("var p={}");
  8662. for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {
  8663. var field = mtype._fieldsArray[i].resolve(),
  8664. ref = "m" + util.safeProp(field.name);
  8665. if (field.optional) gen
  8666. ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name); // !== undefined && !== null
  8667. // map fields
  8668. if (field.map) { gen
  8669. ("if(!util.isObject(%s))", ref)
  8670. ("return%j", invalid(field, "object"))
  8671. ("var k=Object.keys(%s)", ref)
  8672. ("for(var i=0;i<k.length;++i){");
  8673. genVerifyKey(gen, field, "k[i]");
  8674. genVerifyValue(gen, field, i, ref + "[k[i]]")
  8675. ("}");
  8676. // repeated fields
  8677. } else if (field.repeated) { gen
  8678. ("if(!Array.isArray(%s))", ref)
  8679. ("return%j", invalid(field, "array"))
  8680. ("for(var i=0;i<%s.length;++i){", ref);
  8681. genVerifyValue(gen, field, i, ref + "[i]")
  8682. ("}");
  8683. // required or present fields
  8684. } else {
  8685. if (field.partOf) {
  8686. var oneofProp = util.safeProp(field.partOf.name);
  8687. if (seenFirstField[field.partOf.name] === 1) gen
  8688. ("if(p%s===1)", oneofProp)
  8689. ("return%j", field.partOf.name + ": multiple values");
  8690. seenFirstField[field.partOf.name] = 1;
  8691. gen
  8692. ("p%s=1", oneofProp);
  8693. }
  8694. genVerifyValue(gen, field, i, ref);
  8695. }
  8696. if (field.optional) gen
  8697. ("}");
  8698. }
  8699. return gen
  8700. ("return null");
  8701. /* eslint-enable no-unexpected-multiline */
  8702. }
  8703. },{"28":28,"6":6}],43:[function(require,module,exports){
  8704. "use strict";
  8705. /**
  8706. * Wrappers for common types.
  8707. * @type {Object.<string,IWrapper>}
  8708. * @const
  8709. */
  8710. var wrappers = exports;
  8711. var Message = require(12),
  8712. util = require(37);
  8713. /**
  8714. * From object converter part of an {@link IWrapper}.
  8715. * @typedef WrapperFromObjectConverter
  8716. * @type {function}
  8717. * @param {Object.<string,*>} object Plain object
  8718. * @returns {Message<{}>} Message instance
  8719. * @this Type
  8720. */
  8721. /**
  8722. * To object converter part of an {@link IWrapper}.
  8723. * @typedef WrapperToObjectConverter
  8724. * @type {function}
  8725. * @param {Message<{}>} message Message instance
  8726. * @param {IConversionOptions} [options] Conversion options
  8727. * @returns {Object.<string,*>} Plain object
  8728. * @this Type
  8729. */
  8730. /**
  8731. * Common type wrapper part of {@link wrappers}.
  8732. * @interface IWrapper
  8733. * @property {WrapperFromObjectConverter} [fromObject] From object converter
  8734. * @property {WrapperToObjectConverter} [toObject] To object converter
  8735. */
  8736. // Custom wrapper for Any
  8737. wrappers[".google.protobuf.Any"] = {
  8738. fromObject: function(object, depth) {
  8739. // unwrap value type if mapped
  8740. if (object && object["@type"]) {
  8741. // Only use fully qualified type name after the last '/'
  8742. var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1);
  8743. var type = this.lookup(name);
  8744. /* istanbul ignore else */
  8745. if (type) {
  8746. // type_url does not accept leading "."
  8747. var type_url = object["@type"].charAt(0) === "." ?
  8748. object["@type"].slice(1) : object["@type"];
  8749. // type_url prefix is optional, but path seperator is required
  8750. if (type_url.indexOf("/") === -1) {
  8751. type_url = "/" + type_url;
  8752. }
  8753. return this.create({
  8754. type_url: type_url,
  8755. value: type.encode(type.fromObject(object, depth === undefined ? 1 : depth + 1)).finish()
  8756. });
  8757. }
  8758. }
  8759. return this.fromObject(object, depth);
  8760. },
  8761. toObject: function(message, options, depth) {
  8762. if (depth === undefined)
  8763. depth = 0;
  8764. if (depth > util.recursionLimit)
  8765. throw Error("max depth exceeded");
  8766. // Default prefix
  8767. var googleApi = "type.googleapis.com/";
  8768. var prefix = "";
  8769. var name = "";
  8770. // decode value if requested and unmapped
  8771. if (options && options.json && message.type_url && message.value) {
  8772. // Only use fully qualified type name after the last '/'
  8773. name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);
  8774. // Separate the prefix used
  8775. prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1);
  8776. var type = this.lookup(name);
  8777. /* istanbul ignore else */
  8778. if (type)
  8779. message = type.decode(message.value, undefined, undefined, depth + 1);
  8780. }
  8781. // wrap value if unmapped
  8782. if (!(message instanceof this.ctor) && message instanceof Message) {
  8783. var object = message.$type.toObject(message, options, depth + 1);
  8784. var messageName = message.$type.fullName[0] === "." ?
  8785. message.$type.fullName.slice(1) : message.$type.fullName;
  8786. // Default to type.googleapis.com prefix if no prefix is used
  8787. if (prefix === "") {
  8788. prefix = googleApi;
  8789. }
  8790. name = prefix + messageName;
  8791. object["@type"] = name;
  8792. return object;
  8793. }
  8794. return this.toObject(message, options, depth);
  8795. }
  8796. };
  8797. },{"12":12,"37":37}],44:[function(require,module,exports){
  8798. "use strict";
  8799. module.exports = Writer;
  8800. var util = require(37);
  8801. var BufferWriter; // cyclic
  8802. var LongBits = util.LongBits,
  8803. base64 = util.base64,
  8804. utf8 = util.utf8;
  8805. /**
  8806. * Constructs a new writer operation instance.
  8807. * @classdesc Scheduled writer operation.
  8808. * @constructor
  8809. * @param {function(*, Uint8Array, number)} fn Function to call
  8810. * @param {number} len Value byte length
  8811. * @param {*} val Value to write
  8812. * @ignore
  8813. */
  8814. function Op(fn, len, val) {
  8815. /**
  8816. * Function to call.
  8817. * @type {function(Uint8Array, number, *)}
  8818. */
  8819. this.fn = fn;
  8820. /**
  8821. * Value byte length.
  8822. * @type {number}
  8823. */
  8824. this.len = len;
  8825. /**
  8826. * Next operation.
  8827. * @type {Writer.Op|undefined}
  8828. */
  8829. this.next = undefined;
  8830. /**
  8831. * Value to write.
  8832. * @type {*}
  8833. */
  8834. this.val = val; // type varies
  8835. }
  8836. /* istanbul ignore next */
  8837. function noop() {} // eslint-disable-line no-empty-function
  8838. /**
  8839. * Constructs a new writer state instance.
  8840. * @classdesc Copied writer state.
  8841. * @memberof Writer
  8842. * @constructor
  8843. * @param {Writer} writer Writer to copy state from
  8844. * @ignore
  8845. */
  8846. function State(writer) {
  8847. /**
  8848. * Current head.
  8849. * @type {Writer.Op}
  8850. */
  8851. this.head = writer.head;
  8852. /**
  8853. * Current tail.
  8854. * @type {Writer.Op}
  8855. */
  8856. this.tail = writer.tail;
  8857. /**
  8858. * Current buffer length.
  8859. * @type {number}
  8860. */
  8861. this.len = writer.len;
  8862. /**
  8863. * Next state.
  8864. * @type {State|null}
  8865. */
  8866. this.next = writer.states;
  8867. }
  8868. /**
  8869. * Constructs a new writer instance.
  8870. * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.
  8871. * @constructor
  8872. */
  8873. function Writer() {
  8874. /**
  8875. * Current length.
  8876. * @type {number}
  8877. */
  8878. this.len = 0;
  8879. /**
  8880. * Operations head.
  8881. * @type {Object}
  8882. */
  8883. this.head = new Op(noop, 0, 0);
  8884. /**
  8885. * Operations tail
  8886. * @type {Object}
  8887. */
  8888. this.tail = this.head;
  8889. /**
  8890. * Linked forked states.
  8891. * @type {Object|null}
  8892. */
  8893. this.states = null;
  8894. // When a value is written, the writer calculates its byte length and puts it into a linked
  8895. // list of operations to perform when finish() is called. This both allows us to allocate
  8896. // buffers of the exact required size and reduces the amount of work we have to do compared
  8897. // to first calculating over objects and then encoding over objects. In our case, the encoding
  8898. // part is just a linked list walk calling operations with already prepared values.
  8899. }
  8900. var create = function create() {
  8901. return util.Buffer
  8902. ? function create_buffer_setup() {
  8903. return (Writer.create = function create_buffer() {
  8904. return new BufferWriter();
  8905. })();
  8906. }
  8907. /* istanbul ignore next */
  8908. : function create_array() {
  8909. return new Writer();
  8910. };
  8911. };
  8912. /**
  8913. * Creates a new writer.
  8914. * @function
  8915. * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
  8916. */
  8917. Writer.create = create();
  8918. /**
  8919. * Allocates a buffer of the specified size.
  8920. * @param {number} size Buffer size
  8921. * @returns {Uint8Array} Buffer
  8922. */
  8923. Writer.alloc = function alloc(size) {
  8924. return new util.Array(size);
  8925. };
  8926. // Use Uint8Array buffer pool in the browser, just like node does with buffers
  8927. /* istanbul ignore else */
  8928. if (util.Array !== Array)
  8929. Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);
  8930. /**
  8931. * Pushes a new operation to the queue.
  8932. * @param {function(Uint8Array, number, *)} fn Function to call
  8933. * @param {number} len Value byte length
  8934. * @param {number} val Value to write
  8935. * @returns {Writer} `this`
  8936. * @private
  8937. */
  8938. Writer.prototype._push = function push(fn, len, val) {
  8939. this.tail = this.tail.next = new Op(fn, len, val);
  8940. this.len += len;
  8941. return this;
  8942. };
  8943. function writeByte(val, buf, pos) {
  8944. buf[pos] = val & 255;
  8945. }
  8946. function writeStringAscii(val, buf, pos) {
  8947. for (var i = 0; i < val.length;)
  8948. buf[pos++] = val.charCodeAt(i++);
  8949. }
  8950. function writeVarint32(val, buf, pos) {
  8951. while (val > 127) {
  8952. buf[pos++] = val & 127 | 128;
  8953. val >>>= 7;
  8954. }
  8955. buf[pos] = val;
  8956. }
  8957. /**
  8958. * Constructs a new varint writer operation instance.
  8959. * @classdesc Scheduled varint writer operation.
  8960. * @extends Op
  8961. * @constructor
  8962. * @param {number} len Value byte length
  8963. * @param {number} val Value to write
  8964. * @ignore
  8965. */
  8966. function VarintOp(len, val) {
  8967. this.len = len;
  8968. this.next = undefined;
  8969. this.val = val;
  8970. }
  8971. VarintOp.prototype = Object.create(Op.prototype);
  8972. VarintOp.prototype.fn = writeVarint32;
  8973. /**
  8974. * Writes an unsigned 32 bit value as a varint.
  8975. * @param {number} value Value to write
  8976. * @returns {Writer} `this`
  8977. */
  8978. Writer.prototype.uint32 = function write_uint32(value) {
  8979. // here, the call to this.push has been inlined and a varint specific Op subclass is used.
  8980. // uint32 is by far the most frequently used operation and benefits significantly from this.
  8981. this.len += (this.tail = this.tail.next = new VarintOp(
  8982. (value = value >>> 0)
  8983. < 128 ? 1
  8984. : value < 16384 ? 2
  8985. : value < 2097152 ? 3
  8986. : value < 268435456 ? 4
  8987. : 5,
  8988. value)).len;
  8989. return this;
  8990. };
  8991. /**
  8992. * Writes a signed 32 bit value as a varint.
  8993. * @function
  8994. * @param {number} value Value to write
  8995. * @returns {Writer} `this`
  8996. */
  8997. Writer.prototype.int32 = function write_int32(value) {
  8998. return (value |= 0) < 0
  8999. ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
  9000. : this.uint32(value);
  9001. };
  9002. /**
  9003. * Writes a 32 bit value as a varint, zig-zag encoded.
  9004. * @param {number} value Value to write
  9005. * @returns {Writer} `this`
  9006. */
  9007. Writer.prototype.sint32 = function write_sint32(value) {
  9008. return this.uint32((value << 1 ^ value >> 31) >>> 0);
  9009. };
  9010. function writeVarint64(val, buf, pos) {
  9011. var lo = val.lo,
  9012. hi = val.hi;
  9013. while (hi) {
  9014. buf[pos++] = lo & 127 | 128;
  9015. lo = (lo >>> 7 | hi << 25) >>> 0;
  9016. hi >>>= 7;
  9017. }
  9018. while (lo > 127) {
  9019. buf[pos++] = lo & 127 | 128;
  9020. lo = lo >>> 7;
  9021. }
  9022. buf[pos++] = lo;
  9023. }
  9024. /**
  9025. * Writes an unsigned 64 bit value as a varint.
  9026. * @param {Long|number|string} value Value to write
  9027. * @returns {Writer} `this`
  9028. * @throws {TypeError} If `value` is a string and no long library is present.
  9029. */
  9030. Writer.prototype.uint64 = function write_uint64(value) {
  9031. var bits = LongBits.from(value);
  9032. return this._push(writeVarint64, bits.length(), bits);
  9033. };
  9034. /**
  9035. * Writes a signed 64 bit value as a varint.
  9036. * @function
  9037. * @param {Long|number|string} value Value to write
  9038. * @returns {Writer} `this`
  9039. * @throws {TypeError} If `value` is a string and no long library is present.
  9040. */
  9041. Writer.prototype.int64 = Writer.prototype.uint64;
  9042. /**
  9043. * Writes a signed 64 bit value as a varint, zig-zag encoded.
  9044. * @param {Long|number|string} value Value to write
  9045. * @returns {Writer} `this`
  9046. * @throws {TypeError} If `value` is a string and no long library is present.
  9047. */
  9048. Writer.prototype.sint64 = function write_sint64(value) {
  9049. var bits = LongBits.from(value).zzEncode();
  9050. return this._push(writeVarint64, bits.length(), bits);
  9051. };
  9052. /**
  9053. * Writes a boolish value as a varint.
  9054. * @param {boolean} value Value to write
  9055. * @returns {Writer} `this`
  9056. */
  9057. Writer.prototype.bool = function write_bool(value) {
  9058. return this._push(writeByte, 1, value ? 1 : 0);
  9059. };
  9060. function writeFixed32(val, buf, pos) {
  9061. buf[pos ] = val & 255;
  9062. buf[pos + 1] = val >>> 8 & 255;
  9063. buf[pos + 2] = val >>> 16 & 255;
  9064. buf[pos + 3] = val >>> 24;
  9065. }
  9066. /**
  9067. * Writes an unsigned 32 bit value as fixed 32 bits.
  9068. * @param {number} value Value to write
  9069. * @returns {Writer} `this`
  9070. */
  9071. Writer.prototype.fixed32 = function write_fixed32(value) {
  9072. return this._push(writeFixed32, 4, value >>> 0);
  9073. };
  9074. /**
  9075. * Writes a signed 32 bit value as fixed 32 bits.
  9076. * @function
  9077. * @param {number} value Value to write
  9078. * @returns {Writer} `this`
  9079. */
  9080. Writer.prototype.sfixed32 = Writer.prototype.fixed32;
  9081. /**
  9082. * Writes an unsigned 64 bit value as fixed 64 bits.
  9083. * @param {Long|number|string} value Value to write
  9084. * @returns {Writer} `this`
  9085. * @throws {TypeError} If `value` is a string and no long library is present.
  9086. */
  9087. Writer.prototype.fixed64 = function write_fixed64(value) {
  9088. var bits = LongBits.from(value);
  9089. return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
  9090. };
  9091. /**
  9092. * Writes a signed 64 bit value as fixed 64 bits.
  9093. * @function
  9094. * @param {Long|number|string} value Value to write
  9095. * @returns {Writer} `this`
  9096. * @throws {TypeError} If `value` is a string and no long library is present.
  9097. */
  9098. Writer.prototype.sfixed64 = Writer.prototype.fixed64;
  9099. /**
  9100. * Writes a float (32 bit).
  9101. * @function
  9102. * @param {number} value Value to write
  9103. * @returns {Writer} `this`
  9104. */
  9105. Writer.prototype.float = function write_float(value) {
  9106. return this._push(util.float.writeFloatLE, 4, value);
  9107. };
  9108. /**
  9109. * Writes a double (64 bit float).
  9110. * @function
  9111. * @param {number} value Value to write
  9112. * @returns {Writer} `this`
  9113. */
  9114. Writer.prototype.double = function write_double(value) {
  9115. return this._push(util.float.writeDoubleLE, 8, value);
  9116. };
  9117. var writeBytes = util.Array.prototype.set
  9118. ? function writeBytes_set(val, buf, pos) {
  9119. buf.set(val, pos); // also works for plain array values
  9120. }
  9121. /* istanbul ignore next */
  9122. : function writeBytes_for(val, buf, pos) {
  9123. for (var i = 0; i < val.length; ++i)
  9124. buf[pos + i] = val[i];
  9125. };
  9126. /**
  9127. * Writes a sequence of bytes.
  9128. * @param {Uint8Array|string} value Buffer or base64 encoded string to write
  9129. * @returns {Writer} `this`
  9130. */
  9131. Writer.prototype.bytes = function write_bytes(value) {
  9132. var len = value.length >>> 0;
  9133. if (!len)
  9134. return this._push(writeByte, 1, 0);
  9135. if (util.isString(value)) {
  9136. var buf = Writer.alloc(len = base64.length(value));
  9137. base64.decode(value, buf, 0);
  9138. value = buf;
  9139. }
  9140. return this.uint32(len)._push(writeBytes, len, value);
  9141. };
  9142. /**
  9143. * Writes raw bytes without a tag or length prefix.
  9144. * @param {Uint8Array} value Raw bytes
  9145. * @returns {Writer} `this`
  9146. */
  9147. Writer.prototype.raw = function write_raw(value) {
  9148. var len = value.length >>> 0;
  9149. return len ? this._push(writeBytes, len, value) : this;
  9150. };
  9151. /**
  9152. * Writes a string.
  9153. * @param {string} value Value to write
  9154. * @returns {Writer} `this`
  9155. */
  9156. Writer.prototype.string = function write_string(value) {
  9157. var len = utf8.length(value);
  9158. return len
  9159. ? this.uint32(len)._push(len === value.length ? writeStringAscii : utf8.write, len, value)
  9160. : this._push(writeByte, 1, 0);
  9161. };
  9162. /**
  9163. * Forks this writer's state by pushing it to a stack.
  9164. * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
  9165. * @returns {Writer} `this`
  9166. */
  9167. Writer.prototype.fork = function fork() {
  9168. this.states = new State(this);
  9169. this.head = this.tail = new Op(noop, 0, 0);
  9170. this.len = 0;
  9171. return this;
  9172. };
  9173. /**
  9174. * Resets this instance to the last state.
  9175. * @returns {Writer} `this`
  9176. */
  9177. Writer.prototype.reset = function reset() {
  9178. if (this.states) {
  9179. this.head = this.states.head;
  9180. this.tail = this.states.tail;
  9181. this.len = this.states.len;
  9182. this.states = this.states.next;
  9183. } else {
  9184. this.head = this.tail = new Op(noop, 0, 0);
  9185. this.len = 0;
  9186. }
  9187. return this;
  9188. };
  9189. /**
  9190. * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
  9191. * @returns {Writer} `this`
  9192. */
  9193. Writer.prototype.ldelim = function ldelim() {
  9194. var head = this.head,
  9195. tail = this.tail,
  9196. len = this.len;
  9197. this.reset().uint32(len);
  9198. if (len) {
  9199. this.tail.next = head.next; // skip noop
  9200. this.tail = tail;
  9201. this.len += len;
  9202. }
  9203. return this;
  9204. };
  9205. /**
  9206. * Finishes the write operation.
  9207. * @returns {Uint8Array} Finished buffer
  9208. */
  9209. Writer.prototype.finish = function finish() {
  9210. return this.finishInto(this.constructor.alloc(this.len), 0);
  9211. };
  9212. /**
  9213. * Finishes the write operation, writing into the provided buffer.
  9214. * The caller must ensure that `buf` has enough space starting at `offset`
  9215. * to hold {@link Writer#len} bytes.
  9216. * @param {T} buf Target buffer
  9217. * @param {number} [offset=0] Offset to start writing at
  9218. * @returns {T} The provided buffer
  9219. * @template T extends Uint8Array
  9220. */
  9221. Writer.prototype.finishInto = function finishInto(buf, offset) {
  9222. if (offset === undefined)
  9223. offset = 0;
  9224. var head = this.head.next,
  9225. pos = offset;
  9226. while (head) {
  9227. head.fn(head.val, buf, pos);
  9228. pos += head.len;
  9229. head = head.next;
  9230. }
  9231. return buf;
  9232. };
  9233. Writer._configure = function(BufferWriter_) {
  9234. BufferWriter = BufferWriter_;
  9235. Writer.create = create();
  9236. BufferWriter._configure();
  9237. };
  9238. },{"37":37}],45:[function(require,module,exports){
  9239. "use strict";
  9240. module.exports = BufferWriter;
  9241. // extends Writer
  9242. var Writer = require(44);
  9243. (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
  9244. var util = require(37);
  9245. /**
  9246. * Constructs a new buffer writer instance.
  9247. * @classdesc Wire format writer using node buffers.
  9248. * @extends Writer
  9249. * @constructor
  9250. */
  9251. function BufferWriter() {
  9252. Writer.call(this);
  9253. }
  9254. BufferWriter._configure = function () {
  9255. /**
  9256. * Allocates a buffer of the specified size.
  9257. * @function
  9258. * @param {number} size Buffer size
  9259. * @returns {Buffer} Buffer
  9260. */
  9261. BufferWriter.alloc = util._Buffer_allocUnsafe;
  9262. BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set"
  9263. ? function writeBytesBuffer_set(val, buf, pos) {
  9264. buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
  9265. // also works for plain array values
  9266. }
  9267. /* istanbul ignore next */
  9268. : function writeBytesBuffer_copy(val, buf, pos) {
  9269. if (val.copy) // Buffer values
  9270. val.copy(buf, pos, 0, val.length);
  9271. else for (var i = 0; i < val.length;) // plain array values
  9272. buf[pos++] = val[i++];
  9273. };
  9274. };
  9275. /**
  9276. * @override
  9277. */
  9278. BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
  9279. if (util.isString(value))
  9280. value = util._Buffer_from(value, "base64");
  9281. var len = value.length >>> 0;
  9282. this.uint32(len);
  9283. if (len)
  9284. this._push(BufferWriter.writeBytesBuffer, len, value);
  9285. return this;
  9286. };
  9287. /**
  9288. * Writes raw bytes without a tag or length prefix.
  9289. * @name BufferWriter#raw
  9290. * @function
  9291. * @param {Uint8Array} value Raw bytes
  9292. * @returns {BufferWriter} `this`
  9293. */
  9294. BufferWriter.prototype.raw = function write_raw_buffer(value) {
  9295. var len = value.length >>> 0;
  9296. return len ? this._push(BufferWriter.writeBytesBuffer, len, value) : this;
  9297. };
  9298. function writeStringBufferAscii(val, buf, pos) {
  9299. for (var i = 0; i < val.length;)
  9300. buf[pos++] = val.charCodeAt(i++);
  9301. }
  9302. function writeStringBuffer(val, buf, pos) {
  9303. if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
  9304. util.utf8.write(val, buf, pos);
  9305. else if (buf.utf8Write)
  9306. buf.utf8Write(val, pos);
  9307. else
  9308. buf.write(val, pos);
  9309. }
  9310. /**
  9311. * @override
  9312. */
  9313. BufferWriter.prototype.string = function write_string_buffer(value) {
  9314. var len = util.Buffer.byteLength(value);
  9315. this.uint32(len);
  9316. if (len)
  9317. this._push(len === value.length && len < 40 ? writeStringBufferAscii : writeStringBuffer, len, value);
  9318. return this;
  9319. };
  9320. /**
  9321. * Finishes the write operation.
  9322. * @name BufferWriter#finish
  9323. * @function
  9324. * @returns {Buffer} Finished buffer
  9325. */
  9326. BufferWriter._configure();
  9327. },{"37":37,"44":44}]},{},[10])
  9328. })();
  9329. //# sourceMappingURL=protobuf.js.map